check_expr.cpp 331 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466
  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 Entity * find_polymorphic_record_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> const &ordered_operands, bool *failure);
  73. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  74. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  75. gb_internal gbString expr_to_string (Ast *expression);
  76. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  77. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  78. gb_internal bool check_is_terminating (Ast *node, String const &label);
  79. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  80. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  81. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  82. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  83. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  84. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  85. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  86. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  87. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  88. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  89. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  90. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  91. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  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. enum LoadDirectiveResult {
  104. LoadDirective_Success = 0,
  105. LoadDirective_Error = 1,
  106. LoadDirective_NotFound = 2,
  107. };
  108. gb_internal bool is_load_directive_call(Ast *call) {
  109. call = unparen_expr(call);
  110. if (call->kind != Ast_CallExpr) {
  111. return false;
  112. }
  113. ast_node(ce, CallExpr, call);
  114. if (ce->proc->kind != Ast_BasicDirective) {
  115. return false;
  116. }
  117. ast_node(bd, BasicDirective, ce->proc);
  118. String name = bd->name.string;
  119. return name == "load";
  120. }
  121. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  122. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  123. auto results = did_you_mean_results(d);
  124. if (results.count != 0) {
  125. error_line("\tSuggestion: Did you mean?\n");
  126. for (auto const &result : results) {
  127. String const &target = result.target;
  128. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  129. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  130. }
  131. }
  132. }
  133. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  134. if (e->kind != Entity_TypeName) {
  135. return;
  136. }
  137. if (e->TypeName.objc_metadata == nullptr) {
  138. return;
  139. }
  140. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  141. Type *t = base_type(e->type);
  142. GB_ASSERT(t->kind == Type_Struct);
  143. if (is_type) {
  144. for (auto const &entry : objc_metadata->type_entries) {
  145. string_set_add(set, entry.name);
  146. }
  147. } else {
  148. for (auto const &entry : objc_metadata->value_entries) {
  149. string_set_add(set, entry.name);
  150. }
  151. }
  152. for (Entity *f : t->Struct.fields) {
  153. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  154. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  155. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  156. }
  157. }
  158. }
  159. }
  160. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  161. if (build_context.terse_errors) { return; }
  162. ERROR_BLOCK();
  163. GB_ASSERT(e->kind == Entity_TypeName);
  164. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  165. auto *objc_metadata = e->TypeName.objc_metadata;
  166. MUTEX_GUARD(objc_metadata->mutex);
  167. StringSet set = {};
  168. defer (string_set_destroy(&set));
  169. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  170. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  171. defer (did_you_mean_destroy(&d));
  172. for (String const &target : set) {
  173. did_you_mean_append(&d, target);
  174. }
  175. check_did_you_mean_print(&d, prefix);
  176. }
  177. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  178. if (build_context.terse_errors) { return; }
  179. ERROR_BLOCK();
  180. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  181. defer (did_you_mean_destroy(&d));
  182. for (Entity *e : fields) {
  183. did_you_mean_append(&d, e->token.string);
  184. }
  185. check_did_you_mean_print(&d, prefix);
  186. }
  187. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  188. if (build_context.terse_errors) { return; }
  189. ERROR_BLOCK();
  190. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  191. defer (did_you_mean_destroy(&d));
  192. for (Entity *e : fields) {
  193. did_you_mean_append(&d, e->token.string);
  194. }
  195. check_did_you_mean_print(&d, prefix);
  196. }
  197. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  198. if (build_context.terse_errors) { return; }
  199. ERROR_BLOCK();
  200. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  201. defer (did_you_mean_destroy(&d));
  202. rw_mutex_shared_lock(&scope->mutex);
  203. for (auto const &entry : scope->elements) {
  204. Entity *e = entry.value;
  205. did_you_mean_append(&d, e->token.string);
  206. }
  207. rw_mutex_shared_unlock(&scope->mutex);
  208. check_did_you_mean_print(&d, prefix);
  209. }
  210. gb_internal Entity *entity_from_expr(Ast *expr) {
  211. expr = unparen_expr(expr);
  212. switch (expr->kind) {
  213. case Ast_Ident:
  214. return expr->Ident.entity;
  215. case Ast_SelectorExpr:
  216. return entity_from_expr(expr->SelectorExpr.selector);
  217. }
  218. return nullptr;
  219. }
  220. gb_internal void error_operand_not_expression(Operand *o) {
  221. if (o->mode == Addressing_Type) {
  222. gbString err = expr_to_string(o->expr);
  223. error(o->expr, "'%s' is not an expression but a type", err);
  224. gb_string_free(err);
  225. o->mode = Addressing_Invalid;
  226. }
  227. }
  228. gb_internal void error_operand_no_value(Operand *o) {
  229. if (o->mode == Addressing_NoValue) {
  230. gbString err = expr_to_string(o->expr);
  231. Ast *x = unparen_expr(o->expr);
  232. if (x->kind == Ast_CallExpr) {
  233. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  234. } else {
  235. error(o->expr, "'%s' used as a value", err);
  236. }
  237. gb_string_free(err);
  238. o->mode = Addressing_Invalid;
  239. }
  240. }
  241. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  242. if (build_context.dynamic_map_calls) {
  243. add_package_dependency(c, "runtime", "__dynamic_map_get");
  244. } else {
  245. add_package_dependency(c, "runtime", "map_desired_position");
  246. add_package_dependency(c, "runtime", "map_probe_distance");
  247. }
  248. }
  249. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  250. init_core_source_code_location(c->checker);
  251. if (t_map_set_proc == nullptr) {
  252. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  253. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  254. }
  255. if (build_context.dynamic_map_calls) {
  256. add_package_dependency(c, "runtime", "__dynamic_map_set");
  257. } else {
  258. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  259. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  260. }
  261. }
  262. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  263. init_core_source_code_location(c->checker);
  264. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  265. }
  266. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  267. Scope *s = c->scope;
  268. check_collect_entities(c, nodes);
  269. for (auto const &entry : s->elements) {
  270. Entity *e = entry.value;
  271. switch (e->kind) {
  272. case Entity_Constant:
  273. case Entity_TypeName:
  274. case Entity_Procedure:
  275. break;
  276. default:
  277. continue;
  278. }
  279. DeclInfo *d = decl_info_of_entity(e);
  280. if (d != nullptr) {
  281. check_entity_decl(c, e, d, nullptr);
  282. }
  283. }
  284. }
  285. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  286. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  287. ///////////////////////////////////////////////////////////////////////////////
  288. // //
  289. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  290. // //
  291. ///////////////////////////////////////////////////////////////////////////////
  292. CheckerInfo *info = old_c->info;
  293. if (base_entity == nullptr) {
  294. return false;
  295. }
  296. if (!is_type_proc(base_entity->type)) {
  297. return false;
  298. }
  299. if (base_entity->flags & EntityFlag_Disabled) {
  300. return false;
  301. }
  302. String name = base_entity->token.string;
  303. Type *src = base_type(base_entity->type);
  304. Type *dst = nullptr;
  305. if (type != nullptr) {
  306. dst = base_type(type);
  307. }
  308. if (param_operands == nullptr) {
  309. GB_ASSERT(dst != nullptr);
  310. }
  311. if (param_operands != nullptr) {
  312. GB_ASSERT(dst == nullptr);
  313. }
  314. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  315. return false;
  316. }
  317. if (dst != nullptr) {
  318. if (dst->Proc.is_polymorphic) {
  319. return false;
  320. }
  321. if (dst->Proc.param_count != src->Proc.param_count ||
  322. dst->Proc.result_count != src->Proc.result_count) {
  323. return false;
  324. }
  325. }
  326. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  327. if (old_decl == nullptr) {
  328. return false;
  329. }
  330. gbAllocator a = heap_allocator();
  331. Array<Operand> operands = {};
  332. if (param_operands) {
  333. operands = *param_operands;
  334. } else {
  335. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  336. for (isize i = 0; i < dst->Proc.param_count; i++) {
  337. Entity *param = dst->Proc.params->Tuple.variables[i];
  338. Operand o = {Addressing_Value};
  339. o.type = param->type;
  340. array_add(&operands, o);
  341. }
  342. }
  343. defer (if (param_operands == nullptr) {
  344. array_free(&operands);
  345. });
  346. CheckerContext nctx = *old_c;
  347. Scope *scope = create_scope(info, base_entity->scope);
  348. scope->flags |= ScopeFlag_Proc;
  349. nctx.scope = scope;
  350. nctx.allow_polymorphic_types = true;
  351. if (nctx.polymorphic_scope == nullptr) {
  352. nctx.polymorphic_scope = scope;
  353. }
  354. auto *pt = &src->Proc;
  355. // NOTE(bill): This is slightly memory leaking if the type already exists
  356. // Maybe it's better to check with the previous types first?
  357. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  358. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  359. if (!success) {
  360. return false;
  361. }
  362. GenProcsData *gen_procs = nullptr;
  363. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  364. GB_ASSERT(base_entity->kind == Entity_Procedure);
  365. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  366. gen_procs = base_entity->Procedure.gen_procs;
  367. if (gen_procs) {
  368. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  369. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  370. for (Entity *other : gen_procs->procs) {
  371. Type *pt = base_type(other->type);
  372. if (are_types_identical(pt, final_proc_type)) {
  373. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  374. if (poly_proc_data) {
  375. poly_proc_data->gen_entity = other;
  376. }
  377. return true;
  378. }
  379. }
  380. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  381. } else {
  382. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  383. gen_procs->procs.allocator = heap_allocator();
  384. base_entity->Procedure.gen_procs = gen_procs;
  385. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  386. }
  387. {
  388. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  389. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  390. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  391. nctx.no_polymorphic_errors = false;
  392. // NOTE(bill): Reset scope from the failed procedure type
  393. scope_reset(scope);
  394. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  395. Ast *cloned_proc_type_node = clone_ast(pt->node);
  396. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  397. if (!success) {
  398. return false;
  399. }
  400. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  401. for (Entity *other : gen_procs->procs) {
  402. Type *pt = base_type(other->type);
  403. if (are_types_identical(pt, final_proc_type)) {
  404. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  405. if (poly_proc_data) {
  406. poly_proc_data->gen_entity = other;
  407. }
  408. DeclInfo *decl = other->decl_info;
  409. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  410. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  411. proc_info->file = other->file;
  412. proc_info->token = other->token;
  413. proc_info->decl = decl;
  414. proc_info->type = other->type;
  415. proc_info->body = decl->proc_lit->ProcLit.body;
  416. proc_info->tags = other->Procedure.tags;;
  417. proc_info->generated_from_polymorphic = true;
  418. proc_info->poly_def_node = poly_def_node;
  419. check_procedure_later(nctx.checker, proc_info);
  420. }
  421. return true;
  422. }
  423. }
  424. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  425. }
  426. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  427. ast_node(pl, ProcLit, proc_lit);
  428. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  429. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  430. final_proc_type->Proc.is_poly_specialized = true;
  431. final_proc_type->Proc.is_polymorphic = true;
  432. final_proc_type->Proc.variadic = src->Proc.variadic;
  433. final_proc_type->Proc.require_results = src->Proc.require_results;
  434. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  435. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  436. final_proc_type->Proc.diverging = src->Proc.diverging;
  437. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  438. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  439. for (isize i = 0; i < operands.count; i++) {
  440. Operand o = operands[i];
  441. if (final_proc_type == o.type ||
  442. base_entity->type == o.type) {
  443. // NOTE(bill): Cycle
  444. final_proc_type->Proc.is_poly_specialized = false;
  445. break;
  446. }
  447. }
  448. u64 tags = base_entity->Procedure.tags;
  449. Ast *ident = clone_ast(base_entity->identifier);
  450. Token token = ident->Ident.token;
  451. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  452. d->gen_proc_type = final_proc_type;
  453. d->type_expr = pl->type;
  454. d->proc_lit = proc_lit;
  455. d->proc_checked_state = ProcCheckedState_Unchecked;
  456. d->defer_use_checked = false;
  457. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  458. entity->identifier = ident;
  459. add_entity_and_decl_info(&nctx, ident, entity, d);
  460. // NOTE(bill): Set the scope afterwards as this is not real overloading
  461. entity->scope = scope->parent;
  462. entity->file = base_entity->file;
  463. entity->pkg = base_entity->pkg;
  464. entity->flags = 0;
  465. d->entity = entity;
  466. AstFile *file = nullptr;
  467. {
  468. Scope *s = entity->scope;
  469. while (s != nullptr && s->file == nullptr) {
  470. file = s->file;
  471. s = s->parent;
  472. }
  473. }
  474. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  475. array_add(&gen_procs->procs, entity);
  476. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  477. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  478. proc_info->file = file;
  479. proc_info->token = token;
  480. proc_info->decl = d;
  481. proc_info->type = final_proc_type;
  482. proc_info->body = pl->body;
  483. proc_info->tags = tags;
  484. proc_info->generated_from_polymorphic = true;
  485. proc_info->poly_def_node = poly_def_node;
  486. if (poly_proc_data) {
  487. poly_proc_data->gen_entity = entity;
  488. poly_proc_data->proc_info = proc_info;
  489. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  490. }
  491. // NOTE(bill): Check the newly generated procedure body
  492. check_procedure_later(nctx.checker, proc_info);
  493. return true;
  494. }
  495. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  496. if (operand->expr == nullptr) return false;
  497. Entity *base_entity = entity_of_node(operand->expr);
  498. if (base_entity == nullptr) return false;
  499. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  500. }
  501. 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) {
  502. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  503. }
  504. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  505. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  506. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  507. #define MAXIMUM_TYPE_DISTANCE 10
  508. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  509. if (c == nullptr) {
  510. GB_ASSERT(operand->mode == Addressing_Value);
  511. GB_ASSERT(is_type_typed(operand->type));
  512. }
  513. if (operand->mode == Addressing_Invalid ||
  514. type == t_invalid) {
  515. return -1;
  516. }
  517. if (operand->mode == Addressing_Builtin) {
  518. return -1;
  519. }
  520. if (operand->mode == Addressing_Type) {
  521. if (is_type_typeid(type)) {
  522. if (is_type_polymorphic(operand->type)) {
  523. return -1;
  524. }
  525. add_type_info_type(c, operand->type);
  526. return 4;
  527. }
  528. return -1;
  529. }
  530. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  531. return -1;
  532. }
  533. Type *s = operand->type;
  534. if (are_types_identical(s, type)) {
  535. return 0;
  536. }
  537. Type *src = base_type(s);
  538. Type *dst = base_type(type);
  539. if (is_type_untyped_uninit(src)) {
  540. return 1;
  541. }
  542. if (is_type_untyped_nil(src)) {
  543. if (type_has_nil(dst)) {
  544. return 1;
  545. }
  546. return -1;
  547. }
  548. if (is_type_untyped(src)) {
  549. if (is_type_any(dst)) {
  550. // NOTE(bill): Anything can cast to 'Any'
  551. add_type_info_type(c, s);
  552. return MAXIMUM_TYPE_DISTANCE;
  553. }
  554. if (dst->kind == Type_Basic) {
  555. if (operand->mode == Addressing_Constant) {
  556. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  557. if (is_type_typed(dst) && src->kind == Type_Basic) {
  558. switch (src->Basic.kind) {
  559. case Basic_UntypedBool:
  560. if (is_type_boolean(dst)) {
  561. return 1;
  562. }
  563. break;
  564. case Basic_UntypedRune:
  565. if (is_type_integer(dst) || is_type_rune(dst)) {
  566. return 1;
  567. }
  568. break;
  569. case Basic_UntypedInteger:
  570. if (is_type_integer(dst) || is_type_rune(dst)) {
  571. return 1;
  572. }
  573. break;
  574. case Basic_UntypedString:
  575. if (is_type_string(dst)) {
  576. return 1;
  577. }
  578. break;
  579. case Basic_UntypedFloat:
  580. if (is_type_float(dst)) {
  581. return 1;
  582. }
  583. break;
  584. case Basic_UntypedComplex:
  585. if (is_type_complex(dst)) {
  586. return 1;
  587. }
  588. if (is_type_quaternion(dst)) {
  589. return 2;
  590. }
  591. break;
  592. case Basic_UntypedQuaternion:
  593. if (is_type_quaternion(dst)) {
  594. return 1;
  595. }
  596. break;
  597. }
  598. }
  599. return 2;
  600. }
  601. return -1;
  602. }
  603. if (src->kind == Type_Basic) {
  604. Type *d = base_array_type(dst);
  605. i64 score = -1;
  606. switch (src->Basic.kind) {
  607. case Basic_UntypedBool:
  608. if (is_type_boolean(d)) {
  609. score = 1;
  610. }
  611. break;
  612. case Basic_UntypedRune:
  613. if (is_type_integer(d) || is_type_rune(d)) {
  614. score = 1;
  615. }
  616. break;
  617. case Basic_UntypedInteger:
  618. if (is_type_integer(d) || is_type_rune(d)) {
  619. score = 1;
  620. }
  621. break;
  622. case Basic_UntypedString:
  623. if (is_type_string(d)) {
  624. score = 1;
  625. }
  626. break;
  627. case Basic_UntypedFloat:
  628. if (is_type_float(d)) {
  629. score = 1;
  630. }
  631. break;
  632. case Basic_UntypedComplex:
  633. if (is_type_complex(d)) {
  634. score = 1;
  635. }
  636. if (is_type_quaternion(d)) {
  637. score = 2;
  638. }
  639. break;
  640. case Basic_UntypedQuaternion:
  641. if (is_type_quaternion(d)) {
  642. score = 1;
  643. }
  644. break;
  645. }
  646. if (score > 0) {
  647. if (is_type_typed(d)) {
  648. score += 1;
  649. }
  650. if (d != dst) {
  651. score += 6;
  652. }
  653. }
  654. return score;
  655. }
  656. }
  657. }
  658. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  659. if (c->in_enum_type) {
  660. return 3;
  661. }
  662. }
  663. {
  664. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  665. if (subtype_level > 0) {
  666. return 4 + subtype_level;
  667. }
  668. }
  669. // rawptr <- ^T
  670. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  671. return 5;
  672. }
  673. // rawptr <- [^]T
  674. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  675. return 5;
  676. }
  677. // ^T <- [^]T
  678. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  679. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  680. return 4;
  681. }
  682. }
  683. // [^]T <- ^T
  684. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  685. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  686. return 4;
  687. }
  688. }
  689. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  690. bool modify_type = !c->no_polymorphic_errors;
  691. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  692. return 2;
  693. }
  694. }
  695. if (is_type_union(dst)) {
  696. for (Type *vt : dst->Union.variants) {
  697. if (are_types_identical(vt, s)) {
  698. return 1;
  699. }
  700. }
  701. if (dst->Union.variants.count == 1) {
  702. Type *vt = dst->Union.variants[0];
  703. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  704. if (score >= 0) {
  705. return score+2;
  706. }
  707. } else if (is_type_untyped(src)) {
  708. i64 prev_lowest_score = -1;
  709. i64 lowest_score = -1;
  710. for (Type *vt : dst->Union.variants) {
  711. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  712. if (score >= 0) {
  713. if (lowest_score < 0) {
  714. lowest_score = score;
  715. } else {
  716. if (prev_lowest_score < 0) {
  717. prev_lowest_score = lowest_score;
  718. } else {
  719. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  720. }
  721. lowest_score = gb_min(lowest_score, score);
  722. }
  723. }
  724. }
  725. if (lowest_score >= 0) {
  726. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  727. return lowest_score+2;
  728. }
  729. }
  730. }
  731. }
  732. if (is_type_relative_pointer(dst)) {
  733. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type, allow_array_programming);
  734. if (score >= 0) {
  735. return score+2;
  736. }
  737. }
  738. if (is_type_relative_multi_pointer(dst)) {
  739. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type, allow_array_programming);
  740. if (score >= 0) {
  741. return score+2;
  742. }
  743. }
  744. if (is_type_proc(dst)) {
  745. if (are_types_identical(src, dst)) {
  746. return 3;
  747. }
  748. PolyProcData poly_proc_data = {};
  749. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  750. Entity *e = poly_proc_data.gen_entity;
  751. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  752. add_entity_use(c, operand->expr, e);
  753. return 4;
  754. }
  755. }
  756. if (is_type_complex_or_quaternion(dst)) {
  757. Type *elem = base_complex_elem_type(dst);
  758. if (are_types_identical(elem, base_type(src))) {
  759. return 5;
  760. }
  761. }
  762. if (allow_array_programming) {
  763. if (is_type_array(dst)) {
  764. Type *elem = base_array_type(dst);
  765. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  766. if (distance >= 0) {
  767. return distance + 6;
  768. }
  769. }
  770. if (is_type_simd_vector(dst)) {
  771. Type *dst_elem = base_array_type(dst);
  772. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  773. if (distance >= 0) {
  774. return distance + 6;
  775. }
  776. }
  777. }
  778. if (is_type_matrix(dst)) {
  779. if (are_types_identical(src, dst)) {
  780. return 5;
  781. }
  782. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  783. Type *dst_elem = base_array_type(dst);
  784. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  785. if (distance >= 0) {
  786. return distance + 7;
  787. }
  788. }
  789. }
  790. if (is_type_any(dst)) {
  791. if (!is_type_polymorphic(src)) {
  792. if (operand->mode == Addressing_Context && operand->type == t_context) {
  793. return -1;
  794. } else {
  795. // NOTE(bill): Anything can cast to 'Any'
  796. add_type_info_type(c, s);
  797. return MAXIMUM_TYPE_DISTANCE;
  798. }
  799. }
  800. }
  801. Ast *expr = unparen_expr(operand->expr);
  802. if (expr != nullptr) {
  803. if (expr->kind == Ast_AutoCast) {
  804. Operand x = *operand;
  805. x.expr = expr->AutoCast.expr;
  806. if (check_cast_internal(c, &x, type)) {
  807. return MAXIMUM_TYPE_DISTANCE;
  808. }
  809. }
  810. }
  811. return -1;
  812. }
  813. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  814. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  815. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  816. // TODO(bill): A decent score function
  817. i64 d = distance*distance; // x^2
  818. if (is_variadic && d >= 0) {
  819. d += distance + 1; // x^2 + x + 1
  820. }
  821. return gb_max(c - d, 0);
  822. }
  823. 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) {
  824. i64 score = 0;
  825. i64 distance = check_distance_between_types(c, operand, type, allow_array_programming);
  826. bool ok = distance >= 0;
  827. if (ok) {
  828. score = assign_score_function(distance, is_variadic);
  829. }
  830. if (score_) *score_ = score;
  831. return ok;
  832. }
  833. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  834. i64 score = 0;
  835. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  836. }
  837. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  838. Operand x = {};
  839. x.type = src;
  840. x.mode = Addressing_Value;
  841. return check_is_assignable_to(nullptr, &x, dst);
  842. }
  843. gb_internal AstPackage *get_package_of_type(Type *type) {
  844. for (;;) {
  845. if (type == nullptr) {
  846. return nullptr;
  847. }
  848. switch (type->kind) {
  849. case Type_Basic:
  850. return builtin_pkg;
  851. case Type_Named:
  852. if (type->Named.type_name != nullptr) {
  853. return type->Named.type_name->pkg;
  854. }
  855. return nullptr;
  856. case Type_Pointer:
  857. type = type->Pointer.elem;
  858. continue;
  859. case Type_Array:
  860. type = type->Array.elem;
  861. continue;
  862. case Type_Slice:
  863. type = type->Slice.elem;
  864. continue;
  865. case Type_DynamicArray:
  866. type = type->DynamicArray.elem;
  867. continue;
  868. case Type_RelativePointer:
  869. type = type->RelativePointer.pointer_type;
  870. continue;
  871. case Type_RelativeMultiPointer:
  872. type = type->RelativeMultiPointer.pointer_type;
  873. continue;
  874. }
  875. return nullptr;
  876. }
  877. }
  878. // NOTE(bill): 'content_name' is for debugging and error messages
  879. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  880. check_not_tuple(c, operand);
  881. if (operand->mode == Addressing_Invalid) {
  882. return;
  883. }
  884. if (is_type_untyped(operand->type)) {
  885. Type *target_type = type;
  886. if (type == nullptr || is_type_any(type)) {
  887. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  888. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  889. operand->mode = Addressing_Invalid;
  890. return;
  891. }
  892. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  893. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  894. operand->mode = Addressing_Invalid;
  895. return;
  896. }
  897. target_type = default_type(operand->type);
  898. if (type != nullptr && !is_type_any(type)) {
  899. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  900. }
  901. add_type_info_type(c, type);
  902. add_type_info_type(c, target_type);
  903. }
  904. convert_to_typed(c, operand, target_type);
  905. if (operand->mode == Addressing_Invalid) {
  906. return;
  907. }
  908. }
  909. if (type == nullptr) {
  910. return;
  911. }
  912. if (operand->mode == Addressing_ProcGroup) {
  913. bool good = false;
  914. if (type != nullptr && is_type_proc(type)) {
  915. Array<Entity *> procs = proc_group_entities(c, *operand);
  916. // NOTE(bill): These should be done
  917. for (Entity *e : procs) {
  918. Type *t = base_type(e->type);
  919. if (t == t_invalid) {
  920. continue;
  921. }
  922. Operand x = {};
  923. x.mode = Addressing_Value;
  924. x.type = t;
  925. if (check_is_assignable_to(c, &x, type)) {
  926. add_entity_use(c, operand->expr, e);
  927. good = true;
  928. break;
  929. }
  930. }
  931. }
  932. if (!good) {
  933. gbString expr_str = expr_to_string(operand->expr);
  934. gbString op_type_str = type_to_string(operand->type);
  935. gbString type_str = type_to_string(type);
  936. defer (gb_string_free(type_str));
  937. defer (gb_string_free(op_type_str));
  938. defer (gb_string_free(expr_str));
  939. // TODO(bill): is this a good enough error message?
  940. error(operand->expr,
  941. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  942. expr_str,
  943. op_type_str,
  944. LIT(context_name));
  945. operand->mode = Addressing_Invalid;
  946. }
  947. convert_to_typed(c, operand, type);
  948. return;
  949. }
  950. if (check_is_assignable_to(c, operand, type)) {
  951. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  952. add_type_info_type(c, operand->type);
  953. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  954. }
  955. } else {
  956. gbString expr_str = expr_to_string(operand->expr);
  957. gbString op_type_str = type_to_string(operand->type);
  958. gbString type_str = type_to_string(type);
  959. defer (gb_string_free(type_str));
  960. defer (gb_string_free(op_type_str));
  961. defer (gb_string_free(expr_str));
  962. switch (operand->mode) {
  963. case Addressing_Builtin:
  964. error(operand->expr,
  965. "Cannot assign built-in procedure '%s' in %.*s",
  966. expr_str,
  967. LIT(context_name));
  968. break;
  969. case Addressing_Type:
  970. if (is_type_polymorphic(operand->type)) {
  971. error(operand->expr,
  972. "Cannot assign '%s' which is a polymorphic type in %.*s",
  973. op_type_str,
  974. LIT(context_name));
  975. } else {
  976. error(operand->expr,
  977. "Cannot assign '%s' which is a type in %.*s",
  978. op_type_str,
  979. LIT(context_name));
  980. }
  981. break;
  982. default:
  983. // TODO(bill): is this a good enough error message?
  984. {
  985. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  986. gbString type_extra = gb_string_make(heap_allocator(), "");
  987. defer (gb_string_free(op_type_extra));
  988. defer (gb_string_free(type_extra));
  989. isize on = gb_string_length(op_type_str);
  990. isize tn = gb_string_length(type_str);
  991. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  992. AstPackage *op_pkg = get_package_of_type(operand->type);
  993. AstPackage *type_pkg = get_package_of_type(type);
  994. if (op_pkg != nullptr) {
  995. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  996. }
  997. if (type_pkg != nullptr) {
  998. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  999. }
  1000. }
  1001. ERROR_BLOCK();
  1002. error(operand->expr,
  1003. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  1004. expr_str,
  1005. op_type_str, op_type_extra,
  1006. type_str, type_extra,
  1007. LIT(context_name));
  1008. check_assignment_error_suggestion(c, operand, type);
  1009. }
  1010. break;
  1011. }
  1012. operand->mode = Addressing_Invalid;
  1013. return;
  1014. }
  1015. }
  1016. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1017. Type *gt = *gt_;
  1018. GB_ASSERT(gt->kind == Type_Generic);
  1019. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1020. GB_ASSERT(e != nullptr);
  1021. if (e->kind == Entity_TypeName) {
  1022. *gt_ = nullptr;
  1023. *dst_count = source_count;
  1024. e->kind = Entity_Constant;
  1025. e->Constant.value = exact_value_i64(source_count);
  1026. e->type = t_untyped_integer;
  1027. return true;
  1028. } else if (e->kind == Entity_Constant) {
  1029. *gt_ = nullptr;
  1030. if (e->Constant.value.kind != ExactValue_Integer) {
  1031. return false;
  1032. }
  1033. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1034. if (count != source_count) {
  1035. return false;
  1036. }
  1037. *dst_count = source_count;
  1038. return true;
  1039. }
  1040. return false;
  1041. }
  1042. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1043. Operand o = {Addressing_Value};
  1044. o.type = source;
  1045. switch (poly->kind) {
  1046. case Type_Basic:
  1047. if (compound) return are_types_identical(poly, source);
  1048. return check_is_assignable_to(c, &o, poly);
  1049. case Type_Named: {
  1050. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1051. return true;
  1052. }
  1053. if (compound || !is_type_generic(poly)) {
  1054. return are_types_identical(poly, source);
  1055. }
  1056. return check_is_assignable_to(c, &o, poly);
  1057. }
  1058. case Type_Generic: {
  1059. if (poly->Generic.specialized != nullptr) {
  1060. Type *s = poly->Generic.specialized;
  1061. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1062. return false;
  1063. }
  1064. }
  1065. if (modify_type) {
  1066. Type *ds = default_type(source);
  1067. gb_memmove(poly, ds, gb_size_of(Type));
  1068. }
  1069. return true;
  1070. }
  1071. case Type_Pointer:
  1072. if (source->kind == Type_Pointer) {
  1073. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1074. if (level > 0) {
  1075. return true;
  1076. }
  1077. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1078. } else if (source->kind == Type_MultiPointer) {
  1079. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1080. if (level > 0) {
  1081. return true;
  1082. }
  1083. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1084. }
  1085. return false;
  1086. case Type_MultiPointer:
  1087. if (source->kind == Type_MultiPointer) {
  1088. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1089. if (level > 0) {
  1090. return true;
  1091. }
  1092. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1093. } else if (source->kind == Type_Pointer) {
  1094. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1095. if (level > 0) {
  1096. return true;
  1097. }
  1098. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1099. }
  1100. return false;
  1101. case Type_Array:
  1102. if (source->kind == Type_Array) {
  1103. if (poly->Array.generic_count != nullptr) {
  1104. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1105. return false;
  1106. }
  1107. }
  1108. if (poly->Array.count == source->Array.count) {
  1109. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1110. }
  1111. } else if (source->kind == Type_EnumeratedArray) {
  1112. if (poly->Array.generic_count != nullptr) {
  1113. Type *gt = poly->Array.generic_count;
  1114. GB_ASSERT(gt->kind == Type_Generic);
  1115. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1116. GB_ASSERT(e != nullptr);
  1117. if (e->kind == Entity_TypeName) {
  1118. Type *index = source->EnumeratedArray.index;
  1119. Type *it = base_type(index);
  1120. if (it->kind != Type_Enum) {
  1121. return false;
  1122. }
  1123. poly->kind = Type_EnumeratedArray;
  1124. poly->cached_size = -1;
  1125. poly->cached_align = -1;
  1126. poly->flags.exchange(source->flags);
  1127. poly->failure = false;
  1128. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1129. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1130. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1131. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1132. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1133. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1134. e->kind = Entity_TypeName;
  1135. e->TypeName.is_type_alias = true;
  1136. e->type = index;
  1137. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1138. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. return false;
  1144. case Type_EnumeratedArray:
  1145. if (source->kind == Type_EnumeratedArray) {
  1146. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1147. return false;
  1148. }
  1149. if (poly->EnumeratedArray.op) {
  1150. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1151. return false;
  1152. }
  1153. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1154. return false;
  1155. }
  1156. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1157. return false;
  1158. }
  1159. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1160. }
  1161. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1162. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1163. return index || elem;
  1164. }
  1165. return false;
  1166. case Type_DynamicArray:
  1167. if (source->kind == Type_DynamicArray) {
  1168. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1169. }
  1170. return false;
  1171. case Type_Slice:
  1172. if (source->kind == Type_Slice) {
  1173. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1174. }
  1175. return false;
  1176. case Type_Enum:
  1177. return false;
  1178. case Type_BitSet:
  1179. if (source->kind == Type_BitSet) {
  1180. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1181. return false;
  1182. }
  1183. if (poly->BitSet.underlying == nullptr) {
  1184. if (modify_type) {
  1185. poly->BitSet.underlying = source->BitSet.underlying;
  1186. }
  1187. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1188. return false;
  1189. }
  1190. return true;
  1191. }
  1192. return false;
  1193. case Type_Union:
  1194. if (source->kind == Type_Union) {
  1195. TypeUnion *x = &poly->Union;
  1196. TypeUnion *y = &source->Union;
  1197. if (x->variants.count != y->variants.count) {
  1198. return false;
  1199. }
  1200. for_array(i, x->variants) {
  1201. Type *a = x->variants[i];
  1202. Type *b = y->variants[i];
  1203. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1204. if (!ok) return false;
  1205. }
  1206. return true;
  1207. }
  1208. return false;
  1209. case Type_Struct:
  1210. if (source->kind == Type_Struct) {
  1211. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1212. poly->Struct.soa_kind != StructSoa_None) {
  1213. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1214. if (ok) switch (source->Struct.soa_kind) {
  1215. case StructSoa_Fixed:
  1216. default:
  1217. GB_PANIC("Unhandled SOA Kind");
  1218. break;
  1219. case StructSoa_Slice:
  1220. if (modify_type) {
  1221. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1222. gb_memmove(poly, type, gb_size_of(*type));
  1223. }
  1224. break;
  1225. case StructSoa_Dynamic:
  1226. if (modify_type) {
  1227. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1228. gb_memmove(poly, type, gb_size_of(*type));
  1229. }
  1230. break;
  1231. }
  1232. return ok;
  1233. }
  1234. // NOTE(bill): Check for subtypes of
  1235. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1236. }
  1237. return false;
  1238. case Type_Tuple:
  1239. GB_PANIC("This should never happen");
  1240. return false;
  1241. case Type_Proc:
  1242. if (source->kind == Type_Proc) {
  1243. TypeProc *x = &poly->Proc;
  1244. TypeProc *y = &source->Proc;
  1245. if (x->calling_convention != y->calling_convention) {
  1246. return false;
  1247. }
  1248. if (x->c_vararg != y->c_vararg) {
  1249. return false;
  1250. }
  1251. if (x->variadic != y->variadic) {
  1252. return false;
  1253. }
  1254. if (x->param_count != y->param_count) {
  1255. return false;
  1256. }
  1257. if (x->result_count != y->result_count) {
  1258. return false;
  1259. }
  1260. for (isize i = 0; i < x->param_count; i++) {
  1261. Entity *a = x->params->Tuple.variables[i];
  1262. Entity *b = y->params->Tuple.variables[i];
  1263. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1264. if (!ok) return false;
  1265. }
  1266. for (isize i = 0; i < x->result_count; i++) {
  1267. Entity *a = x->results->Tuple.variables[i];
  1268. Entity *b = y->results->Tuple.variables[i];
  1269. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1270. if (!ok) return false;
  1271. }
  1272. return true;
  1273. }
  1274. return false;
  1275. case Type_Map:
  1276. if (source->kind == Type_Map) {
  1277. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1278. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1279. if (key || value) {
  1280. poly->Map.lookup_result_type = nullptr;
  1281. init_map_internal_types(poly);
  1282. return true;
  1283. }
  1284. }
  1285. return false;
  1286. case Type_Matrix:
  1287. if (source->kind == Type_Matrix) {
  1288. if (poly->Matrix.generic_row_count != nullptr) {
  1289. poly->Matrix.stride_in_bytes = 0;
  1290. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1291. return false;
  1292. }
  1293. }
  1294. if (poly->Matrix.generic_column_count != nullptr) {
  1295. poly->Matrix.stride_in_bytes = 0;
  1296. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1297. return false;
  1298. }
  1299. }
  1300. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1301. poly->Matrix.column_count == source->Matrix.column_count) {
  1302. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1303. }
  1304. }
  1305. return false;
  1306. case Type_SimdVector:
  1307. if (source->kind == Type_SimdVector) {
  1308. if (poly->SimdVector.generic_count != nullptr) {
  1309. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1310. return false;
  1311. }
  1312. }
  1313. if (poly->SimdVector.count == source->SimdVector.count) {
  1314. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1315. }
  1316. }
  1317. return false;
  1318. }
  1319. return false;
  1320. }
  1321. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1322. if (curr->state != EntityState_InProgress) {
  1323. return false;
  1324. }
  1325. for_array(i, *c->type_path) {
  1326. Entity *prev = c->type_path->data[i];
  1327. if (prev == curr) {
  1328. if (report) {
  1329. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1330. for (isize j = i; j < c->type_path->count; j++) {
  1331. Entity *curr = (*c->type_path)[j];
  1332. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1333. }
  1334. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1335. curr->type = t_invalid;
  1336. }
  1337. return true;
  1338. }
  1339. }
  1340. return false;
  1341. }
  1342. struct CIdentSuggestion {
  1343. String name;
  1344. String msg;
  1345. };
  1346. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1347. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1348. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1349. {str_lit("sizeof"), str_lit("'size_of'?")},
  1350. {str_lit("alignof"), str_lit("'align_of'?")},
  1351. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1352. {str_lit("_Bool"), str_lit("'bool'?")},
  1353. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1354. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1355. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1356. {str_lit("float"), str_lit("'f32'?")},
  1357. {str_lit("double"), str_lit("'f64'?")},
  1358. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1359. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1360. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1361. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1362. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1363. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1364. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1365. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1366. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1367. {str_lit("uint8_t"), str_lit("'u8'?")},
  1368. {str_lit("int8_t"), str_lit("'i8'?")},
  1369. {str_lit("uint16_t"), str_lit("'u16'?")},
  1370. {str_lit("int16_t"), str_lit("'i16'?")},
  1371. {str_lit("uint32_t"), str_lit("'u32'?")},
  1372. {str_lit("int32_t"), str_lit("'i32'?")},
  1373. {str_lit("uint64_t"), str_lit("'u64'?")},
  1374. {str_lit("int64_t"), str_lit("'i64'?")},
  1375. {str_lit("uint128_t"), str_lit("'u128'?")},
  1376. {str_lit("int128_t"), str_lit("'i128'?")},
  1377. {str_lit("float32"), str_lit("'f32'?")},
  1378. {str_lit("float64"), str_lit("'f64'?")},
  1379. {str_lit("float32_t"), str_lit("'f32'?")},
  1380. {str_lit("float64_t"), str_lit("'f64'?")},
  1381. };
  1382. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1383. GB_ASSERT(n->kind == Ast_Ident);
  1384. o->mode = Addressing_Invalid;
  1385. o->expr = n;
  1386. String name = n->Ident.token.string;
  1387. Entity *e = scope_lookup(c->scope, name);
  1388. if (e == nullptr) {
  1389. if (is_blank_ident(name)) {
  1390. error(n, "'_' cannot be used as a value");
  1391. } else {
  1392. ERROR_BLOCK();
  1393. error(n, "Undeclared name: %.*s", LIT(name));
  1394. // NOTE(bill): Loads of checks for C programmers
  1395. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1396. if (name == suggestion.name) {
  1397. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1398. }
  1399. }
  1400. }
  1401. o->type = t_invalid;
  1402. o->mode = Addressing_Invalid;
  1403. if (named_type != nullptr) {
  1404. set_base_type(named_type, t_invalid);
  1405. }
  1406. return nullptr;
  1407. }
  1408. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1409. if (e->parent_proc_decl != nullptr &&
  1410. e->parent_proc_decl != c->curr_proc_decl) {
  1411. if (e->kind == Entity_Variable) {
  1412. if ((e->flags & EntityFlag_Static) == 0) {
  1413. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1414. return nullptr;
  1415. }
  1416. } else if (e->kind == Entity_Label) {
  1417. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1418. return nullptr;
  1419. }
  1420. }
  1421. if (e->kind == Entity_ProcGroup) {
  1422. auto *pge = &e->ProcGroup;
  1423. DeclInfo *d = decl_info_of_entity(e);
  1424. check_entity_decl(c, e, d, nullptr);
  1425. Array<Entity *> procs = pge->entities;
  1426. bool skip = false;
  1427. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1428. // NOTE(bill): These should be done
  1429. for (Entity *proc : procs) {
  1430. Type *t = base_type(proc->type);
  1431. if (t == t_invalid) {
  1432. continue;
  1433. }
  1434. Operand x = {};
  1435. x.mode = Addressing_Value;
  1436. x.type = t;
  1437. if (check_is_assignable_to(c, &x, type_hint)) {
  1438. e = proc;
  1439. add_entity_use(c, n, e);
  1440. skip = true;
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. if (!skip) {
  1446. o->mode = Addressing_ProcGroup;
  1447. o->type = t_invalid;
  1448. o->proc_group = e;
  1449. return nullptr;
  1450. }
  1451. }
  1452. add_entity_use(c, n, e);
  1453. if (e->state == EntityState_Unresolved) {
  1454. check_entity_decl(c, e, nullptr, named_type);
  1455. }
  1456. if (e->type == nullptr) {
  1457. // TODO(bill): Which is correct? return or compiler_error?
  1458. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1459. return nullptr;
  1460. }
  1461. e->flags |= EntityFlag_Used;
  1462. Type *type = e->type;
  1463. o->type = type;
  1464. switch (e->kind) {
  1465. case Entity_Constant:
  1466. if (type == t_invalid) {
  1467. o->type = t_invalid;
  1468. return e;
  1469. }
  1470. o->value = e->Constant.value;
  1471. if (o->value.kind == ExactValue_Invalid) {
  1472. return e;
  1473. }
  1474. if (o->value.kind == ExactValue_Procedure) {
  1475. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1476. if (proc != nullptr) {
  1477. o->mode = Addressing_Value;
  1478. o->type = proc->type;
  1479. return proc;
  1480. }
  1481. }
  1482. o->mode = Addressing_Constant;
  1483. break;
  1484. case Entity_Variable:
  1485. e->flags |= EntityFlag_Used;
  1486. if (type == t_invalid) {
  1487. o->type = t_invalid;
  1488. return e;
  1489. }
  1490. o->mode = Addressing_Variable;
  1491. if (e->flags & EntityFlag_Value) {
  1492. o->mode = Addressing_Value;
  1493. }
  1494. break;
  1495. case Entity_Procedure:
  1496. o->mode = Addressing_Value;
  1497. o->value = exact_value_procedure(n);
  1498. break;
  1499. case Entity_Builtin:
  1500. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1501. o->mode = Addressing_Builtin;
  1502. break;
  1503. case Entity_TypeName:
  1504. o->mode = Addressing_Type;
  1505. if (check_cycle(c, e, true)) {
  1506. o->type = t_invalid;
  1507. }
  1508. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1509. o->type = base_type(o->type);
  1510. }
  1511. break;
  1512. case Entity_ImportName:
  1513. if (!allow_import_name) {
  1514. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1515. }
  1516. return e;
  1517. case Entity_LibraryName:
  1518. if (!allow_import_name) {
  1519. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1520. }
  1521. return e;
  1522. case Entity_Label:
  1523. o->mode = Addressing_NoValue;
  1524. break;
  1525. case Entity_Nil:
  1526. o->mode = Addressing_Value;
  1527. break;
  1528. default:
  1529. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1530. break;
  1531. }
  1532. return e;
  1533. }
  1534. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1535. if (o->type == nullptr) {
  1536. gbString str = expr_to_string(o->expr);
  1537. error(o->expr, "Expression has no value '%s'", str);
  1538. gb_string_free(str);
  1539. return false;
  1540. }
  1541. Type *type = base_type(core_array_type(o->type));
  1542. gbString str = nullptr;
  1543. switch (op.kind) {
  1544. case Token_Add:
  1545. case Token_Sub:
  1546. if (!is_type_numeric(type)) {
  1547. str = expr_to_string(o->expr);
  1548. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1549. gb_string_free(str);
  1550. }
  1551. break;
  1552. case Token_Xor:
  1553. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1554. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1555. }
  1556. break;
  1557. case Token_Not:
  1558. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1559. ERROR_BLOCK();
  1560. str = expr_to_string(o->expr);
  1561. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1562. gb_string_free(str);
  1563. if (is_type_integer(type)) {
  1564. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1565. }
  1566. } else {
  1567. o->type = t_untyped_bool;
  1568. }
  1569. break;
  1570. default:
  1571. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1572. return false;
  1573. }
  1574. return true;
  1575. }
  1576. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1577. Type *main_type = o->type;
  1578. Type *type = base_type(core_array_type(main_type));
  1579. Type *ct = core_type(type);
  1580. switch (op.kind) {
  1581. case Token_Sub:
  1582. case Token_SubEq:
  1583. if (is_type_bit_set(type)) {
  1584. return true;
  1585. } else if (!is_type_numeric(type)) {
  1586. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1587. return false;
  1588. }
  1589. break;
  1590. case Token_Quo:
  1591. case Token_QuoEq:
  1592. if (is_type_matrix(main_type)) {
  1593. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1594. return false;
  1595. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1596. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1597. return false;
  1598. }
  1599. /*fallthrough*/
  1600. case Token_Mul:
  1601. case Token_MulEq:
  1602. case Token_AddEq:
  1603. if (is_type_bit_set(type)) {
  1604. return true;
  1605. } else if (!is_type_numeric(type)) {
  1606. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1607. return false;
  1608. }
  1609. break;
  1610. case Token_Add:
  1611. if (is_type_string(type)) {
  1612. if (o->mode == Addressing_Constant) {
  1613. return true;
  1614. }
  1615. error(op, "String concatenation is only allowed with constant strings");
  1616. return false;
  1617. } else if (is_type_bit_set(type)) {
  1618. return true;
  1619. } else if (!is_type_numeric(type)) {
  1620. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1621. return false;
  1622. }
  1623. break;
  1624. case Token_And:
  1625. case Token_Or:
  1626. case Token_AndEq:
  1627. case Token_OrEq:
  1628. case Token_Xor:
  1629. case Token_XorEq:
  1630. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1631. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1632. return false;
  1633. }
  1634. break;
  1635. case Token_Mod:
  1636. case Token_ModMod:
  1637. case Token_ModEq:
  1638. case Token_ModModEq:
  1639. if (is_type_matrix(main_type)) {
  1640. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1641. return false;
  1642. }
  1643. if (!is_type_integer(type)) {
  1644. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1645. return false;
  1646. } else if (is_type_simd_vector(main_type)) {
  1647. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1648. return false;
  1649. }
  1650. break;
  1651. case Token_AndNot:
  1652. case Token_AndNotEq:
  1653. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1654. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1655. return false;
  1656. }
  1657. break;
  1658. case Token_CmpAnd:
  1659. case Token_CmpOr:
  1660. case Token_CmpAndEq:
  1661. case Token_CmpOrEq:
  1662. if (!is_type_boolean(type)) {
  1663. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1664. return false;
  1665. }
  1666. break;
  1667. default:
  1668. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1669. return false;
  1670. }
  1671. return true;
  1672. }
  1673. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1674. if (in_value.kind == ExactValue_Invalid) {
  1675. // NOTE(bill): There's already been an error
  1676. return true;
  1677. }
  1678. type = core_type(type);
  1679. if (type == t_invalid) {
  1680. return false;
  1681. } else if (is_type_boolean(type)) {
  1682. return in_value.kind == ExactValue_Bool;
  1683. } else if (is_type_string(type)) {
  1684. return in_value.kind == ExactValue_String;
  1685. } else if (is_type_integer(type) || is_type_rune(type)) {
  1686. if (in_value.kind == ExactValue_Bool) {
  1687. return false;
  1688. }
  1689. ExactValue v = exact_value_to_integer(in_value);
  1690. if (v.kind != ExactValue_Integer) {
  1691. return false;
  1692. }
  1693. if (out_value) *out_value = v;
  1694. if (is_type_untyped(type)) {
  1695. return true;
  1696. }
  1697. BigInt i = v.value_integer;
  1698. i64 byte_size = type_size_of(type);
  1699. BigInt umax = {};
  1700. BigInt imin = {};
  1701. BigInt imax = {};
  1702. if (c->bit_field_bit_size > 0) {
  1703. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1704. big_int_from_u64(&umax, 1);
  1705. big_int_from_i64(&imin, 1);
  1706. big_int_from_i64(&imax, 1);
  1707. BigInt bu = {};
  1708. BigInt bi = {};
  1709. big_int_from_i64(&bu, bit_size);
  1710. big_int_from_i64(&bi, bit_size-1);
  1711. big_int_shl_eq(&umax, &bu);
  1712. mp_decr(&umax);
  1713. big_int_shl_eq(&imin, &bi);
  1714. big_int_neg(&imin, &imin);
  1715. big_int_shl_eq(&imax, &bi);
  1716. mp_decr(&imax);
  1717. } else {
  1718. if (byte_size < 16) {
  1719. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1720. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1721. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1722. } else {
  1723. big_int_from_u64(&umax, 1);
  1724. big_int_from_i64(&imin, 1);
  1725. big_int_from_i64(&imax, 1);
  1726. BigInt bi128 = {};
  1727. BigInt bi127 = {};
  1728. big_int_from_i64(&bi128, 128);
  1729. big_int_from_i64(&bi127, 127);
  1730. big_int_shl_eq(&umax, &bi128);
  1731. mp_decr(&umax);
  1732. big_int_shl_eq(&imin, &bi127);
  1733. big_int_neg(&imin, &imin);
  1734. big_int_shl_eq(&imax, &bi127);
  1735. mp_decr(&imax);
  1736. }
  1737. }
  1738. switch (type->Basic.kind) {
  1739. case Basic_rune:
  1740. case Basic_i8:
  1741. case Basic_i16:
  1742. case Basic_i32:
  1743. case Basic_i64:
  1744. case Basic_i128:
  1745. case Basic_int:
  1746. case Basic_i16le:
  1747. case Basic_i32le:
  1748. case Basic_i64le:
  1749. case Basic_i128le:
  1750. case Basic_i16be:
  1751. case Basic_i32be:
  1752. case Basic_i64be:
  1753. case Basic_i128be:
  1754. {
  1755. // return imin <= i && i <= imax;
  1756. int a = big_int_cmp(&imin, &i);
  1757. int b = big_int_cmp(&i, &imax);
  1758. return (a <= 0) && (b <= 0);
  1759. }
  1760. case Basic_u8:
  1761. case Basic_u16:
  1762. case Basic_u32:
  1763. case Basic_u64:
  1764. case Basic_u128:
  1765. case Basic_uint:
  1766. case Basic_uintptr:
  1767. case Basic_u16le:
  1768. case Basic_u32le:
  1769. case Basic_u64le:
  1770. case Basic_u128le:
  1771. case Basic_u16be:
  1772. case Basic_u32be:
  1773. case Basic_u64be:
  1774. case Basic_u128be:
  1775. {
  1776. // return 0ull <= i && i <= umax;
  1777. int b = big_int_cmp(&i, &umax);
  1778. return !i.sign && (b <= 0);
  1779. }
  1780. case Basic_UntypedInteger:
  1781. return true;
  1782. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1783. }
  1784. } else if (is_type_float(type)) {
  1785. ExactValue v = exact_value_to_float(in_value);
  1786. if (v.kind != ExactValue_Float) {
  1787. return false;
  1788. }
  1789. if (out_value) *out_value = v;
  1790. switch (type->Basic.kind) {
  1791. case Basic_f16:
  1792. case Basic_f32:
  1793. case Basic_f64:
  1794. return true;
  1795. case Basic_f16le:
  1796. case Basic_f16be:
  1797. case Basic_f32le:
  1798. case Basic_f32be:
  1799. case Basic_f64le:
  1800. case Basic_f64be:
  1801. return true;
  1802. case Basic_UntypedFloat:
  1803. return true;
  1804. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1805. }
  1806. } else if (is_type_complex(type)) {
  1807. ExactValue v = exact_value_to_complex(in_value);
  1808. if (v.kind != ExactValue_Complex) {
  1809. return false;
  1810. }
  1811. switch (type->Basic.kind) {
  1812. case Basic_complex32:
  1813. case Basic_complex64:
  1814. case Basic_complex128: {
  1815. ExactValue real = exact_value_real(v);
  1816. ExactValue imag = exact_value_imag(v);
  1817. if (real.kind != ExactValue_Invalid &&
  1818. imag.kind != ExactValue_Invalid) {
  1819. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1820. return true;
  1821. }
  1822. break;
  1823. }
  1824. case Basic_UntypedComplex:
  1825. return true;
  1826. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1827. }
  1828. return false;
  1829. } else if (is_type_quaternion(type)) {
  1830. ExactValue v = exact_value_to_quaternion(in_value);
  1831. if (v.kind != ExactValue_Quaternion) {
  1832. return false;
  1833. }
  1834. switch (type->Basic.kind) {
  1835. case Basic_quaternion64:
  1836. case Basic_quaternion128:
  1837. case Basic_quaternion256: {
  1838. ExactValue real = exact_value_real(v);
  1839. ExactValue imag = exact_value_imag(v);
  1840. ExactValue jmag = exact_value_jmag(v);
  1841. ExactValue kmag = exact_value_kmag(v);
  1842. if (real.kind != ExactValue_Invalid &&
  1843. imag.kind != ExactValue_Invalid) {
  1844. 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));
  1845. return true;
  1846. }
  1847. break;
  1848. }
  1849. case Basic_UntypedComplex:
  1850. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1851. return true;
  1852. case Basic_UntypedQuaternion:
  1853. return true;
  1854. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1855. }
  1856. return false;
  1857. } else if (is_type_pointer(type)) {
  1858. if (in_value.kind == ExactValue_Pointer) {
  1859. return true;
  1860. }
  1861. if (in_value.kind == ExactValue_Integer) {
  1862. return false;
  1863. // return true;
  1864. }
  1865. if (in_value.kind == ExactValue_String) {
  1866. return false;
  1867. }
  1868. if (out_value) *out_value = in_value;
  1869. } else if (is_type_bit_set(type)) {
  1870. if (in_value.kind == ExactValue_Integer) {
  1871. return true;
  1872. }
  1873. }
  1874. return false;
  1875. }
  1876. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  1877. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1878. gbString b = type_to_string(type);
  1879. i64 sz = type_size_of(type);
  1880. i64 bit_size = 8*sz;
  1881. bool size_changed = false;
  1882. if (max_bit_size > 0) {
  1883. size_changed = (bit_size != max_bit_size);
  1884. bit_size = gb_min(bit_size, max_bit_size);
  1885. }
  1886. BigInt *bi = &o->value.value_integer;
  1887. if (is_type_unsigned(type)) {
  1888. if (big_int_is_neg(bi)) {
  1889. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1890. } else {
  1891. BigInt one = big_int_make_u64(1);
  1892. BigInt max_size = big_int_make_u64(1);
  1893. BigInt bits = big_int_make_i64(bit_size);
  1894. big_int_shl_eq(&max_size, &bits);
  1895. big_int_sub_eq(&max_size, &one);
  1896. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1897. if (size_changed) {
  1898. 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));
  1899. } else {
  1900. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1901. }
  1902. }
  1903. } else {
  1904. BigInt zero = big_int_make_u64(0);
  1905. BigInt one = big_int_make_u64(1);
  1906. BigInt max_size = big_int_make_u64(1);
  1907. BigInt bits = big_int_make_i64(bit_size - 1);
  1908. big_int_shl_eq(&max_size, &bits);
  1909. String max_size_str = {};
  1910. if (big_int_is_neg(bi)) {
  1911. big_int_neg(&max_size, &max_size);
  1912. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1913. } else {
  1914. big_int_sub_eq(&max_size, &one);
  1915. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1916. }
  1917. if (size_changed) {
  1918. 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));
  1919. } else {
  1920. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1921. }
  1922. }
  1923. gb_string_free(b);
  1924. return true;
  1925. }
  1926. return false;
  1927. }
  1928. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  1929. gbString a = expr_to_string(o->expr);
  1930. gbString b = type_to_string(type);
  1931. defer(
  1932. gb_string_free(b);
  1933. gb_string_free(a);
  1934. );
  1935. Type *src = base_type(o->type);
  1936. Type *dst = base_type(type);
  1937. if (is_type_array(src) && is_type_slice(dst)) {
  1938. Type *s = src->Array.elem;
  1939. Type *d = dst->Slice.elem;
  1940. if (are_types_identical(s, d)) {
  1941. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1942. }
  1943. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1944. Type *s = src->DynamicArray.elem;
  1945. Type *d = dst->Slice.elem;
  1946. if (are_types_identical(s, d)) {
  1947. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1948. }
  1949. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1950. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1951. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1952. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1953. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1954. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1955. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1956. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1957. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  1958. return;
  1959. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  1960. gbString s = expr_to_string(c->type_hint_expr);
  1961. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  1962. gb_string_free(s);
  1963. } else if (is_type_pointer(type) &&
  1964. o->mode == Addressing_Variable &&
  1965. are_types_identical(type_deref(type), o->type)) {
  1966. gbString s = expr_to_string(o->expr);
  1967. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  1968. gb_string_free(s);
  1969. } else if (is_type_pointer(o->type) &&
  1970. are_types_identical(type_deref(o->type), type)) {
  1971. gbString s = expr_to_string(o->expr);
  1972. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  1973. gb_string_free(s);
  1974. }
  1975. }
  1976. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1977. gbString a = expr_to_string(o->expr);
  1978. gbString b = type_to_string(type);
  1979. defer(
  1980. gb_string_free(b);
  1981. gb_string_free(a);
  1982. );
  1983. Type *src = base_type(o->type);
  1984. Type *dst = base_type(type);
  1985. if (is_type_array(src) && is_type_slice(dst)) {
  1986. Type *s = src->Array.elem;
  1987. Type *d = dst->Slice.elem;
  1988. if (are_types_identical(s, d)) {
  1989. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1990. }
  1991. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1992. if (is_type_uintptr(type)) {
  1993. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1994. } else {
  1995. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1996. i64 x = type_size_of(o->type);
  1997. i64 y = type_size_of(type);
  1998. if (x != y) {
  1999. 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);
  2000. }
  2001. }
  2002. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2003. if (is_type_uintptr(o->type)) {
  2004. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2005. } else {
  2006. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2007. }
  2008. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2009. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2010. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2011. return;
  2012. }
  2013. }
  2014. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2015. GB_ASSERT(o->mode == Addressing_Constant);
  2016. ExactValue out_value = o->value;
  2017. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2018. o->value = out_value;
  2019. return true;
  2020. } else {
  2021. o->value = out_value;
  2022. gbString a = expr_to_string(o->expr);
  2023. gbString b = type_to_string(type);
  2024. gbString c = type_to_string(o->type);
  2025. gbString s = exact_value_to_string(o->value);
  2026. defer(
  2027. gb_string_free(s);
  2028. gb_string_free(c);
  2029. gb_string_free(b);
  2030. gb_string_free(a);
  2031. o->mode = Addressing_Invalid;
  2032. );
  2033. ERROR_BLOCK();
  2034. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2035. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2036. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2037. } else {
  2038. i64 max_bit_size = 0;
  2039. if (ctx->bit_field_bit_size) {
  2040. max_bit_size = ctx->bit_field_bit_size;
  2041. }
  2042. if (are_types_identical(o->type, type)) {
  2043. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2044. } else {
  2045. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2046. }
  2047. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2048. }
  2049. } else {
  2050. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2051. check_assignment_error_suggestion(ctx, o, type);
  2052. }
  2053. return false;
  2054. }
  2055. }
  2056. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2057. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2058. if (o->expr->SelectorExpr.is_bit_field) {
  2059. return true;
  2060. }
  2061. }
  2062. if (o->mode == Addressing_OptionalOk) {
  2063. Ast *expr = unselector_expr(o->expr);
  2064. if (expr->kind != Ast_TypeAssertion) {
  2065. return true;
  2066. }
  2067. ast_node(ta, TypeAssertion, expr);
  2068. TypeAndValue tv = ta->expr->tav;
  2069. if (is_type_pointer(tv.type)) {
  2070. return false;
  2071. }
  2072. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2073. return false;
  2074. }
  2075. if (is_type_any(tv.type)) {
  2076. return false;
  2077. }
  2078. return true;
  2079. }
  2080. if (o->mode == Addressing_MapIndex) {
  2081. return false;
  2082. }
  2083. Ast *expr = unparen_expr(o->expr);
  2084. if (expr->kind == Ast_CompoundLit) {
  2085. return false;
  2086. }
  2087. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2088. }
  2089. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  2090. if (!(build_context.strict_style || (check_vet_flags(expr) & VetFlag_Style))) {
  2091. return;
  2092. }
  2093. Entity *e = entity_of_node(expr);
  2094. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  2095. GB_ASSERT(e->kind == Entity_Variable);
  2096. ERROR_BLOCK();
  2097. if ((e->flags & EntityFlag_ForValue) != 0) {
  2098. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2099. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  2100. if (is_type_map(parent_type)) {
  2101. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2102. } else {
  2103. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2104. }
  2105. } else {
  2106. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  2107. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  2108. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2109. }
  2110. }
  2111. }
  2112. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2113. switch (op.kind) {
  2114. case Token_And: { // Pointer address
  2115. if (check_is_not_addressable(c, o)) {
  2116. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2117. ast_node(ue, UnaryExpr, node);
  2118. gbString str = expr_to_string(ue->expr);
  2119. defer (gb_string_free(str));
  2120. Entity *e = entity_of_node(ue->expr);
  2121. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2122. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2123. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2124. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2125. } else {
  2126. switch (o->mode) {
  2127. case Addressing_Constant:
  2128. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2129. break;
  2130. case Addressing_SwizzleValue:
  2131. case Addressing_SwizzleVariable:
  2132. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2133. break;
  2134. default:
  2135. {
  2136. ERROR_BLOCK();
  2137. error(op, "Cannot take the pointer address of '%s'", str);
  2138. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2139. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2140. if (parent_type != nullptr && is_type_string(parent_type)) {
  2141. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2142. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2143. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2144. } else {
  2145. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2146. }
  2147. }
  2148. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2149. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2150. }
  2151. }
  2152. break;
  2153. }
  2154. }
  2155. }
  2156. o->mode = Addressing_Invalid;
  2157. return;
  2158. }
  2159. if (o->mode == Addressing_SoaVariable) {
  2160. ast_node(ue, UnaryExpr, node);
  2161. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2162. ast_node(ie, IndexExpr, ue->expr);
  2163. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2164. GB_ASSERT(is_type_soa_struct(soa_type));
  2165. o->type = alloc_type_soa_pointer(soa_type);
  2166. } else {
  2167. o->type = alloc_type_pointer(o->type);
  2168. }
  2169. } else {
  2170. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2171. ast_node(ue, UnaryExpr, node);
  2172. check_old_for_or_switch_value_usage(ue->expr);
  2173. }
  2174. o->type = alloc_type_pointer(o->type);
  2175. }
  2176. switch (o->mode) {
  2177. case Addressing_OptionalOk:
  2178. case Addressing_MapIndex:
  2179. o->mode = Addressing_OptionalOkPtr;
  2180. break;
  2181. default:
  2182. o->mode = Addressing_Value;
  2183. break;
  2184. }
  2185. return;
  2186. }
  2187. }
  2188. if (!check_unary_op(c, o, op)) {
  2189. o->mode = Addressing_Invalid;
  2190. return;
  2191. }
  2192. if (o->mode == Addressing_Constant) {
  2193. Type *type = base_type(o->type);
  2194. if (!is_type_constant_type(o->type)) {
  2195. gbString xt = type_to_string(o->type);
  2196. gbString err_str = expr_to_string(node);
  2197. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2198. gb_string_free(err_str);
  2199. gb_string_free(xt);
  2200. o->mode = Addressing_Invalid;
  2201. return;
  2202. }
  2203. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2204. gbString err_str = expr_to_string(node);
  2205. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2206. gb_string_free(err_str);
  2207. o->mode = Addressing_Invalid;
  2208. return;
  2209. }
  2210. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2211. gbString err_str = expr_to_string(node);
  2212. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2213. gb_string_free(err_str);
  2214. o->mode = Addressing_Invalid;
  2215. return;
  2216. }
  2217. i32 precision = 0;
  2218. if (is_type_typed(type)) {
  2219. precision = cast(i32)(8 * type_size_of(type));
  2220. }
  2221. bool is_unsigned = is_type_unsigned(type);
  2222. if (is_type_rune(type)) {
  2223. GB_ASSERT(!is_unsigned);
  2224. }
  2225. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2226. if (is_type_typed(type)) {
  2227. if (node != nullptr) {
  2228. o->expr = node;
  2229. }
  2230. check_is_expressible(c, o, type);
  2231. }
  2232. return;
  2233. }
  2234. o->mode = Addressing_Value;
  2235. }
  2236. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2237. if (t == nullptr) {
  2238. return;
  2239. }
  2240. t = base_type(t);
  2241. if (!is_type_comparable(t)) {
  2242. return;
  2243. }
  2244. switch (t->kind) {
  2245. case Type_Basic:
  2246. switch (t->Basic.kind) {
  2247. case Basic_complex32:
  2248. add_package_dependency(c, "runtime", "complex32_eq");
  2249. add_package_dependency(c, "runtime", "complex32_ne");
  2250. break;
  2251. case Basic_complex64:
  2252. add_package_dependency(c, "runtime", "complex64_eq");
  2253. add_package_dependency(c, "runtime", "complex64_ne");
  2254. break;
  2255. case Basic_complex128:
  2256. add_package_dependency(c, "runtime", "complex128_eq");
  2257. add_package_dependency(c, "runtime", "complex128_ne");
  2258. break;
  2259. case Basic_quaternion64:
  2260. add_package_dependency(c, "runtime", "quaternion64_eq");
  2261. add_package_dependency(c, "runtime", "quaternion64_ne");
  2262. break;
  2263. case Basic_quaternion128:
  2264. add_package_dependency(c, "runtime", "quaternion128_eq");
  2265. add_package_dependency(c, "runtime", "quaternion128_ne");
  2266. break;
  2267. case Basic_quaternion256:
  2268. add_package_dependency(c, "runtime", "quaternion256_eq");
  2269. add_package_dependency(c, "runtime", "quaternion256_ne");
  2270. break;
  2271. case Basic_cstring:
  2272. add_package_dependency(c, "runtime", "cstring_eq");
  2273. add_package_dependency(c, "runtime", "cstring_ne");
  2274. break;
  2275. case Basic_string:
  2276. add_package_dependency(c, "runtime", "string_eq");
  2277. add_package_dependency(c, "runtime", "string_ne");
  2278. break;
  2279. }
  2280. break;
  2281. case Type_Struct:
  2282. for (Entity *field : t->Struct.fields) {
  2283. add_comparison_procedures_for_fields(c, field->type);
  2284. }
  2285. break;
  2286. }
  2287. }
  2288. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2289. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2290. bool comp = are_types_identical(x->type, y->type);
  2291. switch (op) {
  2292. case Token_CmpEq: /* comp = comp; */ break;
  2293. case Token_NotEq: comp = !comp; break;
  2294. }
  2295. x->mode = Addressing_Constant;
  2296. x->type = t_untyped_bool;
  2297. x->value = exact_value_bool(comp);
  2298. return;
  2299. }
  2300. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2301. add_type_info_type(c, x->type);
  2302. add_type_info_type(c, y->type);
  2303. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2304. x->mode = Addressing_Value;
  2305. x->type = t_untyped_bool;
  2306. return;
  2307. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2308. add_type_info_type(c, x->type);
  2309. add_type_info_type(c, y->type);
  2310. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2311. x->mode = Addressing_Value;
  2312. x->type = t_untyped_bool;
  2313. return;
  2314. }
  2315. TEMPORARY_ALLOCATOR_GUARD();
  2316. gbString err_str = nullptr;
  2317. if (check_is_assignable_to(c, x, y->type) ||
  2318. check_is_assignable_to(c, y, x->type)) {
  2319. Type *err_type = x->type;
  2320. bool defined = false;
  2321. switch (op) {
  2322. case Token_CmpEq:
  2323. case Token_NotEq:
  2324. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2325. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2326. (is_operand_nil(*y) && type_has_nil(x->type));
  2327. break;
  2328. case Token_Lt:
  2329. case Token_Gt:
  2330. case Token_LtEq:
  2331. case Token_GtEq:
  2332. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2333. defined = true;
  2334. } else {
  2335. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2336. }
  2337. break;
  2338. }
  2339. if (!defined) {
  2340. gbString xs = type_to_string(x->type, temporary_allocator());
  2341. gbString ys = type_to_string(y->type, temporary_allocator());
  2342. err_str = gb_string_make(temporary_allocator(),
  2343. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2344. );
  2345. } else {
  2346. Type *comparison_type = x->type;
  2347. if (x->type == err_type && is_operand_nil(*x)) {
  2348. comparison_type = y->type;
  2349. }
  2350. add_comparison_procedures_for_fields(c, comparison_type);
  2351. }
  2352. } else {
  2353. gbString xt, yt;
  2354. if (x->mode == Addressing_ProcGroup) {
  2355. xt = gb_string_make(temporary_allocator(), "procedure group");
  2356. } else {
  2357. xt = type_to_string(x->type);
  2358. }
  2359. if (y->mode == Addressing_ProcGroup) {
  2360. yt = gb_string_make(temporary_allocator(), "procedure group");
  2361. } else {
  2362. yt = type_to_string(y->type);
  2363. }
  2364. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2365. }
  2366. if (err_str != nullptr) {
  2367. error(node, "Cannot compare expression, %s", err_str);
  2368. x->type = t_untyped_bool;
  2369. } else {
  2370. if (x->mode == Addressing_Constant &&
  2371. y->mode == Addressing_Constant) {
  2372. if (is_type_constant_type(x->type)) {
  2373. if (is_type_bit_set(x->type)) {
  2374. switch (op) {
  2375. case Token_CmpEq:
  2376. case Token_NotEq:
  2377. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2378. break;
  2379. case Token_Lt:
  2380. case Token_LtEq:
  2381. {
  2382. ExactValue lhs = x->value;
  2383. ExactValue rhs = y->value;
  2384. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2385. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2386. if (op == Token_Lt) {
  2387. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2388. }
  2389. x->value = res;
  2390. break;
  2391. }
  2392. case Token_Gt:
  2393. case Token_GtEq:
  2394. {
  2395. ExactValue lhs = x->value;
  2396. ExactValue rhs = y->value;
  2397. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2398. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2399. if (op == Token_Gt) {
  2400. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2401. }
  2402. x->value = res;
  2403. break;
  2404. }
  2405. }
  2406. } else {
  2407. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2408. }
  2409. } else {
  2410. x->mode = Addressing_Value;
  2411. }
  2412. } else {
  2413. x->mode = Addressing_Value;
  2414. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2415. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2416. i64 size = 0;
  2417. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2418. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2419. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2420. switch (op) {
  2421. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2422. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2423. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2424. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2425. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2426. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2427. }
  2428. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2429. switch (op) {
  2430. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2431. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2432. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2433. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2434. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2435. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2436. }
  2437. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2438. switch (op) {
  2439. case Token_CmpEq:
  2440. switch (8*size) {
  2441. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2442. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2443. }
  2444. break;
  2445. case Token_NotEq:
  2446. switch (8*size) {
  2447. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2448. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2449. }
  2450. break;
  2451. }
  2452. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2453. switch (op) {
  2454. case Token_CmpEq:
  2455. switch (8*size) {
  2456. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2457. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2458. }
  2459. break;
  2460. case Token_NotEq:
  2461. switch (8*size) {
  2462. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2463. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2464. }
  2465. break;
  2466. }
  2467. }
  2468. }
  2469. x->type = t_untyped_bool;
  2470. }
  2471. }
  2472. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2473. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2474. ast_node(be, BinaryExpr, node);
  2475. ExactValue x_val = {};
  2476. if (x->mode == Addressing_Constant) {
  2477. x_val = exact_value_to_integer(x->value);
  2478. }
  2479. bool x_is_untyped = is_type_untyped(x->type);
  2480. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2481. gbString err_str = expr_to_string(x->expr);
  2482. error(node, "Shifted operand '%s' must be an integer", err_str);
  2483. gb_string_free(err_str);
  2484. x->mode = Addressing_Invalid;
  2485. return;
  2486. }
  2487. if (is_type_unsigned(y->type)) {
  2488. } else if (is_type_untyped(y->type)) {
  2489. convert_to_typed(c, y, t_untyped_integer);
  2490. if (y->mode == Addressing_Invalid) {
  2491. x->mode = Addressing_Invalid;
  2492. return;
  2493. }
  2494. } else {
  2495. gbString err_str = expr_to_string(y->expr);
  2496. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2497. gb_string_free(err_str);
  2498. x->mode = Addressing_Invalid;
  2499. return;
  2500. }
  2501. if (x->mode == Addressing_Constant) {
  2502. if (y->mode == Addressing_Constant) {
  2503. ExactValue y_val = exact_value_to_integer(y->value);
  2504. if (y_val.kind != ExactValue_Integer) {
  2505. gbString err_str = expr_to_string(y->expr);
  2506. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2507. gb_string_free(err_str);
  2508. x->mode = Addressing_Invalid;
  2509. return;
  2510. }
  2511. BigInt max_shift = {};
  2512. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2513. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2514. gbString err_str = expr_to_string(y->expr);
  2515. error(node, "Shift amount too large: '%s'", err_str);
  2516. gb_string_free(err_str);
  2517. x->mode = Addressing_Invalid;
  2518. return;
  2519. }
  2520. if (!is_type_integer(x->type)) {
  2521. // NOTE(bill): It could be an untyped float but still representable
  2522. // as an integer
  2523. x->type = t_untyped_integer;
  2524. }
  2525. x->expr = node;
  2526. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2527. if (is_type_typed(x->type)) {
  2528. check_is_expressible(c, x, x->type);
  2529. }
  2530. return;
  2531. }
  2532. TokenPos pos = ast_token(x->expr).pos;
  2533. if (x_is_untyped) {
  2534. if (x->expr != nullptr) {
  2535. x->expr->tav.is_lhs = true;
  2536. }
  2537. x->mode = Addressing_Value;
  2538. if (type_hint) {
  2539. if (is_type_integer(type_hint)) {
  2540. x->type = type_hint;
  2541. } else {
  2542. gbString x_str = expr_to_string(x->expr);
  2543. gbString to_type = type_to_string(type_hint);
  2544. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2545. gb_string_free(x_str);
  2546. gb_string_free(to_type);
  2547. x->mode = Addressing_Invalid;
  2548. }
  2549. } else if (!is_type_integer(x->type)) {
  2550. gbString x_str = expr_to_string(x->expr);
  2551. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2552. gb_string_free(x_str);
  2553. x->mode = Addressing_Invalid;
  2554. }
  2555. // x->value = x_val;
  2556. return;
  2557. }
  2558. }
  2559. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2560. gbString err_str = expr_to_string(y->expr);
  2561. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2562. gb_string_free(err_str);
  2563. }
  2564. if (!is_type_integer(x->type)) {
  2565. gbString err_str = expr_to_string(x->expr);
  2566. error(node, "Shift operand '%s' must be an integer", err_str);
  2567. gb_string_free(err_str);
  2568. x->mode = Addressing_Invalid;
  2569. return;
  2570. }
  2571. if (is_type_untyped(y->type)) {
  2572. convert_to_typed(c, y, t_uint);
  2573. }
  2574. x->mode = Addressing_Value;
  2575. }
  2576. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2577. if (check_is_assignable_to(c, operand, y)) {
  2578. return true;
  2579. }
  2580. bool is_constant = operand->mode == Addressing_Constant;
  2581. Type *x = operand->type;
  2582. Type *src = core_type(x);
  2583. Type *dst = core_type(y);
  2584. if (are_types_identical(src, dst)) {
  2585. return true;
  2586. }
  2587. // if (is_type_tuple(src)) {
  2588. // Ast *expr = unparen_expr(operand->expr);
  2589. // if (expr && expr->kind == Ast_CallExpr) {
  2590. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2591. // ast_node(ce, CallExpr, expr);
  2592. // Type *pt = base_type(type_of_expr(ce->proc));
  2593. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2594. // if (pt->Proc.result_count > 0) {
  2595. // Operand op = *operand;
  2596. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2597. // bool ok = check_is_castable_to(c, &op, y);
  2598. // if (ok) {
  2599. // ce->optional_ok_one = true;
  2600. // }
  2601. // return ok;
  2602. // }
  2603. // }
  2604. // }
  2605. // }
  2606. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2607. if (is_type_u8_array(dst)) {
  2608. String s = operand->value.value_string;
  2609. return s.len == dst->Array.count;
  2610. }
  2611. if (is_type_rune_array(dst)) {
  2612. String s = operand->value.value_string;
  2613. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2614. }
  2615. }
  2616. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2617. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2618. return dst->Array.count == src->Array.count;
  2619. }
  2620. }
  2621. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2622. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2623. }
  2624. // Cast between booleans and integers
  2625. if (is_type_boolean(src) || is_type_integer(src)) {
  2626. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2627. return true;
  2628. }
  2629. }
  2630. // Cast between numbers
  2631. if (is_type_integer(src) || is_type_float(src)) {
  2632. if (is_type_integer(dst) || is_type_float(dst)) {
  2633. return true;
  2634. }
  2635. }
  2636. if (is_type_bit_field(src)) {
  2637. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2638. }
  2639. if (is_type_bit_field(dst)) {
  2640. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2641. }
  2642. if (is_type_integer(src) && is_type_rune(dst)) {
  2643. return true;
  2644. }
  2645. if (is_type_rune(src) && is_type_integer(dst)) {
  2646. return true;
  2647. }
  2648. if (is_type_complex(src) && is_type_complex(dst)) {
  2649. return true;
  2650. }
  2651. if (is_type_float(src) && is_type_complex(dst)) {
  2652. return true;
  2653. }
  2654. if (is_type_float(src) && is_type_quaternion(dst)) {
  2655. return true;
  2656. }
  2657. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2658. return true;
  2659. }
  2660. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2661. return true;
  2662. }
  2663. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2664. GB_ASSERT(src->kind == Type_Matrix);
  2665. GB_ASSERT(dst->kind == Type_Matrix);
  2666. Operand op = *operand;
  2667. op.type = src->Matrix.elem;
  2668. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2669. return false;
  2670. }
  2671. if (src->Matrix.row_count != src->Matrix.column_count) {
  2672. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2673. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2674. return src_count == dst_count;
  2675. }
  2676. return is_matrix_square(dst) && is_matrix_square(src);
  2677. }
  2678. // Cast between pointers
  2679. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2680. return true;
  2681. }
  2682. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2683. return true;
  2684. }
  2685. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2686. return true;
  2687. }
  2688. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2689. return true;
  2690. }
  2691. // uintptr <-> pointer
  2692. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2693. return true;
  2694. }
  2695. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2696. return true;
  2697. }
  2698. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2699. return true;
  2700. }
  2701. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2702. return true;
  2703. }
  2704. // []byte/[]u8 <-> string (not cstring)
  2705. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2706. return true;
  2707. }
  2708. // cstring -> string
  2709. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2710. if (operand->mode != Addressing_Constant) {
  2711. add_package_dependency(c, "runtime", "cstring_to_string");
  2712. }
  2713. return true;
  2714. }
  2715. // cstring -> ^u8
  2716. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2717. return !is_constant;
  2718. }
  2719. // cstring -> [^]u8
  2720. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2721. return !is_constant;
  2722. }
  2723. // cstring -> rawptr
  2724. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2725. return !is_constant;
  2726. }
  2727. // ^u8 -> cstring
  2728. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2729. return !is_constant;
  2730. }
  2731. // [^]u8 -> cstring
  2732. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2733. return !is_constant;
  2734. }
  2735. // rawptr -> cstring
  2736. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2737. return !is_constant;
  2738. }
  2739. // proc <-> proc
  2740. if (is_type_proc(src) && is_type_proc(dst)) {
  2741. if (is_type_polymorphic(dst)) {
  2742. if (is_type_polymorphic(src) &&
  2743. operand->mode == Addressing_Variable) {
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. return true;
  2749. }
  2750. // proc -> rawptr
  2751. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2752. return true;
  2753. }
  2754. // rawptr -> proc
  2755. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2756. return true;
  2757. }
  2758. if (is_type_array(dst)) {
  2759. Type *elem = base_array_type(dst);
  2760. if (check_is_castable_to(c, operand, elem)) {
  2761. return true;
  2762. }
  2763. }
  2764. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2765. if (src->SimdVector.count != dst->SimdVector.count) {
  2766. return false;
  2767. }
  2768. Type *elem_src = base_array_type(src);
  2769. Type *elem_dst = base_array_type(dst);
  2770. Operand x = {};
  2771. x.type = elem_src;
  2772. x.mode = Addressing_Value;
  2773. return check_is_castable_to(c, &x, elem_dst);
  2774. }
  2775. if (is_type_simd_vector(dst)) {
  2776. Type *elem = base_array_type(dst);
  2777. if (check_is_castable_to(c, operand, elem)) {
  2778. return true;
  2779. }
  2780. }
  2781. return false;
  2782. }
  2783. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2784. bool is_const_expr = x->mode == Addressing_Constant;
  2785. Type *bt = base_type(type);
  2786. if (is_const_expr && is_type_constant_type(bt)) {
  2787. if (core_type(bt)->kind == Type_Basic) {
  2788. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2789. return true;
  2790. } else if (check_is_castable_to(c, x, type)) {
  2791. if (is_type_pointer(type)) {
  2792. return true;
  2793. }
  2794. }
  2795. } else if (check_is_castable_to(c, x, type)) {
  2796. x->value = {};
  2797. x->mode = Addressing_Value;
  2798. return true;
  2799. }
  2800. } else if (check_is_castable_to(c, x, type)) {
  2801. if (x->mode != Addressing_Constant) {
  2802. x->mode = Addressing_Value;
  2803. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2804. x->mode = Addressing_Value;
  2805. } else if (is_type_union(type)) {
  2806. x->mode = Addressing_Value;
  2807. }
  2808. if (x->mode == Addressing_Value) {
  2809. x->value = {};
  2810. }
  2811. return true;
  2812. }
  2813. return false;
  2814. }
  2815. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2816. if (!is_operand_value(*x)) {
  2817. error(x->expr, "Only values can be casted");
  2818. x->mode = Addressing_Invalid;
  2819. return;
  2820. }
  2821. bool is_const_expr = x->mode == Addressing_Constant;
  2822. bool can_convert = check_cast_internal(c, x, type);
  2823. if (!can_convert) {
  2824. TEMPORARY_ALLOCATOR_GUARD();
  2825. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2826. gbString to_type = type_to_string(type, temporary_allocator());
  2827. gbString from_type = type_to_string(x->type, temporary_allocator());
  2828. x->mode = Addressing_Invalid;
  2829. ERROR_BLOCK();
  2830. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2831. if (is_const_expr) {
  2832. gbString val_str = exact_value_to_string(x->value);
  2833. if (is_type_float(x->type) && is_type_integer(type)) {
  2834. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2835. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2836. x->mode = Addressing_Constant;
  2837. x->type = type;
  2838. } else {
  2839. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2840. if (is_type_numeric(type)) {
  2841. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2842. x->mode = Addressing_Constant;
  2843. x->type = type;
  2844. }
  2845. }
  2846. gb_string_free(val_str);
  2847. }
  2848. check_cast_error_suggestion(c, x, type);
  2849. return;
  2850. }
  2851. if (is_type_untyped(x->type)) {
  2852. Type *final_type = type;
  2853. if (is_const_expr && !is_type_constant_type(type)) {
  2854. final_type = default_type(x->type);
  2855. }
  2856. update_untyped_expr_type(c, x->expr, final_type, true);
  2857. } else {
  2858. Type *src = core_type(x->type);
  2859. Type *dst = core_type(type);
  2860. if (src != dst) {
  2861. bool const REQUIRE = true;
  2862. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  2863. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  2864. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  2865. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  2866. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  2867. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  2868. } else if (src == t_f16 && is_type_float(dst)) {
  2869. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  2870. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  2871. } else if (is_type_float(dst) && dst == t_f16) {
  2872. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  2873. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  2874. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  2875. }
  2876. }
  2877. }
  2878. x->type = type;
  2879. }
  2880. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2881. if (!is_operand_value(*o)) {
  2882. error(o->expr, "'transmute' can only be applied to values");
  2883. o->mode = Addressing_Invalid;
  2884. return false;
  2885. }
  2886. // if (o->mode == Addressing_Constant) {
  2887. // gbString expr_str = expr_to_string(o->expr);
  2888. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2889. // gb_string_free(expr_str);
  2890. // o->mode = Addressing_Invalid;
  2891. // o->expr = node;
  2892. // return false;
  2893. // }
  2894. Type *src_t = o->type;
  2895. Type *dst_t = t;
  2896. Type *src_bt = base_type(src_t);
  2897. Type *dst_bt = base_type(dst_t);
  2898. if (is_type_untyped(src_t)) {
  2899. gbString expr_str = expr_to_string(o->expr);
  2900. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2901. gb_string_free(expr_str);
  2902. o->mode = Addressing_Invalid;
  2903. o->expr = node;
  2904. return false;
  2905. }
  2906. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2907. GB_ASSERT(global_error_collector.count != 0);
  2908. o->mode = Addressing_Invalid;
  2909. o->expr = node;
  2910. return false;
  2911. }
  2912. if (src_bt == nullptr || src_bt == t_invalid) {
  2913. // NOTE(bill): this should be an error
  2914. GB_ASSERT(global_error_collector.count != 0);
  2915. o->mode = Addressing_Value;
  2916. o->expr = node;
  2917. o->type = dst_t;
  2918. return true;
  2919. }
  2920. i64 srcz = type_size_of(src_t);
  2921. i64 dstz = type_size_of(dst_t);
  2922. if (srcz != dstz) {
  2923. gbString expr_str = expr_to_string(o->expr);
  2924. gbString type_str = type_to_string(dst_t);
  2925. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2926. gb_string_free(type_str);
  2927. gb_string_free(expr_str);
  2928. o->mode = Addressing_Invalid;
  2929. o->expr = node;
  2930. return false;
  2931. }
  2932. o->expr = node;
  2933. o->type = dst_t;
  2934. if (o->mode == Addressing_Constant) {
  2935. if (are_types_identical(src_bt, dst_bt)) {
  2936. return true;
  2937. }
  2938. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2939. if (types_have_same_internal_endian(src_t, dst_t)) {
  2940. ExactValue src_v = exact_value_to_integer(o->value);
  2941. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2942. BigInt v = src_v.value_integer;
  2943. BigInt smax = {};
  2944. BigInt umax = {};
  2945. big_int_from_u64(&smax, 0);
  2946. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2947. big_int_from_u64(&umax, 1);
  2948. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2949. big_int_shl_eq(&umax, &sz_in_bits);
  2950. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2951. if (big_int_cmp(&v, &smax) >= 0) {
  2952. big_int_sub_eq(&v, &umax);
  2953. }
  2954. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2955. if (big_int_is_neg(&v)) {
  2956. big_int_add_eq(&v, &umax);
  2957. }
  2958. }
  2959. o->value.kind = ExactValue_Integer;
  2960. o->value.value_integer = v;
  2961. return true;
  2962. }
  2963. }
  2964. }
  2965. o->mode = Addressing_Value;
  2966. o->value = {};
  2967. return true;
  2968. }
  2969. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2970. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2971. if (check_is_assignable_to(c, y, x->type)) {
  2972. if (check_binary_op(c, x, op)) {
  2973. return true;
  2974. }
  2975. }
  2976. }
  2977. return false;
  2978. }
  2979. gb_internal bool is_ise_expr(Ast *node) {
  2980. node = unparen_expr(node);
  2981. return node->kind == Ast_ImplicitSelectorExpr;
  2982. }
  2983. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2984. if (use_lhs_as_type_hint) { // RHS in this case
  2985. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2986. }
  2987. return false;
  2988. }
  2989. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2990. Type *xt = base_type(matrix);
  2991. if (type_hint != nullptr) {
  2992. Type *th = base_type(type_hint);
  2993. if (are_types_identical(th, xt)) {
  2994. return type_hint;
  2995. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  2996. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  2997. // ignore
  2998. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  2999. xt->Matrix.column_count == th->Matrix.column_count) {
  3000. return type_hint;
  3001. }
  3002. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3003. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3004. // ignore
  3005. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3006. return type_hint;
  3007. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3008. return type_hint;
  3009. }
  3010. }
  3011. }
  3012. return matrix;
  3013. }
  3014. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3015. if (!check_binary_op(c, x, op)) {
  3016. x->mode = Addressing_Invalid;
  3017. return;
  3018. }
  3019. Type *xt = base_type(x->type);
  3020. Type *yt = base_type(y->type);
  3021. if (is_type_matrix(x->type)) {
  3022. GB_ASSERT(xt->kind == Type_Matrix);
  3023. if (op.kind == Token_Mul) {
  3024. if (yt->kind == Type_Matrix) {
  3025. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3026. goto matrix_error;
  3027. }
  3028. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3029. goto matrix_error;
  3030. }
  3031. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3032. goto matrix_error;
  3033. }
  3034. x->mode = Addressing_Value;
  3035. if (are_types_identical(xt, yt)) {
  3036. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3037. // prefer the named type
  3038. x->type = y->type;
  3039. }
  3040. } else {
  3041. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3042. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3043. }
  3044. goto matrix_success;
  3045. } else if (yt->kind == Type_Array) {
  3046. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3047. goto matrix_error;
  3048. }
  3049. if (xt->Matrix.column_count != yt->Array.count) {
  3050. goto matrix_error;
  3051. }
  3052. // Treat arrays as column vectors
  3053. x->mode = Addressing_Value;
  3054. if (xt->Matrix.row_count == yt->Array.count) {
  3055. x->type = y->type;
  3056. } else {
  3057. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3058. }
  3059. goto matrix_success;
  3060. }
  3061. }
  3062. if (!are_types_identical(xt, yt)) {
  3063. goto matrix_error;
  3064. }
  3065. x->mode = Addressing_Value;
  3066. x->type = xt;
  3067. goto matrix_success;
  3068. } else {
  3069. GB_ASSERT(!is_type_matrix(xt));
  3070. GB_ASSERT(is_type_matrix(yt));
  3071. if (op.kind == Token_Mul) {
  3072. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3073. if (xt->kind == Type_Array) {
  3074. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3075. goto matrix_error;
  3076. }
  3077. if (xt->Array.count != yt->Matrix.row_count) {
  3078. goto matrix_error;
  3079. }
  3080. // Treat arrays as row vectors
  3081. x->mode = Addressing_Value;
  3082. if (yt->Matrix.column_count == xt->Array.count) {
  3083. x->type = x->type;
  3084. } else {
  3085. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3086. }
  3087. goto matrix_success;
  3088. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3089. x->type = check_matrix_type_hint(y->type, type_hint);
  3090. return;
  3091. }
  3092. }
  3093. if (!are_types_identical(xt, yt)) {
  3094. goto matrix_error;
  3095. }
  3096. x->mode = Addressing_Value;
  3097. x->type = xt;
  3098. goto matrix_success;
  3099. }
  3100. matrix_success:
  3101. x->type = check_matrix_type_hint(x->type, type_hint);
  3102. return;
  3103. matrix_error:
  3104. gbString xts = type_to_string(x->type);
  3105. gbString yts = type_to_string(y->type);
  3106. gbString expr_str = expr_to_string(x->expr);
  3107. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3108. gb_string_free(expr_str);
  3109. gb_string_free(yts);
  3110. gb_string_free(xts);
  3111. x->type = t_invalid;
  3112. x->mode = Addressing_Invalid;
  3113. return;
  3114. }
  3115. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3116. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3117. Operand y_ = {}, *y = &y_;
  3118. ast_node(be, BinaryExpr, node);
  3119. defer({
  3120. node->viral_state_flags |= be->left->viral_state_flags;
  3121. node->viral_state_flags |= be->right->viral_state_flags;
  3122. });
  3123. Token op = be->op;
  3124. switch (op.kind) {
  3125. case Token_CmpEq:
  3126. case Token_NotEq: {
  3127. // NOTE(bill): Allow comparisons between types
  3128. if (is_ise_expr(be->left)) {
  3129. // Evalute the right before the left for an '.X' expression
  3130. check_expr_or_type(c, y, be->right, type_hint);
  3131. check_expr_or_type(c, x, be->left, y->type);
  3132. } else {
  3133. check_expr_or_type(c, x, be->left, type_hint);
  3134. check_expr_or_type(c, y, be->right, x->type);
  3135. }
  3136. bool xt = x->mode == Addressing_Type;
  3137. bool yt = y->mode == Addressing_Type;
  3138. // If only one is a type, this is an error
  3139. if (xt ^ yt) {
  3140. GB_ASSERT(xt != yt);
  3141. if (xt) {
  3142. if (!is_type_typeid(y->type)) {
  3143. error_operand_not_expression(x);
  3144. }
  3145. }
  3146. if (yt) {
  3147. if (!is_type_typeid(x->type)) {
  3148. error_operand_not_expression(y);
  3149. }
  3150. }
  3151. }
  3152. break;
  3153. }
  3154. case Token_in:
  3155. case Token_not_in:
  3156. {
  3157. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3158. check_expr(c, y, be->right);
  3159. Type *rhs_type = type_deref(y->type);
  3160. if (is_type_bit_set(rhs_type)) {
  3161. Type *elem = base_type(rhs_type)->BitSet.elem;
  3162. check_expr_with_type_hint(c, x, be->left, elem);
  3163. } else if (is_type_map(rhs_type)) {
  3164. Type *key = base_type(rhs_type)->Map.key;
  3165. check_expr_with_type_hint(c, x, be->left, key);
  3166. } else {
  3167. check_expr(c, x, be->left);
  3168. }
  3169. if (x->mode == Addressing_Invalid) {
  3170. return;
  3171. }
  3172. if (y->mode == Addressing_Invalid) {
  3173. x->mode = Addressing_Invalid;
  3174. x->expr = y->expr;
  3175. return;
  3176. }
  3177. if (is_type_map(rhs_type)) {
  3178. Type *yt = base_type(rhs_type);
  3179. if (op.kind == Token_in) {
  3180. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3181. } else {
  3182. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3183. }
  3184. add_map_get_dependencies(c);
  3185. } else if (is_type_bit_set(rhs_type)) {
  3186. Type *yt = base_type(rhs_type);
  3187. if (op.kind == Token_in) {
  3188. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3189. } else {
  3190. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3191. }
  3192. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3193. ExactValue k = exact_value_to_integer(x->value);
  3194. ExactValue v = exact_value_to_integer(y->value);
  3195. GB_ASSERT(k.kind == ExactValue_Integer);
  3196. GB_ASSERT(v.kind == ExactValue_Integer);
  3197. i64 key = big_int_to_i64(&k.value_integer);
  3198. i64 lower = yt->BitSet.lower;
  3199. i64 upper = yt->BitSet.upper;
  3200. if (lower <= key && key <= upper) {
  3201. i64 bit = 1ll<<key;
  3202. i64 bits = big_int_to_i64(&v.value_integer);
  3203. x->mode = Addressing_Constant;
  3204. x->type = t_untyped_bool;
  3205. if (op.kind == Token_in) {
  3206. x->value = exact_value_bool((bit & bits) != 0);
  3207. } else {
  3208. x->value = exact_value_bool((bit & bits) == 0);
  3209. }
  3210. x->expr = node;
  3211. return;
  3212. } else {
  3213. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3214. x->mode = Addressing_Invalid;
  3215. }
  3216. }
  3217. } else {
  3218. gbString t = type_to_string(y->type);
  3219. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3220. gb_string_free(t);
  3221. x->expr = node;
  3222. x->mode = Addressing_Invalid;
  3223. return;
  3224. }
  3225. if (x->mode != Addressing_Invalid) {
  3226. x->mode = Addressing_Value;
  3227. x->type = t_untyped_bool;
  3228. }
  3229. x->expr = node;
  3230. return;
  3231. }
  3232. default:
  3233. if (is_ise_expr(be->left)) {
  3234. // Evalute the right before the left for an '.X' expression
  3235. check_expr_or_type(c, y, be->right, type_hint);
  3236. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3237. check_expr_or_type(c, x, be->left, y->type);
  3238. } else {
  3239. check_expr_with_type_hint(c, x, be->left, type_hint);
  3240. }
  3241. } else {
  3242. check_expr_with_type_hint(c, x, be->left, type_hint);
  3243. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3244. check_expr_with_type_hint(c, y, be->right, x->type);
  3245. } else {
  3246. check_expr_with_type_hint(c, y, be->right, type_hint);
  3247. }
  3248. }
  3249. break;
  3250. }
  3251. if (x->mode == Addressing_Invalid) {
  3252. return;
  3253. }
  3254. if (y->mode == Addressing_Invalid) {
  3255. x->mode = Addressing_Invalid;
  3256. x->expr = y->expr;
  3257. return;
  3258. }
  3259. if (x->mode == Addressing_Builtin) {
  3260. x->mode = Addressing_Invalid;
  3261. error(x->expr, "built-in expression in binary expression");
  3262. return;
  3263. }
  3264. if (y->mode == Addressing_Builtin) {
  3265. x->mode = Addressing_Invalid;
  3266. error(y->expr, "built-in expression in binary expression");
  3267. return;
  3268. }
  3269. if (x->mode == Addressing_ProcGroup) {
  3270. x->mode = Addressing_Invalid;
  3271. if (x->proc_group != nullptr) {
  3272. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3273. } else {
  3274. error(x->expr, "procedure group used in binary expression");
  3275. }
  3276. return;
  3277. }
  3278. if (y->mode == Addressing_ProcGroup) {
  3279. x->mode = Addressing_Invalid;
  3280. if (x->proc_group != nullptr) {
  3281. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3282. } else {
  3283. error(y->expr, "procedure group used in binary expression");
  3284. }
  3285. return;
  3286. }
  3287. if (token_is_shift(op.kind)) {
  3288. check_shift(c, x, y, node, type_hint);
  3289. return;
  3290. }
  3291. switch (op.kind) {
  3292. case Token_Quo:
  3293. case Token_Mod:
  3294. case Token_ModMod:
  3295. case Token_QuoEq:
  3296. case Token_ModEq:
  3297. case Token_ModModEq:
  3298. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3299. is_type_float(x->type) && is_type_untyped(x->type)) {
  3300. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3301. gbString t = type_to_string(y->type);
  3302. if (x->value.kind != ExactValue_Invalid) {
  3303. gbString s = exact_value_to_string(x->value);
  3304. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3305. gb_string_free(s);
  3306. } else {
  3307. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3308. }
  3309. gb_string_free(t);
  3310. }
  3311. break;
  3312. }
  3313. convert_to_typed(c, x, y->type);
  3314. if (x->mode == Addressing_Invalid) {
  3315. return;
  3316. }
  3317. convert_to_typed(c, y, x->type);
  3318. if (y->mode == Addressing_Invalid) {
  3319. x->mode = Addressing_Invalid;
  3320. return;
  3321. }
  3322. if (token_is_comparison(op.kind)) {
  3323. check_comparison(c, node, x, y, op.kind);
  3324. return;
  3325. }
  3326. if (check_binary_array_expr(c, op, x, y)) {
  3327. x->mode = Addressing_Value;
  3328. x->type = x->type;
  3329. return;
  3330. }
  3331. if (check_binary_array_expr(c, op, y, x)) {
  3332. x->mode = Addressing_Value;
  3333. x->type = y->type;
  3334. return;
  3335. }
  3336. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3337. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3338. x->expr = node;
  3339. return;
  3340. }
  3341. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3342. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3343. // NOTE(bill, 2022-06-26)
  3344. // Allow any boolean types within `&&` and `||`
  3345. // This is an exception to all other binary expressions since the result
  3346. // of a comparison will always be an untyped boolean, and allowing
  3347. // any boolean between these two simplifies a lot of expressions
  3348. } else if (!are_types_identical(x->type, y->type)) {
  3349. if (x->type != t_invalid &&
  3350. y->type != t_invalid) {
  3351. gbString xt = type_to_string(x->type);
  3352. gbString yt = type_to_string(y->type);
  3353. gbString expr_str = expr_to_string(node);
  3354. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3355. gb_string_free(expr_str);
  3356. gb_string_free(yt);
  3357. gb_string_free(xt);
  3358. }
  3359. x->mode = Addressing_Invalid;
  3360. return;
  3361. }
  3362. if (!check_binary_op(c, x, op)) {
  3363. x->mode = Addressing_Invalid;
  3364. return;
  3365. }
  3366. switch (op.kind) {
  3367. case Token_Quo:
  3368. case Token_Mod:
  3369. case Token_ModMod:
  3370. case Token_QuoEq:
  3371. case Token_ModEq:
  3372. case Token_ModModEq:
  3373. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3374. y->mode == Addressing_Constant) {
  3375. bool fail = false;
  3376. switch (y->value.kind) {
  3377. case ExactValue_Integer:
  3378. if (big_int_is_zero(&y->value.value_integer)) {
  3379. fail = true;
  3380. }
  3381. break;
  3382. case ExactValue_Float:
  3383. if (y->value.value_float == 0.0) {
  3384. fail = true;
  3385. }
  3386. break;
  3387. }
  3388. if (fail) {
  3389. error(y->expr, "Division by zero not allowed");
  3390. x->mode = Addressing_Invalid;
  3391. return;
  3392. }
  3393. }
  3394. break;
  3395. case Token_CmpAnd:
  3396. case Token_CmpOr:
  3397. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3398. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3399. }
  3400. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3401. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3402. }
  3403. break;
  3404. }
  3405. if (x->mode == Addressing_Constant &&
  3406. y->mode == Addressing_Constant) {
  3407. ExactValue a = x->value;
  3408. ExactValue b = y->value;
  3409. if (!is_type_constant_type(x->type)) {
  3410. x->mode = Addressing_Value;
  3411. return;
  3412. }
  3413. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3414. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3415. }
  3416. if (is_type_bit_set(x->type)) {
  3417. switch (op.kind) {
  3418. case Token_Add: op.kind = Token_Or; break;
  3419. case Token_Sub: op.kind = Token_AndNot; break;
  3420. }
  3421. }
  3422. x->value = exact_binary_operator_value(op.kind, a, b);
  3423. if (is_type_typed(x->type)) {
  3424. if (node != nullptr) {
  3425. x->expr = node;
  3426. }
  3427. check_is_expressible(c, x, x->type);
  3428. }
  3429. return;
  3430. } else if (is_type_string(x->type)) {
  3431. error(node, "String concatenation is only allowed with constant strings");
  3432. x->mode = Addressing_Invalid;
  3433. return;
  3434. }
  3435. bool REQUIRE = true;
  3436. Type *bt = base_type(x->type);
  3437. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3438. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3439. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3440. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3441. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3442. }
  3443. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3444. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3445. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3446. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3447. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3448. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3449. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3450. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3451. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3452. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3453. }
  3454. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3455. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3456. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3457. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3458. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3459. case Basic_u128:
  3460. case Basic_i128:
  3461. if (is_arch_wasm()) {
  3462. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3463. }
  3464. break;
  3465. }
  3466. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3467. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3468. case Basic_u128:
  3469. case Basic_i128:
  3470. if (is_arch_wasm()) {
  3471. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3472. }
  3473. break;
  3474. }
  3475. }
  3476. x->mode = Addressing_Value;
  3477. }
  3478. gb_internal Operand make_operand_from_node(Ast *node) {
  3479. GB_ASSERT(node != nullptr);
  3480. Operand x = {};
  3481. x.expr = node;
  3482. x.mode = node->tav.mode;
  3483. x.type = node->tav.type;
  3484. x.value = node->tav.value;
  3485. return x;
  3486. }
  3487. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3488. GB_ASSERT(e != nullptr);
  3489. ExprInfo *old = check_get_expr_info(c, e);
  3490. if (old == nullptr) {
  3491. if (type != nullptr && type != t_invalid) {
  3492. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3493. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3494. if (e->kind == Ast_TernaryIfExpr) {
  3495. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3496. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3497. }
  3498. }
  3499. }
  3500. return;
  3501. }
  3502. switch (e->kind) {
  3503. case_ast_node(ue, UnaryExpr, e);
  3504. if (old->value.kind != ExactValue_Invalid) {
  3505. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3506. // They don't need to be updated as they will be updated later and
  3507. // checked at the end of general checking stage.
  3508. break;
  3509. }
  3510. update_untyped_expr_type(c, ue->expr, type, final);
  3511. case_end;
  3512. case_ast_node(be, BinaryExpr, e);
  3513. if (old->value.kind != ExactValue_Invalid) {
  3514. // See above note in UnaryExpr case
  3515. break;
  3516. }
  3517. if (token_is_comparison(be->op.kind)) {
  3518. // NOTE(bill): Do nothing as the types are fine
  3519. } else if (token_is_shift(be->op.kind)) {
  3520. update_untyped_expr_type(c, be->left, type, final);
  3521. } else {
  3522. update_untyped_expr_type(c, be->left, type, final);
  3523. update_untyped_expr_type(c, be->right, type, final);
  3524. }
  3525. case_end;
  3526. case_ast_node(te, TernaryIfExpr, e);
  3527. if (old->value.kind != ExactValue_Invalid) {
  3528. // See above note in UnaryExpr case
  3529. break;
  3530. }
  3531. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3532. // having an untyped value
  3533. Operand x = make_operand_from_node(te->x);
  3534. Operand y = make_operand_from_node(te->y);
  3535. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3536. update_untyped_expr_type(c, te->x, type, final);
  3537. }
  3538. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3539. update_untyped_expr_type(c, te->y, type, final);
  3540. }
  3541. case_end;
  3542. case_ast_node(te, TernaryWhenExpr, e);
  3543. if (old->value.kind != ExactValue_Invalid) {
  3544. // See above note in UnaryExpr case
  3545. break;
  3546. }
  3547. update_untyped_expr_type(c, te->x, type, final);
  3548. update_untyped_expr_type(c, te->y, type, final);
  3549. case_end;
  3550. case_ast_node(ore, OrReturnExpr, e);
  3551. if (old->value.kind != ExactValue_Invalid) {
  3552. // See above note in UnaryExpr case
  3553. break;
  3554. }
  3555. update_untyped_expr_type(c, ore->expr, type, final);
  3556. case_end;
  3557. case_ast_node(obe, OrBranchExpr, e);
  3558. if (old->value.kind != ExactValue_Invalid) {
  3559. // See above note in UnaryExpr case
  3560. break;
  3561. }
  3562. update_untyped_expr_type(c, obe->expr, type, final);
  3563. case_end;
  3564. case_ast_node(oee, OrElseExpr, e);
  3565. if (old->value.kind != ExactValue_Invalid) {
  3566. // See above note in UnaryExpr case
  3567. break;
  3568. }
  3569. update_untyped_expr_type(c, oee->x, type, final);
  3570. update_untyped_expr_type(c, oee->y, type, final);
  3571. case_end;
  3572. case_ast_node(pe, ParenExpr, e);
  3573. update_untyped_expr_type(c, pe->expr, type, final);
  3574. case_end;
  3575. }
  3576. if (!final && is_type_untyped(type)) {
  3577. old->type = base_type(type);
  3578. return;
  3579. }
  3580. // We need to remove it and then give it a new one
  3581. check_remove_expr_info(c, e);
  3582. if (old->is_lhs && !is_type_integer(type)) {
  3583. gbString expr_str = expr_to_string(e);
  3584. gbString type_str = type_to_string(type);
  3585. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3586. gb_string_free(type_str);
  3587. gb_string_free(expr_str);
  3588. return;
  3589. }
  3590. add_type_and_value(c, e, old->mode, type, old->value);
  3591. }
  3592. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3593. GB_ASSERT(e != nullptr);
  3594. ExprInfo *found = check_get_expr_info(c, e);
  3595. if (found) {
  3596. found->value = value;
  3597. }
  3598. }
  3599. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3600. gbString expr_str = expr_to_string(operand->expr);
  3601. gbString type_str = type_to_string(target_type);
  3602. gbString from_type_str = type_to_string(operand->type);
  3603. char const *extra_text = "";
  3604. if (operand->mode == Addressing_Constant) {
  3605. if (big_int_is_zero(&operand->value.value_integer)) {
  3606. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3607. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3608. extra_text = " - Did you want 'nil'?";
  3609. }
  3610. }
  3611. }
  3612. ERROR_BLOCK();
  3613. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3614. if (operand->value.kind == ExactValue_String) {
  3615. String key = operand->value.value_string;
  3616. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3617. Type *et = base_type(target_type);
  3618. check_did_you_mean_type(key, et->Enum.fields, ".");
  3619. }
  3620. }
  3621. gb_string_free(from_type_str);
  3622. gb_string_free(type_str);
  3623. gb_string_free(expr_str);
  3624. operand->mode = Addressing_Invalid;
  3625. }
  3626. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3627. Type *t = core_type(type);
  3628. if (is_type_boolean(t)) {
  3629. // v = exact_value_to_boolean(v);
  3630. } else if (is_type_float(t)) {
  3631. v = exact_value_to_float(v);
  3632. } else if (is_type_integer(t)) {
  3633. v = exact_value_to_integer(v);
  3634. } else if (is_type_pointer(t)) {
  3635. v = exact_value_to_integer(v);
  3636. } else if (is_type_complex(t)) {
  3637. v = exact_value_to_complex(v);
  3638. } else if (is_type_quaternion(t)) {
  3639. v = exact_value_to_quaternion(v);
  3640. }
  3641. return v;
  3642. }
  3643. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3644. GB_ASSERT_NOT_NULL(target_type);
  3645. if (operand->mode == Addressing_Invalid ||
  3646. operand->mode == Addressing_Type ||
  3647. is_type_typed(operand->type) ||
  3648. target_type == t_invalid) {
  3649. return;
  3650. }
  3651. if (is_type_untyped(target_type)) {
  3652. GB_ASSERT(operand->type->kind == Type_Basic);
  3653. GB_ASSERT(target_type->kind == Type_Basic);
  3654. BasicKind x_kind = operand->type->Basic.kind;
  3655. BasicKind y_kind = target_type->Basic.kind;
  3656. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3657. if (x_kind < y_kind) {
  3658. operand->type = target_type;
  3659. update_untyped_expr_type(c, operand->expr, target_type, false);
  3660. }
  3661. } else if (x_kind != y_kind) {
  3662. operand->mode = Addressing_Invalid;
  3663. convert_untyped_error(c, operand, target_type);
  3664. return;
  3665. }
  3666. return;
  3667. }
  3668. Type *t = base_type(target_type);
  3669. if (c->in_enum_type) {
  3670. t = core_type(target_type);
  3671. }
  3672. switch (t->kind) {
  3673. case Type_Basic:
  3674. if (operand->mode == Addressing_Constant) {
  3675. check_is_expressible(c, operand, t);
  3676. if (operand->mode == Addressing_Invalid) {
  3677. return;
  3678. }
  3679. update_untyped_expr_value(c, operand->expr, operand->value);
  3680. } else {
  3681. switch (operand->type->Basic.kind) {
  3682. case Basic_UntypedBool:
  3683. if (!is_type_boolean(target_type)) {
  3684. operand->mode = Addressing_Invalid;
  3685. convert_untyped_error(c, operand, target_type);
  3686. return;
  3687. }
  3688. break;
  3689. case Basic_UntypedInteger:
  3690. case Basic_UntypedFloat:
  3691. case Basic_UntypedComplex:
  3692. case Basic_UntypedQuaternion:
  3693. case Basic_UntypedRune:
  3694. if (!is_type_numeric(target_type)) {
  3695. operand->mode = Addressing_Invalid;
  3696. convert_untyped_error(c, operand, target_type);
  3697. return;
  3698. }
  3699. break;
  3700. case Basic_UntypedNil:
  3701. if (is_type_any(target_type)) {
  3702. // target_type = t_untyped_nil;
  3703. } else if (is_type_cstring(target_type)) {
  3704. // target_type = t_untyped_nil;
  3705. } else if (!type_has_nil(target_type)) {
  3706. operand->mode = Addressing_Invalid;
  3707. convert_untyped_error(c, operand, target_type);
  3708. return;
  3709. }
  3710. break;
  3711. }
  3712. }
  3713. break;
  3714. case Type_Array: {
  3715. Type *elem = base_array_type(t);
  3716. if (check_is_assignable_to(c, operand, elem)) {
  3717. operand->mode = Addressing_Value;
  3718. } else {
  3719. if (operand->value.kind == ExactValue_String) {
  3720. String s = operand->value.value_string;
  3721. if (is_type_u8_array(t)) {
  3722. if (s.len == t->Array.count) {
  3723. break;
  3724. }
  3725. } else if (is_type_rune_array(t)) {
  3726. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3727. if (rune_count == t->Array.count) {
  3728. break;
  3729. }
  3730. }
  3731. }
  3732. operand->mode = Addressing_Invalid;
  3733. convert_untyped_error(c, operand, target_type);
  3734. return;
  3735. }
  3736. break;
  3737. }
  3738. case Type_Matrix: {
  3739. Type *elem = base_array_type(t);
  3740. if (check_is_assignable_to(c, operand, elem)) {
  3741. if (t->Matrix.row_count != t->Matrix.column_count) {
  3742. operand->mode = Addressing_Invalid;
  3743. ERROR_BLOCK();
  3744. convert_untyped_error(c, operand, target_type);
  3745. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3746. return;
  3747. } else {
  3748. operand->mode = Addressing_Value;
  3749. }
  3750. } else {
  3751. operand->mode = Addressing_Invalid;
  3752. convert_untyped_error(c, operand, target_type);
  3753. return;
  3754. }
  3755. break;
  3756. }
  3757. case Type_Union:
  3758. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3759. TEMPORARY_ALLOCATOR_GUARD();
  3760. isize count = t->Union.variants.count;
  3761. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3762. isize valid_count = 0;
  3763. isize first_success_index = -1;
  3764. for_array(i, t->Union.variants) {
  3765. Type *vt = t->Union.variants[i];
  3766. i64 score = 0;
  3767. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3768. valids[valid_count].index = i;
  3769. valids[valid_count].score = score;
  3770. valid_count += 1;
  3771. if (first_success_index < 0) {
  3772. first_success_index = i;
  3773. }
  3774. }
  3775. }
  3776. if (valid_count > 1) {
  3777. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3778. i64 best_score = valids[0].score;
  3779. for (isize i = 1; i < valid_count; i++) {
  3780. auto v = valids[i];
  3781. if (best_score > v.score) {
  3782. valid_count = i;
  3783. break;
  3784. }
  3785. best_score = v.score;
  3786. }
  3787. first_success_index = valids[0].index;
  3788. }
  3789. gbString type_str = type_to_string(target_type);
  3790. defer (gb_string_free(type_str));
  3791. if (valid_count == 1) {
  3792. operand->mode = Addressing_Value;
  3793. operand->type = t->Union.variants[first_success_index];
  3794. target_type = t->Union.variants[first_success_index];
  3795. break;
  3796. } else if (valid_count > 1) {
  3797. ERROR_BLOCK();
  3798. GB_ASSERT(first_success_index >= 0);
  3799. operand->mode = Addressing_Invalid;
  3800. convert_untyped_error(c, operand, target_type);
  3801. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3802. i32 j = 0;
  3803. for (i32 i = 0; i < valid_count; i++) {
  3804. ValidIndexAndScore valid = valids[i];
  3805. if (j > 0 && valid_count > 2) error_line(", ");
  3806. if (j == valid_count-1) {
  3807. if (valid_count == 2) error_line(" ");
  3808. error_line("or ");
  3809. }
  3810. gbString str = type_to_string(t->Union.variants[valid.index]);
  3811. error_line("'%s'", str);
  3812. gb_string_free(str);
  3813. j++;
  3814. }
  3815. error_line("\n\n");
  3816. return;
  3817. } else if (is_type_untyped_uninit(operand->type)) {
  3818. target_type = t_untyped_uninit;
  3819. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3820. ERROR_BLOCK();
  3821. operand->mode = Addressing_Invalid;
  3822. convert_untyped_error(c, operand, target_type);
  3823. if (count > 0) {
  3824. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3825. error_line("\t");
  3826. for (i32 i = 0; i < count; i++) {
  3827. Type *v = t->Union.variants[i];
  3828. if (i > 0 && count > 2) error_line(", ");
  3829. if (i == count-1) {
  3830. if (count == 2) error_line(" ");
  3831. if (count > 1) {
  3832. error_line("or ");
  3833. }
  3834. }
  3835. gbString str = type_to_string(v);
  3836. error_line("'%s'", str);
  3837. gb_string_free(str);
  3838. }
  3839. error_line("\n\n");
  3840. }
  3841. return;
  3842. }
  3843. }
  3844. /* fallthrough */
  3845. default:
  3846. if (is_type_untyped_uninit(operand->type)) {
  3847. target_type = t_untyped_uninit;
  3848. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3849. target_type = t_untyped_nil;
  3850. } else {
  3851. operand->mode = Addressing_Invalid;
  3852. convert_untyped_error(c, operand, target_type);
  3853. return;
  3854. }
  3855. break;
  3856. }
  3857. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3858. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3859. } else {
  3860. target_type = default_type(operand->type);
  3861. }
  3862. }
  3863. update_untyped_expr_type(c, operand->expr, target_type, true);
  3864. operand->type = target_type;
  3865. }
  3866. 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) {
  3867. Operand operand = {Addressing_Invalid};
  3868. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3869. if (operand.mode == Addressing_Invalid) {
  3870. if (value) *value = 0;
  3871. return false;
  3872. }
  3873. Type *index_type = t_int;
  3874. if (type_hint != nullptr) {
  3875. index_type = type_hint;
  3876. }
  3877. convert_to_typed(c, &operand, index_type);
  3878. if (operand.mode == Addressing_Invalid) {
  3879. if (value) *value = 0;
  3880. return false;
  3881. }
  3882. if (type_hint != nullptr) {
  3883. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3884. gbString expr_str = expr_to_string(operand.expr);
  3885. gbString index_type_str = type_to_string(type_hint);
  3886. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3887. gb_string_free(index_type_str);
  3888. gb_string_free(expr_str);
  3889. if (value) *value = 0;
  3890. return false;
  3891. }
  3892. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3893. gbString expr_str = expr_to_string(operand.expr);
  3894. gbString type_str = type_to_string(operand.type);
  3895. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3896. gb_string_free(type_str);
  3897. gb_string_free(expr_str);
  3898. if (value) *value = 0;
  3899. return false;
  3900. }
  3901. if (operand.mode == Addressing_Constant &&
  3902. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3903. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3904. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3905. TEMPORARY_ALLOCATOR_GUARD();
  3906. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3907. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3908. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3909. if (value) *value = 0;
  3910. return false;
  3911. }
  3912. if (max_count >= 0) {
  3913. if (is_type_enum(index_type)) {
  3914. Type *bt = base_type(index_type);
  3915. GB_ASSERT(bt->kind == Type_Enum);
  3916. ExactValue const &lo = *bt->Enum.min_value;
  3917. ExactValue const &hi = *bt->Enum.max_value;
  3918. String lo_str = {};
  3919. String hi_str = {};
  3920. if (bt->Enum.fields.count > 0) {
  3921. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3922. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3923. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3924. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3925. }
  3926. bool out_of_bounds = false;
  3927. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3928. out_of_bounds = true;
  3929. }
  3930. if (out_of_bounds) {
  3931. gbString expr_str = expr_to_string(operand.expr);
  3932. if (lo_str.len > 0) {
  3933. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3934. } else {
  3935. gbString index_type_str = type_to_string(index_type);
  3936. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3937. gb_string_free(index_type_str);
  3938. }
  3939. gb_string_free(expr_str);
  3940. return false;
  3941. }
  3942. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3943. return true;
  3944. } else { // NOTE(bill): Do array bound checking
  3945. i64 v = -1;
  3946. if (i.used <= 1) {
  3947. v = big_int_to_i64(&i);
  3948. }
  3949. if (value) *value = v;
  3950. bool out_of_bounds = false;
  3951. if (v < 0) {
  3952. out_of_bounds = true;
  3953. } else if (open_range) {
  3954. out_of_bounds = v > max_count;
  3955. } else {
  3956. out_of_bounds = v >= max_count;
  3957. }
  3958. if (out_of_bounds) {
  3959. TEMPORARY_ALLOCATOR_GUARD();
  3960. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3961. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3962. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3963. return false;
  3964. }
  3965. return true;
  3966. }
  3967. } else {
  3968. if (value) *value = exact_value_to_i64(operand.value);
  3969. return true;
  3970. }
  3971. }
  3972. // NOTE(bill): It's alright :D
  3973. if (value) *value = -1;
  3974. return true;
  3975. }
  3976. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3977. if (value.kind == ExactValue_String) {
  3978. GB_ASSERT(0 <= index && index < value.value_string.len);
  3979. u8 val = value.value_string[index];
  3980. if (success_) *success_ = true;
  3981. if (finish_) *finish_ = true;
  3982. return exact_value_u64(val);
  3983. }
  3984. if (value.kind != ExactValue_Compound) {
  3985. if (success_) *success_ = true;
  3986. if (finish_) *finish_ = true;
  3987. return value;
  3988. }
  3989. Ast *node = value.value_compound;
  3990. switch (node->kind) {
  3991. case_ast_node(cl, CompoundLit, node);
  3992. if (cl->elems.count == 0) {
  3993. if (success_) *success_ = true;
  3994. if (finish_) *finish_ = true;
  3995. return empty_exact_value;
  3996. }
  3997. if (cl->elems[0]->kind == Ast_FieldValue) {
  3998. if (is_type_struct(node->tav.type)) {
  3999. bool found = false;
  4000. for (Ast *elem : cl->elems) {
  4001. if (elem->kind != Ast_FieldValue) {
  4002. continue;
  4003. }
  4004. ast_node(fv, FieldValue, elem);
  4005. String name = fv->field->Ident.token.string;
  4006. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4007. defer (array_free(&sub_sel.index));
  4008. if (sub_sel.index[0] == index) {
  4009. value = fv->value->tav.value;
  4010. found = true;
  4011. break;
  4012. }
  4013. }
  4014. if (!found) {
  4015. // Use the zero value if it is not found
  4016. value = {};
  4017. }
  4018. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4019. for (Ast *elem : cl->elems) {
  4020. if (elem->kind != Ast_FieldValue) {
  4021. continue;
  4022. }
  4023. ast_node(fv, FieldValue, elem);
  4024. if (is_ast_range(fv->field)) {
  4025. ast_node(ie, BinaryExpr, fv->field);
  4026. TypeAndValue lo_tav = ie->left->tav;
  4027. TypeAndValue hi_tav = ie->right->tav;
  4028. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4029. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4030. TokenKind op = ie->op.kind;
  4031. i64 lo = exact_value_to_i64(lo_tav.value);
  4032. i64 hi = exact_value_to_i64(hi_tav.value);
  4033. i64 corrected_index = index;
  4034. if (is_type_enumerated_array(node->tav.type)) {
  4035. Type *bt = base_type(node->tav.type);
  4036. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4037. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4038. }
  4039. if (op != Token_RangeHalf) {
  4040. if (lo <= corrected_index && corrected_index <= hi) {
  4041. TypeAndValue tav = fv->value->tav;
  4042. if (success_) *success_ = true;
  4043. if (finish_) *finish_ = false;
  4044. return tav.value;
  4045. }
  4046. } else {
  4047. if (lo <= corrected_index && corrected_index < hi) {
  4048. TypeAndValue tav = fv->value->tav;
  4049. if (success_) *success_ = true;
  4050. if (finish_) *finish_ = false;
  4051. return tav.value;
  4052. }
  4053. }
  4054. } else {
  4055. TypeAndValue index_tav = fv->field->tav;
  4056. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4057. ExactValue index_value = index_tav.value;
  4058. if (is_type_enumerated_array(node->tav.type)) {
  4059. Type *bt = base_type(node->tav.type);
  4060. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4061. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4062. }
  4063. i64 field_index = exact_value_to_i64(index_value);
  4064. if (index == field_index) {
  4065. TypeAndValue tav = fv->value->tav;
  4066. if (success_) *success_ = true;
  4067. if (finish_) *finish_ = false;
  4068. return tav.value;;
  4069. }
  4070. }
  4071. }
  4072. }
  4073. } else {
  4074. i32 count = (i32)cl->elems.count;
  4075. if (count < index) {
  4076. if (success_) *success_ = false;
  4077. if (finish_) *finish_ = true;
  4078. return empty_exact_value;
  4079. }
  4080. if (cl->elems.count <= index) {
  4081. if (success_) *success_ = false;
  4082. if (finish_) *finish_ = false;
  4083. return value;
  4084. }
  4085. TypeAndValue tav = cl->elems[index]->tav;
  4086. if (tav.mode == Addressing_Constant) {
  4087. if (success_) *success_ = true;
  4088. if (finish_) *finish_ = false;
  4089. return tav.value;
  4090. } else {
  4091. GB_ASSERT(is_type_untyped_nil(tav.type));
  4092. if (success_) *success_ = true;
  4093. if (finish_) *finish_ = false;
  4094. return tav.value;
  4095. }
  4096. }
  4097. case_end;
  4098. default:
  4099. if (success_) *success_ = true;
  4100. if (finish_) *finish_ = true;
  4101. return empty_exact_value;
  4102. }
  4103. if (finish_) *finish_ = false;
  4104. return value;
  4105. }
  4106. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4107. if (operand->mode != Addressing_Constant) {
  4108. if (success_) *success_ = false;
  4109. return empty_exact_value;
  4110. }
  4111. if (sel.indirect) {
  4112. if (success_) *success_ = false;
  4113. return empty_exact_value;
  4114. }
  4115. if (sel.index.count == 0) {
  4116. if (success_) *success_ = false;
  4117. return empty_exact_value;
  4118. }
  4119. ExactValue value = operand->value;
  4120. if (value.kind == ExactValue_Compound) {
  4121. while (sel.index.count > 0) {
  4122. i32 index = sel.index[0];
  4123. sel = sub_selection(sel, 1);
  4124. bool finish = false;
  4125. value = get_constant_field_single(c, value, index, success_, &finish);
  4126. if (finish) {
  4127. return value;
  4128. }
  4129. }
  4130. if (success_) *success_ = true;
  4131. return value;
  4132. } else if (value.kind == ExactValue_Quaternion) {
  4133. // @QuaternionLayout
  4134. Quaternion256 q = *value.value_quaternion;
  4135. GB_ASSERT(sel.index.count == 1);
  4136. switch (sel.index[0]) {
  4137. case 3: // w
  4138. if (success_) *success_ = true;
  4139. return exact_value_float(q.real);
  4140. case 0: // x
  4141. if (success_) *success_ = true;
  4142. return exact_value_float(q.imag);
  4143. case 1: // y
  4144. if (success_) *success_ = true;
  4145. return exact_value_float(q.jmag);
  4146. case 2: // z
  4147. if (success_) *success_ = true;
  4148. return exact_value_float(q.kmag);
  4149. }
  4150. if (success_) *success_ = false;
  4151. return empty_exact_value;
  4152. } else if (value.kind == ExactValue_Complex) {
  4153. // @QuaternionLayout
  4154. Complex128 c = *value.value_complex;
  4155. GB_ASSERT(sel.index.count == 1);
  4156. switch (sel.index[0]) {
  4157. case 0: // real
  4158. if (success_) *success_ = true;
  4159. return exact_value_float(c.real);
  4160. case 1: // imag
  4161. if (success_) *success_ = true;
  4162. return exact_value_float(c.imag);
  4163. }
  4164. if (success_) *success_ = false;
  4165. return empty_exact_value;
  4166. }
  4167. if (success_) *success_ = true;
  4168. return empty_exact_value;
  4169. }
  4170. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4171. Type *array_type = base_type(type_deref(original_type));
  4172. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4173. if (array_type->kind == Type_SimdVector) {
  4174. Type *elem_type = array_type->SimdVector.elem;
  4175. return alloc_type_simd_vector(new_count, elem_type);
  4176. }
  4177. Type *elem_type = array_type->Array.elem;
  4178. Type *swizzle_array_type = nullptr;
  4179. Type *bth = base_type(type_deref(type_hint));
  4180. if (bth != nullptr && bth->kind == Type_Array &&
  4181. bth->Array.count == new_count &&
  4182. are_types_identical(bth->Array.elem, elem_type)) {
  4183. swizzle_array_type = type_hint;
  4184. } else {
  4185. i64 max_count = array_type->Array.count;
  4186. if (new_count == max_count) {
  4187. swizzle_array_type = original_type;
  4188. } else {
  4189. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4190. }
  4191. }
  4192. return swizzle_array_type;
  4193. }
  4194. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4195. bool is_declared = entity != nullptr;
  4196. if (is_declared) {
  4197. if (entity->kind == Entity_Builtin) {
  4198. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4199. // This means that we should just ignore the found result through it
  4200. *allow_builtin = entity->scope == import_scope ||
  4201. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4202. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4203. is_declared = false;
  4204. }
  4205. }
  4206. return is_declared;
  4207. }
  4208. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4209. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4210. if (node->kind == Ast_Ident) {
  4211. String name = node->Ident.token.string;
  4212. return scope_lookup(c->scope, name);
  4213. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4214. ast_node(se, SelectorExpr, node);
  4215. if (se->token.kind == Token_ArrowRight) {
  4216. return nullptr;
  4217. }
  4218. Ast *op_expr = se->expr;
  4219. Ast *selector = unparen_expr(se->selector);
  4220. if (selector == nullptr) {
  4221. return nullptr;
  4222. }
  4223. if (selector->kind != Ast_Ident) {
  4224. return nullptr;
  4225. }
  4226. Entity *entity = nullptr;
  4227. Entity *expr_entity = nullptr;
  4228. bool check_op_expr = true;
  4229. if (op_expr->kind == Ast_Ident) {
  4230. String op_name = op_expr->Ident.token.string;
  4231. Entity *e = scope_lookup(c->scope, op_name);
  4232. if (e == nullptr) {
  4233. return nullptr;
  4234. }
  4235. add_entity_use(c, op_expr, e);
  4236. expr_entity = e;
  4237. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4238. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4239. // It pretty much needs to be in this order and this way
  4240. // If you can clean this up, please do but be really careful
  4241. String import_name = op_name;
  4242. Scope *import_scope = e->ImportName.scope;
  4243. String entity_name = selector->Ident.token.string;
  4244. check_op_expr = false;
  4245. entity = scope_lookup_current(import_scope, entity_name);
  4246. bool allow_builtin = false;
  4247. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4248. return nullptr;
  4249. }
  4250. check_entity_decl(c, entity, nullptr, nullptr);
  4251. if (entity->kind == Entity_ProcGroup) {
  4252. return entity;
  4253. }
  4254. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4255. }
  4256. }
  4257. Operand operand = {};
  4258. if (check_op_expr) {
  4259. check_expr_base(c, &operand, op_expr, nullptr);
  4260. if (operand.mode == Addressing_Invalid) {
  4261. return nullptr;
  4262. }
  4263. }
  4264. if (entity == nullptr && selector->kind == Ast_Ident) {
  4265. String field_name = selector->Ident.token.string;
  4266. if (is_type_dynamic_array(type_deref(operand.type))) {
  4267. init_mem_allocator(c->checker);
  4268. }
  4269. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4270. entity = sel.entity;
  4271. }
  4272. if (entity != nullptr) {
  4273. return entity;
  4274. }
  4275. }
  4276. return nullptr;
  4277. }
  4278. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4279. ast_node(se, SelectorExpr, node);
  4280. bool check_op_expr = true;
  4281. Entity *expr_entity = nullptr;
  4282. Entity *entity = nullptr;
  4283. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4284. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4285. error(node, "Illegal use of -> selector shorthand outside of a call");
  4286. operand->mode = Addressing_Invalid;
  4287. operand->expr = node;
  4288. return nullptr;
  4289. }
  4290. operand->expr = node;
  4291. Ast *op_expr = se->expr;
  4292. Ast *selector = unparen_expr(se->selector);
  4293. if (selector == nullptr) {
  4294. operand->mode = Addressing_Invalid;
  4295. operand->expr = node;
  4296. return nullptr;
  4297. }
  4298. if (selector->kind != Ast_Ident) {
  4299. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4300. operand->mode = Addressing_Invalid;
  4301. operand->expr = node;
  4302. return nullptr;
  4303. }
  4304. if (op_expr->kind == Ast_Ident) {
  4305. String op_name = op_expr->Ident.token.string;
  4306. Entity *e = scope_lookup(c->scope, op_name);
  4307. add_entity_use(c, op_expr, e);
  4308. expr_entity = e;
  4309. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4310. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4311. // It pretty much needs to be in this order and this way
  4312. // If you can clean this up, please do but be really careful
  4313. String import_name = op_name;
  4314. Scope *import_scope = e->ImportName.scope;
  4315. String entity_name = selector->Ident.token.string;
  4316. check_op_expr = false;
  4317. entity = scope_lookup_current(import_scope, entity_name);
  4318. bool allow_builtin = false;
  4319. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4320. ERROR_BLOCK();
  4321. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4322. operand->mode = Addressing_Invalid;
  4323. operand->expr = node;
  4324. check_did_you_mean_scope(entity_name, import_scope);
  4325. return nullptr;
  4326. }
  4327. check_entity_decl(c, entity, nullptr, nullptr);
  4328. if (entity->kind == Entity_ProcGroup) {
  4329. operand->mode = Addressing_ProcGroup;
  4330. operand->proc_group = entity;
  4331. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4332. return entity;
  4333. }
  4334. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4335. if (!is_entity_exported(entity, allow_builtin)) {
  4336. gbString sel_str = expr_to_string(selector);
  4337. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4338. gb_string_free(sel_str);
  4339. // NOTE(bill): make the state valid still, even if it's "invalid"
  4340. // operand->mode = Addressing_Invalid;
  4341. // operand->expr = node;
  4342. // return nullptr;
  4343. }
  4344. if (entity->kind == Entity_ProcGroup) {
  4345. Array<Entity *> procs = entity->ProcGroup.entities;
  4346. bool skip = false;
  4347. for (Entity *p : procs) {
  4348. Type *t = base_type(p->type);
  4349. if (t == t_invalid) {
  4350. continue;
  4351. }
  4352. Operand x = {};
  4353. x.mode = Addressing_Value;
  4354. x.type = t;
  4355. if (type_hint != nullptr) {
  4356. if (check_is_assignable_to(c, &x, type_hint)) {
  4357. entity = p;
  4358. skip = true;
  4359. break;
  4360. }
  4361. }
  4362. }
  4363. if (!skip) {
  4364. GB_ASSERT(entity != nullptr);
  4365. operand->mode = Addressing_ProcGroup;
  4366. operand->type = t_invalid;
  4367. operand->expr = node;
  4368. operand->proc_group = entity;
  4369. return entity;
  4370. }
  4371. }
  4372. }
  4373. }
  4374. if (check_op_expr) {
  4375. check_expr_base(c, operand, op_expr, nullptr);
  4376. if (operand->mode == Addressing_Invalid) {
  4377. operand->mode = Addressing_Invalid;
  4378. operand->expr = node;
  4379. return nullptr;
  4380. }
  4381. }
  4382. if (entity == nullptr && selector->kind == Ast_Ident) {
  4383. String field_name = selector->Ident.token.string;
  4384. Type *t = type_deref(operand->type);
  4385. if (t == nullptr) {
  4386. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4387. } else if (is_type_dynamic_array(t)) {
  4388. init_mem_allocator(c->checker);
  4389. }
  4390. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4391. entity = sel.entity;
  4392. // NOTE(bill): Add type info needed for fields like 'names'
  4393. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4394. add_type_info_type(c, operand->type);
  4395. }
  4396. if (is_type_enum(operand->type)) {
  4397. add_type_info_type(c, operand->type);
  4398. }
  4399. }
  4400. if (entity == nullptr && selector->kind == Ast_Ident && (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4401. String field_name = selector->Ident.token.string;
  4402. if (1 < field_name.len && field_name.len <= 4) {
  4403. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4404. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4405. bool found_xyzw = false;
  4406. bool found_rgba = false;
  4407. for (isize i = 0; i < field_name.len; i++) {
  4408. bool valid = false;
  4409. for (isize j = 0; j < 4; j++) {
  4410. if (field_name.text[i] == swizzles_xyzw[j]) {
  4411. found_xyzw = true;
  4412. valid = true;
  4413. break;
  4414. }
  4415. if (field_name.text[i] == swizzles_rgba[j]) {
  4416. found_rgba = true;
  4417. valid = true;
  4418. break;
  4419. }
  4420. }
  4421. if (!valid) {
  4422. goto end_of_array_selector_swizzle;
  4423. }
  4424. }
  4425. u8 *swizzles = nullptr;
  4426. u8 index_count = cast(u8)field_name.len;
  4427. if (found_xyzw && found_rgba) {
  4428. gbString op_str = expr_to_string(op_expr);
  4429. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4430. gb_string_free(op_str);
  4431. operand->mode = Addressing_Invalid;
  4432. operand->expr = node;
  4433. return nullptr;
  4434. }
  4435. u8 indices = 0;
  4436. if (found_xyzw) {
  4437. swizzles = swizzles_xyzw;
  4438. } else if (found_rgba) {
  4439. swizzles = swizzles_rgba;
  4440. }
  4441. for (isize i = 0; i < field_name.len; i++) {
  4442. for (isize j = 0; j < 4; j++) {
  4443. if (field_name.text[i] == swizzles[j]) {
  4444. indices |= cast(u8)(j)<<(i*2);
  4445. break;
  4446. }
  4447. }
  4448. }
  4449. Type *original_type = operand->type;
  4450. Type *array_type = base_type(type_deref(original_type));
  4451. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4452. i64 array_count = get_array_type_count(array_type);
  4453. for (u8 i = 0; i < index_count; i++) {
  4454. u8 idx = indices>>(i*2) & 3;
  4455. if (idx >= array_count) {
  4456. char c = 0;
  4457. if (found_xyzw) {
  4458. c = swizzles_xyzw[idx];
  4459. } else if (found_rgba) {
  4460. c = swizzles_rgba[idx];
  4461. } else {
  4462. GB_PANIC("unknown swizzle kind");
  4463. }
  4464. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4465. break;
  4466. }
  4467. }
  4468. se->swizzle_count = index_count;
  4469. se->swizzle_indices = indices;
  4470. AddressingMode prev_mode = operand->mode;
  4471. operand->mode = Addressing_SwizzleValue;
  4472. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4473. operand->expr = node;
  4474. switch (prev_mode) {
  4475. case Addressing_Variable:
  4476. case Addressing_SoaVariable:
  4477. case Addressing_SwizzleVariable:
  4478. operand->mode = Addressing_SwizzleVariable;
  4479. break;
  4480. }
  4481. if (array_type->kind == Type_SimdVector) {
  4482. operand->mode = Addressing_Value;
  4483. }
  4484. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4485. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4486. return swizzle_entity;
  4487. }
  4488. end_of_array_selector_swizzle:;
  4489. }
  4490. if (entity == nullptr) {
  4491. gbString op_str = expr_to_string(op_expr);
  4492. gbString type_str = type_to_string_shorthand(operand->type);
  4493. gbString sel_str = expr_to_string(selector);
  4494. if (operand->mode == Addressing_Type) {
  4495. if (is_type_polymorphic(operand->type, true)) {
  4496. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4497. } else {
  4498. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4499. }
  4500. } else {
  4501. ERROR_BLOCK();
  4502. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4503. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4504. String const &name = selector->Ident.token.string;
  4505. Type *bt = base_type(operand->type);
  4506. if (operand->type->kind == Type_Named &&
  4507. operand->type->Named.type_name &&
  4508. operand->type->Named.type_name->kind == Entity_TypeName &&
  4509. operand->type->Named.type_name->TypeName.objc_metadata) {
  4510. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4511. } else if (bt->kind == Type_Struct) {
  4512. check_did_you_mean_type(name, bt->Struct.fields);
  4513. } else if (bt->kind == Type_Enum) {
  4514. check_did_you_mean_type(name, bt->Enum.fields);
  4515. }
  4516. }
  4517. }
  4518. gb_string_free(sel_str);
  4519. gb_string_free(type_str);
  4520. gb_string_free(op_str);
  4521. operand->mode = Addressing_Invalid;
  4522. operand->expr = node;
  4523. return nullptr;
  4524. }
  4525. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4526. bool success = false;
  4527. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4528. if (success) {
  4529. operand->mode = Addressing_Constant;
  4530. operand->expr = node;
  4531. operand->value = field_value;
  4532. operand->type = entity->type;
  4533. add_entity_use(c, selector, entity);
  4534. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4535. return entity;
  4536. }
  4537. gbString op_str = expr_to_string(op_expr);
  4538. gbString type_str = type_to_string_shorthand(operand->type);
  4539. gbString sel_str = expr_to_string(selector);
  4540. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4541. gb_string_free(sel_str);
  4542. gb_string_free(type_str);
  4543. gb_string_free(op_str);
  4544. operand->mode = Addressing_Invalid;
  4545. operand->expr = node;
  4546. return nullptr;
  4547. }
  4548. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4549. bool success = false;
  4550. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4551. if (success) {
  4552. operand->mode = Addressing_Constant;
  4553. operand->expr = node;
  4554. operand->value = field_value;
  4555. operand->type = entity->type;
  4556. add_entity_use(c, selector, entity);
  4557. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4558. return entity;
  4559. }
  4560. gbString op_str = expr_to_string(op_expr);
  4561. gbString type_str = type_to_string_shorthand(operand->type);
  4562. gbString sel_str = expr_to_string(selector);
  4563. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4564. gb_string_free(sel_str);
  4565. gb_string_free(type_str);
  4566. gb_string_free(op_str);
  4567. operand->mode = Addressing_Invalid;
  4568. operand->expr = node;
  4569. return nullptr;
  4570. }
  4571. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4572. gbString op_str = expr_to_string(op_expr);
  4573. gbString type_str = type_to_string_shorthand(operand->type);
  4574. gbString sel_str = expr_to_string(selector);
  4575. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4576. gb_string_free(sel_str);
  4577. gb_string_free(type_str);
  4578. gb_string_free(op_str);
  4579. operand->mode = Addressing_Invalid;
  4580. operand->expr = node;
  4581. return nullptr;
  4582. }
  4583. add_entity_use(c, selector, entity);
  4584. operand->type = entity->type;
  4585. operand->expr = node;
  4586. if (entity->flags & EntityFlag_BitFieldField) {
  4587. add_package_dependency(c, "runtime", "__write_bits");
  4588. add_package_dependency(c, "runtime", "__read_bits");
  4589. }
  4590. switch (entity->kind) {
  4591. case Entity_Constant:
  4592. operand->value = entity->Constant.value;
  4593. operand->mode = Addressing_Constant;
  4594. if (operand->value.kind == ExactValue_Procedure) {
  4595. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4596. if (proc != nullptr) {
  4597. operand->mode = Addressing_Value;
  4598. operand->type = proc->type;
  4599. }
  4600. }
  4601. break;
  4602. case Entity_Variable:
  4603. if (sel.is_bit_field) {
  4604. se->is_bit_field = true;
  4605. }
  4606. if (sel.indirect) {
  4607. operand->mode = Addressing_Variable;
  4608. } else if (operand->mode == Addressing_Context) {
  4609. // Do nothing
  4610. } else if (operand->mode == Addressing_MapIndex) {
  4611. operand->mode = Addressing_Value;
  4612. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4613. operand->mode = Addressing_SoaVariable;
  4614. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4615. operand->mode = Addressing_Value;
  4616. } else if (operand->mode == Addressing_SoaVariable) {
  4617. operand->mode = Addressing_Variable;
  4618. } else if (operand->mode != Addressing_Value) {
  4619. operand->mode = Addressing_Variable;
  4620. } else {
  4621. operand->mode = Addressing_Value;
  4622. }
  4623. break;
  4624. case Entity_TypeName:
  4625. operand->mode = Addressing_Type;
  4626. break;
  4627. case Entity_Procedure:
  4628. operand->mode = Addressing_Value;
  4629. operand->value = exact_value_procedure(node);
  4630. break;
  4631. case Entity_Builtin:
  4632. operand->mode = Addressing_Builtin;
  4633. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4634. break;
  4635. case Entity_ProcGroup:
  4636. operand->mode = Addressing_ProcGroup;
  4637. operand->proc_group = entity;
  4638. break;
  4639. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4640. case Entity_Nil:
  4641. operand->mode = Addressing_Value;
  4642. break;
  4643. }
  4644. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4645. return entity;
  4646. }
  4647. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4648. ptr = base_type(ptr);
  4649. if (is_type_pointer(ptr)) {
  4650. if (is_type_rawptr(ptr)) {
  4651. return false;
  4652. }
  4653. if (elem) *elem = ptr->Pointer.elem;
  4654. return true;
  4655. }
  4656. return false;
  4657. }
  4658. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4659. elem = core_type(elem);
  4660. if (is_type_internally_pointer_like(elem)) {
  4661. return true;
  4662. }
  4663. if (elem->kind == Type_BitSet) {
  4664. elem = bit_set_to_int(elem);
  4665. }
  4666. if (elem->kind != Type_Basic) {
  4667. return false;
  4668. }
  4669. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4670. }
  4671. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4672. switch (node->kind) {
  4673. case_ast_node(i, Ident, node);
  4674. String name = i->token.string;
  4675. if (nested) {
  4676. Entity *e = scope_lookup_current(s, name);
  4677. if (e != nullptr) {
  4678. if (out_scope) *out_scope = e->scope;
  4679. return true;
  4680. }
  4681. } else {
  4682. Entity *e = scope_lookup(s, name);
  4683. if (e != nullptr) {
  4684. if (out_scope) *out_scope = e->scope;
  4685. return true;
  4686. }
  4687. }
  4688. case_end;
  4689. case_ast_node(se, SelectorExpr, node);
  4690. Ast *lhs = se->expr;
  4691. Ast *rhs = se->selector;
  4692. Scope *lhs_scope = nullptr;
  4693. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4694. return check_identifier_exists(lhs_scope, rhs, true);
  4695. }
  4696. case_end;
  4697. }
  4698. return false;
  4699. }
  4700. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4701. if (o.type && is_type_no_copy(o.type)) {
  4702. Ast *expr = unparen_expr(o.expr);
  4703. if (expr && o.mode != Addressing_Constant) {
  4704. if (expr->kind == Ast_CallExpr) {
  4705. // Okay
  4706. } else {
  4707. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4708. return true;
  4709. }
  4710. }
  4711. }
  4712. return false;
  4713. }
  4714. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4715. bool optional_ok = false;
  4716. isize tuple_index = 0;
  4717. for (Ast *rhs_expr : rhs) {
  4718. CheckerContext c_ = *ctx;
  4719. CheckerContext *c = &c_;
  4720. Operand o = {};
  4721. Type *type_hint = nullptr;
  4722. if (tuple_index < lhs.count) {
  4723. type_hint = lhs[tuple_index].type;
  4724. }
  4725. check_expr_base(c, &o, rhs_expr, type_hint);
  4726. if (o.mode == Addressing_NoValue) {
  4727. error_operand_no_value(&o);
  4728. o.mode = Addressing_Invalid;
  4729. }
  4730. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4731. if (lhs.count == 2 && rhs.count == 1 &&
  4732. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4733. Ast *expr = unparen_expr(o.expr);
  4734. Operand val0 = o;
  4735. Operand val1 = o;
  4736. val0.mode = Addressing_Value;
  4737. val1.mode = Addressing_Value;
  4738. val1.type = t_untyped_bool;
  4739. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4740. if (expr->kind == Ast_TypeAssertion &&
  4741. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4742. // NOTE(bill): Used only for optimizations in the backend
  4743. if (is_blank_ident(lhs[0].expr)) {
  4744. expr->TypeAssertion.ignores[0] = true;
  4745. }
  4746. if (is_blank_ident(lhs[1].expr)) {
  4747. expr->TypeAssertion.ignores[1] = true;
  4748. }
  4749. }
  4750. array_add(operands, val0);
  4751. array_add(operands, val1);
  4752. optional_ok = true;
  4753. tuple_index += 2;
  4754. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4755. Type *tuple = o.type;
  4756. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4757. Ast *expr = unparen_expr(o.expr);
  4758. if (expr->kind == Ast_CallExpr) {
  4759. expr->CallExpr.optional_ok_one = true;
  4760. }
  4761. Operand val = o;
  4762. val.type = tuple->Tuple.variables[0]->type;
  4763. val.mode = Addressing_Value;
  4764. array_add(operands, val);
  4765. tuple_index += tuple->Tuple.variables.count;
  4766. } else {
  4767. array_add(operands, o);
  4768. tuple_index += 1;
  4769. }
  4770. } else {
  4771. TypeTuple *tuple = &o.type->Tuple;
  4772. for (Entity *e : tuple->variables) {
  4773. o.type = e->type;
  4774. array_add(operands, o);
  4775. check_no_copy_assignment(o, str_lit("assignment"));
  4776. }
  4777. tuple_index += tuple->variables.count;
  4778. }
  4779. }
  4780. return optional_ok;
  4781. }
  4782. typedef u32 UnpackFlags;
  4783. enum UnpackFlag : u32 {
  4784. UnpackFlag_None = 0,
  4785. UnpackFlag_AllowOk = 1<<0,
  4786. UnpackFlag_IsVariadic = 1<<1,
  4787. UnpackFlag_AllowUndef = 1<<2,
  4788. };
  4789. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4790. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4791. if (lhs == nullptr || c->decl == nullptr) {
  4792. return tuple_count;
  4793. }
  4794. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4795. Entity *e = lhs[tuple_index + j];
  4796. if (e == nullptr) {
  4797. continue;
  4798. }
  4799. DeclInfo *decl = decl_info_of_entity(e);
  4800. if (decl == nullptr) {
  4801. continue;
  4802. }
  4803. rw_mutex_shared_lock(&decl->deps_mutex);
  4804. rw_mutex_lock(&c->decl->deps_mutex);
  4805. for (Entity *dep : decl->deps) {
  4806. ptr_set_add(&c->decl->deps, dep);
  4807. }
  4808. rw_mutex_unlock(&c->decl->deps_mutex);
  4809. rw_mutex_shared_unlock(&decl->deps_mutex);
  4810. }
  4811. return tuple_count;
  4812. };
  4813. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4814. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4815. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4816. bool optional_ok = false;
  4817. isize tuple_index = 0;
  4818. for (Ast *rhs : rhs_arguments) {
  4819. if (rhs->kind == Ast_FieldValue) {
  4820. error(rhs, "Invalid use of 'field = value'");
  4821. rhs = rhs->FieldValue.value;
  4822. }
  4823. CheckerContext c_ = *ctx;
  4824. CheckerContext *c = &c_;
  4825. Operand o = {};
  4826. Type *type_hint = nullptr;
  4827. if (lhs != nullptr && tuple_index < lhs_count) {
  4828. // NOTE(bill): override DeclInfo for dependency
  4829. Entity *e = lhs[tuple_index];
  4830. if (e != nullptr) {
  4831. type_hint = e->type;
  4832. if (e->flags & EntityFlag_Ellipsis) {
  4833. GB_ASSERT(is_type_slice(e->type));
  4834. GB_ASSERT(e->type->kind == Type_Slice);
  4835. type_hint = e->type->Slice.elem;
  4836. }
  4837. }
  4838. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4839. // NOTE(bill): override DeclInfo for dependency
  4840. Entity *e = lhs[lhs_count-1];
  4841. if (e != nullptr) {
  4842. type_hint = e->type;
  4843. if (e->flags & EntityFlag_Ellipsis) {
  4844. GB_ASSERT(is_type_slice(e->type));
  4845. GB_ASSERT(e->type->kind == Type_Slice);
  4846. type_hint = e->type->Slice.elem;
  4847. }
  4848. }
  4849. }
  4850. Ast *rhs_expr = unparen_expr(rhs);
  4851. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4852. // NOTE(bill): Just handle this very specific logic here
  4853. o.type = t_untyped_uninit;
  4854. o.mode = Addressing_Value;
  4855. o.expr = rhs;
  4856. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4857. } else {
  4858. check_expr_base(c, &o, rhs, type_hint);
  4859. }
  4860. if (o.mode == Addressing_NoValue) {
  4861. error_operand_no_value(&o);
  4862. o.mode = Addressing_Invalid;
  4863. }
  4864. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4865. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4866. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4867. Ast *expr = unparen_expr(o.expr);
  4868. Operand val0 = o;
  4869. Operand val1 = o;
  4870. val0.mode = Addressing_Value;
  4871. val1.mode = Addressing_Value;
  4872. val1.type = t_untyped_bool;
  4873. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4874. if (expr->kind == Ast_TypeAssertion &&
  4875. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4876. // NOTE(bill): Used only for optimizations in the backend
  4877. if (is_blank_ident(lhs[0]->token)) {
  4878. expr->TypeAssertion.ignores[0] = true;
  4879. }
  4880. if (is_blank_ident(lhs[1]->token)) {
  4881. expr->TypeAssertion.ignores[1] = true;
  4882. }
  4883. }
  4884. array_add(operands, val0);
  4885. array_add(operands, val1);
  4886. optional_ok = true;
  4887. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4888. } else {
  4889. array_add(operands, o);
  4890. tuple_index += 1;
  4891. }
  4892. } else {
  4893. TypeTuple *tuple = &o.type->Tuple;
  4894. for (Entity *e : tuple->variables) {
  4895. o.type = e->type;
  4896. array_add(operands, o);
  4897. }
  4898. isize count = tuple->variables.count;
  4899. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4900. }
  4901. }
  4902. return optional_ok;
  4903. }
  4904. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4905. GB_ASSERT(pt != nullptr);
  4906. GB_ASSERT(pt->kind == Type_Proc);
  4907. isize param_count = 0;
  4908. isize param_count_excluding_defaults = 0;
  4909. bool variadic = pt->Proc.variadic;
  4910. TypeTuple *param_tuple = nullptr;
  4911. if (pt->Proc.params != nullptr) {
  4912. param_tuple = &pt->Proc.params->Tuple;
  4913. param_count = param_tuple->variables.count;
  4914. if (variadic) {
  4915. for (isize i = param_count-1; i >= 0; i--) {
  4916. Entity *e = param_tuple->variables[i];
  4917. if (e->kind == Entity_TypeName) {
  4918. break;
  4919. }
  4920. if (e->kind == Entity_Variable) {
  4921. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4922. param_count--;
  4923. continue;
  4924. }
  4925. }
  4926. break;
  4927. }
  4928. param_count--;
  4929. }
  4930. }
  4931. param_count_excluding_defaults = param_count;
  4932. if (param_tuple != nullptr) {
  4933. for (isize i = param_count-1; i >= 0; i--) {
  4934. Entity *e = param_tuple->variables[i];
  4935. if (e->kind == Entity_TypeName) {
  4936. break;
  4937. }
  4938. if (e->kind == Entity_Variable) {
  4939. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4940. param_count_excluding_defaults--;
  4941. continue;
  4942. }
  4943. }
  4944. break;
  4945. }
  4946. }
  4947. if (param_count_) *param_count_ = param_count;
  4948. return param_count_excluding_defaults;
  4949. }
  4950. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4951. isize param_count = pt->param_count;
  4952. for (isize i = 0; i < param_count; i++) {
  4953. Entity *e = pt->params->Tuple.variables[i];
  4954. String name = e->token.string;
  4955. if (is_blank_ident(name)) {
  4956. continue;
  4957. }
  4958. if (name == parameter_name) {
  4959. return i;
  4960. }
  4961. }
  4962. return -1;
  4963. }
  4964. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4965. type = base_type(type);
  4966. GB_ASSERT(type->kind == Type_Proc);
  4967. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4968. }
  4969. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  4970. Entity *entity, Type *proc_type,
  4971. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  4972. CallArgumentErrorMode show_error_mode,
  4973. CallArgumentData *data) {
  4974. TEMPORARY_ALLOCATOR_GUARD();
  4975. CallArgumentError err = CallArgumentError_None;
  4976. ast_node(ce, CallExpr, call);
  4977. GB_ASSERT(is_type_proc(proc_type));
  4978. proc_type = base_type(proc_type);
  4979. TypeProc *pt = &proc_type->Proc;
  4980. isize param_count = 0;
  4981. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4982. bool variadic = pt->variadic;
  4983. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4984. i64 score = 0;
  4985. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  4986. Type *final_proc_type = proc_type;
  4987. Entity *gen_entity = nullptr;
  4988. if (vari_expand && !variadic) {
  4989. if (show_error) {
  4990. error(ce->ellipsis,
  4991. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4992. LIT(ce->proc->Ident.token.string));
  4993. }
  4994. err = CallArgumentError_NonVariadicExpand;
  4995. } else if (vari_expand && pt->c_vararg) {
  4996. if (show_error) {
  4997. error(ce->ellipsis,
  4998. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4999. LIT(ce->proc->Ident.token.string));
  5000. }
  5001. err = CallArgumentError_NonVariadicExpand;
  5002. }
  5003. GB_ASSERT(ce->split_args);
  5004. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5005. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5006. defer ({
  5007. for (Operand const &o : ordered_operands) {
  5008. if (o.expr != nullptr) {
  5009. call->viral_state_flags |= o.expr->viral_state_flags;
  5010. }
  5011. }
  5012. });
  5013. isize positional_operand_count = positional_operands.count;
  5014. if (variadic) {
  5015. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5016. } else if (positional_operand_count > pt->param_count) {
  5017. err = CallArgumentError_TooManyArguments;
  5018. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5019. if (show_error) {
  5020. gbString proc_str = expr_to_string(ce->proc);
  5021. defer (gb_string_free(proc_str));
  5022. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5023. }
  5024. return err;
  5025. }
  5026. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5027. for (isize i = 0; i < positional_operand_count; i++) {
  5028. ordered_operands[i] = positional_operands[i];
  5029. visited[i] = true;
  5030. }
  5031. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5032. bool named_variadic_param = false;
  5033. if (named_operands.count != 0) {
  5034. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5035. for_array(i, ce->split_args->named) {
  5036. Ast *arg = ce->split_args->named[i];
  5037. Operand operand = named_operands[i];
  5038. ast_node(fv, FieldValue, arg);
  5039. if (fv->field->kind != Ast_Ident) {
  5040. if (show_error) {
  5041. gbString expr_str = expr_to_string(fv->field);
  5042. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5043. gb_string_free(expr_str);
  5044. }
  5045. err = CallArgumentError_InvalidFieldValue;
  5046. continue;
  5047. }
  5048. String name = fv->field->Ident.token.string;
  5049. isize param_index = lookup_procedure_parameter(pt, name);
  5050. if (param_index < 0) {
  5051. if (show_error) {
  5052. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5053. }
  5054. err = CallArgumentError_ParameterNotFound;
  5055. continue;
  5056. }
  5057. if (pt->variadic && param_index == pt->variadic_index) {
  5058. named_variadic_param = true;
  5059. }
  5060. if (visited[param_index]) {
  5061. if (show_error) {
  5062. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5063. }
  5064. err = CallArgumentError_DuplicateParameter;
  5065. continue;
  5066. }
  5067. visited[param_index] = true;
  5068. ordered_operands[param_index] = operand;
  5069. }
  5070. }
  5071. isize dummy_argument_count = 0;
  5072. bool actually_variadic = false;
  5073. if (variadic) {
  5074. if (visited[pt->variadic_index] &&
  5075. positional_operand_count < positional_operands.count) {
  5076. if (show_error) {
  5077. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5078. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5079. }
  5080. err = CallArgumentError_DuplicateParameter;
  5081. } else if (!visited[pt->variadic_index]) {
  5082. visited[pt->variadic_index] = true;
  5083. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5084. if (vari_expand) {
  5085. GB_ASSERT(variadic_operands.count != 0);
  5086. *variadic_operand = variadic_operands[0];
  5087. variadic_operand->type = default_type(variadic_operand->type);
  5088. actually_variadic = true;
  5089. } else {
  5090. AstFile *f = call->file();
  5091. // HACK(bill): this is an awful hack
  5092. Operand o = {};
  5093. o.mode = Addressing_Value;
  5094. o.expr = ast_ident(f, make_token_ident("nil"));
  5095. o.expr->Ident.token.pos = ast_token(call).pos;
  5096. if (variadic_operands.count != 0) {
  5097. actually_variadic = true;
  5098. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5099. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5100. o.type = vt->type;
  5101. } else {
  5102. dummy_argument_count += 1;
  5103. o.type = t_untyped_nil;
  5104. }
  5105. *variadic_operand = o;
  5106. }
  5107. }
  5108. }
  5109. for (Operand const &o : ordered_operands) {
  5110. if (o.mode != Addressing_Invalid) {
  5111. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5112. }
  5113. }
  5114. for (isize i = 0; i < pt->param_count; i++) {
  5115. if (!visited[i]) {
  5116. Entity *e = pt->params->Tuple.variables[i];
  5117. if (e->kind == Entity_Variable) {
  5118. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5119. ordered_operands[i].mode = Addressing_Value;
  5120. ordered_operands[i].type = e->type;
  5121. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5122. dummy_argument_count += 1;
  5123. score += assign_score_function(1);
  5124. continue;
  5125. }
  5126. }
  5127. if (show_error) {
  5128. if (e->kind == Entity_TypeName) {
  5129. error(call, "Type parameter '%.*s' is missing in procedure call",
  5130. LIT(e->token.string));
  5131. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5132. // Ignore
  5133. } else {
  5134. gbString str = type_to_string(e->type);
  5135. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5136. LIT(e->token.string), str);
  5137. gb_string_free(str);
  5138. }
  5139. }
  5140. err = CallArgumentError_ParameterMissing;
  5141. }
  5142. }
  5143. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5144. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5145. i64 s = 0;
  5146. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5147. bool ok = false;
  5148. if (e && (e->flags & EntityFlag_AnyInt)) {
  5149. if (is_type_integer(param_type)) {
  5150. ok = check_is_castable_to(c, o, param_type);
  5151. }
  5152. }
  5153. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5154. if (show_error) {
  5155. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5156. }
  5157. }
  5158. if (ok) {
  5159. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5160. } else {
  5161. if (show_error) {
  5162. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5163. Type *src = base_type(o->type);
  5164. Type *dst = base_type(param_type);
  5165. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  5166. gbString a = expr_to_string(o->expr);
  5167. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  5168. gb_string_free(a);
  5169. }
  5170. }
  5171. err = CallArgumentError_WrongTypes;
  5172. }
  5173. } else if (show_error) {
  5174. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5175. }
  5176. if (e && e->flags & EntityFlag_ConstInput) {
  5177. if (o->mode != Addressing_Constant) {
  5178. if (show_error) {
  5179. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5180. }
  5181. err = CallArgumentError_NoneConstantParameter;
  5182. }
  5183. }
  5184. if (!err && is_type_any(param_type)) {
  5185. add_type_info_type(c, o->type);
  5186. }
  5187. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5188. add_type_info_type(c, o->type);
  5189. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5190. } else if (show_error && is_type_untyped(o->type)) {
  5191. update_untyped_expr_type(c, o->expr, param_type, true);
  5192. }
  5193. return s;
  5194. };
  5195. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5196. err = CallArgumentError_None;
  5197. if (variadic) {
  5198. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5199. Type *t = pt->params->Tuple.variables[0]->type;
  5200. if (is_type_polymorphic(t)) {
  5201. if (show_error) {
  5202. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5203. }
  5204. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5205. }
  5206. }
  5207. } else {
  5208. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5209. PolyProcData poly_proc_data = {};
  5210. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5211. gen_entity = poly_proc_data.gen_entity;
  5212. Type *gept = base_type(gen_entity->type);
  5213. GB_ASSERT(is_type_proc(gept));
  5214. final_proc_type = gen_entity->type;
  5215. pt = &gept->Proc;
  5216. } else {
  5217. err = CallArgumentError_WrongTypes;
  5218. }
  5219. }
  5220. for (isize i = 0; i < pt->param_count; i++) {
  5221. Operand *o = &ordered_operands[i];
  5222. if (o->mode == Addressing_Invalid) {
  5223. continue;
  5224. }
  5225. Entity *e = pt->params->Tuple.variables[i];
  5226. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5227. if (e->kind == Entity_TypeName) {
  5228. GB_ASSERT(pt->is_polymorphic);
  5229. if (o->mode != Addressing_Type) {
  5230. if (show_error) {
  5231. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5232. }
  5233. err = CallArgumentError_WrongTypes;
  5234. }
  5235. if (are_types_identical(e->type, o->type)) {
  5236. score += assign_score_function(1);
  5237. } else {
  5238. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5239. }
  5240. continue;
  5241. }
  5242. if (param_is_variadic) {
  5243. continue;
  5244. }
  5245. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5246. }
  5247. }
  5248. if (variadic) {
  5249. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5250. Type *slice = var_entity->type;
  5251. GB_ASSERT(is_type_slice(slice));
  5252. Type *elem = base_type(slice)->Slice.elem;
  5253. Type *t = elem;
  5254. if (is_type_polymorphic(t)) {
  5255. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5256. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5257. }
  5258. for_array(operand_index, variadic_operands) {
  5259. Operand *o = &variadic_operands[operand_index];
  5260. if (vari_expand) {
  5261. t = slice;
  5262. if (operand_index > 0) {
  5263. if (show_error) {
  5264. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5265. }
  5266. if (data) {
  5267. data->score = score;
  5268. data->result_type = final_proc_type->Proc.results;
  5269. data->gen_entity = gen_entity;
  5270. }
  5271. return CallArgumentError_MultipleVariadicExpand;
  5272. }
  5273. }
  5274. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5275. }
  5276. }
  5277. if (data) {
  5278. data->score = score;
  5279. data->result_type = final_proc_type->Proc.results;
  5280. data->gen_entity = gen_entity;
  5281. Ast *proc_lit = nullptr;
  5282. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5283. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5284. if (vp && vp->kind == Ast_ProcLit) {
  5285. proc_lit = vp;
  5286. }
  5287. }
  5288. if (proc_lit == nullptr) {
  5289. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5290. }
  5291. }
  5292. return err;
  5293. }
  5294. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5295. GB_ASSERT(ce != nullptr);
  5296. if (ce->args.count == 0) {
  5297. return false;
  5298. }
  5299. return ce->args[0]->kind == Ast_FieldValue;
  5300. }
  5301. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5302. Entity **lhs = nullptr;
  5303. isize lhs_count = -1;
  5304. if (proc_type == nullptr) {
  5305. return nullptr;
  5306. }
  5307. GB_ASSERT(is_type_proc(proc_type));
  5308. TypeProc *pt = &base_type(proc_type)->Proc;
  5309. *is_variadic = pt->variadic;
  5310. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5311. if (pt->params != nullptr) {
  5312. lhs = pt->params->Tuple.variables.data;
  5313. lhs_count = pt->params->Tuple.variables.count;
  5314. }
  5315. } else {
  5316. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5317. if (pt->params == nullptr) {
  5318. lhs_count = 0;
  5319. } else {
  5320. lhs_count = pt->params->Tuple.variables.count;
  5321. }
  5322. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5323. for (isize i = 0; i < lhs_count; i++) {
  5324. Entity *e = pt->params->Tuple.variables[i];
  5325. if (!is_type_polymorphic(e->type)) {
  5326. lhs[i] = e;
  5327. }
  5328. }
  5329. }
  5330. if (lhs_count_) *lhs_count_ = lhs_count;
  5331. return lhs;
  5332. }
  5333. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5334. if (clauses != nullptr) {
  5335. for (Ast *clause : *clauses) {
  5336. Operand o = {};
  5337. check_expr(ctx, &o, clause);
  5338. if (o.mode != Addressing_Constant) {
  5339. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5340. if (print_err && call_expr) error(call_expr, "at caller location");
  5341. return false;
  5342. } else if (o.value.kind != ExactValue_Bool) {
  5343. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5344. if (print_err && call_expr) error(call_expr, "at caller location");
  5345. return false;
  5346. } else if (!o.value.value_bool) {
  5347. if (print_err) {
  5348. ERROR_BLOCK();
  5349. gbString str = expr_to_string(clause);
  5350. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5351. gb_string_free(str);
  5352. if (scope != nullptr) {
  5353. isize print_count = 0;
  5354. for (auto const &entry : scope->elements) {
  5355. Entity *e = entry.value;
  5356. switch (e->kind) {
  5357. case Entity_TypeName: {
  5358. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5359. gbString str = type_to_string(e->type);
  5360. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5361. gb_string_free(str);
  5362. print_count += 1;
  5363. break;
  5364. }
  5365. case Entity_Constant: {
  5366. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5367. gbString str = exact_value_to_string(e->Constant.value);
  5368. if (is_type_untyped(e->type)) {
  5369. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5370. } else {
  5371. gbString t = type_to_string(e->type);
  5372. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5373. gb_string_free(t);
  5374. }
  5375. gb_string_free(str);
  5376. print_count += 1;
  5377. break;
  5378. }
  5379. }
  5380. }
  5381. }
  5382. if (call_expr) {
  5383. TokenPos pos = ast_token(call_expr).pos;
  5384. error_line("%s at caller location\n", token_pos_to_string(pos));
  5385. }
  5386. }
  5387. return false;
  5388. }
  5389. }
  5390. }
  5391. return true;
  5392. }
  5393. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5394. bool success = true;
  5395. type = base_type(type);
  5396. if (named_args.count > 0) {
  5397. TypeProc *pt = nullptr;
  5398. if (is_type_proc(type)) {
  5399. pt = &type->Proc;
  5400. }
  5401. for_array(i, named_args) {
  5402. Ast *arg = named_args[i];
  5403. if (arg->kind != Ast_FieldValue) {
  5404. if (show_error) {
  5405. error(arg, "Expected a 'field = value'");
  5406. }
  5407. return false;
  5408. }
  5409. ast_node(fv, FieldValue, arg);
  5410. if (fv->field->kind != Ast_Ident) {
  5411. if (show_error) {
  5412. gbString expr_str = expr_to_string(fv->field);
  5413. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5414. gb_string_free(expr_str);
  5415. }
  5416. success = false;
  5417. continue;
  5418. }
  5419. String key = fv->field->Ident.token.string;
  5420. Ast *value = fv->value;
  5421. Type *type_hint = nullptr;
  5422. if (pt) {
  5423. isize param_index = lookup_procedure_parameter(pt, key);
  5424. if (param_index < 0) {
  5425. if (show_error) {
  5426. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5427. }
  5428. success = false;
  5429. continue;
  5430. }
  5431. Entity *e = pt->params->Tuple.variables[param_index];
  5432. if (!is_type_polymorphic(e->type)) {
  5433. type_hint = e->type;
  5434. }
  5435. }
  5436. Operand o = {};
  5437. check_expr_with_type_hint(c, &o, value, type_hint);
  5438. if (o.mode == Addressing_Invalid) {
  5439. success = false;
  5440. }
  5441. array_add(named_operands, o);
  5442. }
  5443. }
  5444. return success;
  5445. }
  5446. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5447. Entity *e, Type *proc_type,
  5448. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5449. CallArgumentErrorMode show_error_mode,
  5450. CallArgumentData *data) {
  5451. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5452. Ast *ident = operand->expr;
  5453. while (ident->kind == Ast_SelectorExpr) {
  5454. Ast *s = ident->SelectorExpr.selector;
  5455. ident = s;
  5456. }
  5457. if (e == nullptr) {
  5458. e = entity_of_node(ident);
  5459. if (e != nullptr) {
  5460. proc_type = e->type;
  5461. }
  5462. }
  5463. GB_ASSERT(proc_type != nullptr);
  5464. proc_type = base_type(proc_type);
  5465. GB_ASSERT(proc_type->kind == Type_Proc);
  5466. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5467. if (return_on_failure && err != CallArgumentError_None) {
  5468. return false;
  5469. }
  5470. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5471. if (!return_on_failure && entity_to_use != nullptr) {
  5472. add_entity_use(c, ident, entity_to_use);
  5473. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5474. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5475. }
  5476. if (data->gen_entity != nullptr) {
  5477. Entity *e = data->gen_entity;
  5478. DeclInfo *decl = data->gen_entity->decl_info;
  5479. CheckerContext ctx = *c;
  5480. ctx.scope = decl->scope;
  5481. ctx.decl = decl;
  5482. ctx.proc_name = e->token.string;
  5483. ctx.curr_proc_decl = decl;
  5484. ctx.curr_proc_sig = e->type;
  5485. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5486. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5487. if (return_on_failure) {
  5488. if (!ok) {
  5489. return false;
  5490. }
  5491. } else {
  5492. decl->where_clauses_evaluated = true;
  5493. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5494. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5495. }
  5496. if (is_type_proc(data->gen_entity->type)) {
  5497. Type *t = base_type(entity_to_use->type);
  5498. data->result_type = t->Proc.results;
  5499. }
  5500. }
  5501. }
  5502. return true;
  5503. }
  5504. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5505. ast_node(ce, CallExpr, call);
  5506. GB_ASSERT(ce->split_args != nullptr);
  5507. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5508. Slice<Ast *> const &named_args = ce->split_args->named;
  5509. CallArgumentData data = {};
  5510. data.result_type = t_invalid;
  5511. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5512. auto procs = proc_group_entities_cloned(c, *operand);
  5513. if (procs.count > 1) {
  5514. isize max_arg_count = positional_args.count + named_args.count;
  5515. for (Ast *arg : positional_args) {
  5516. // NOTE(bill): The only thing that may have multiple values
  5517. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5518. arg = strip_or_return_expr(arg);
  5519. if (arg && arg->kind == Ast_CallExpr) {
  5520. max_arg_count = ISIZE_MAX;
  5521. break;
  5522. }
  5523. }
  5524. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5525. // NOTE(bill): The only thing that may have multiple values
  5526. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5527. if (arg->kind == Ast_FieldValue) {
  5528. arg = strip_or_return_expr(arg->FieldValue.value);
  5529. if (arg && arg->kind == Ast_CallExpr) {
  5530. max_arg_count = ISIZE_MAX;
  5531. break;
  5532. }
  5533. }
  5534. }
  5535. // ignore named arguments first
  5536. for (Ast *arg : named_args) {
  5537. if (arg->kind != Ast_FieldValue) {
  5538. continue;
  5539. }
  5540. ast_node(fv, FieldValue, arg);
  5541. if (fv->field->kind != Ast_Ident) {
  5542. continue;
  5543. }
  5544. String key = fv->field->Ident.token.string;
  5545. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5546. Type *t = procs[proc_index]->type;
  5547. if (is_type_proc(t)) {
  5548. isize param_index = lookup_procedure_parameter(t, key);
  5549. if (param_index < 0) {
  5550. array_unordered_remove(&procs, proc_index);
  5551. }
  5552. }
  5553. }
  5554. }
  5555. if (procs.count == 0) {
  5556. // if any of the named arguments are wrong, the `procs` will be empty
  5557. // just start from scratch
  5558. array_free(&procs);
  5559. procs = proc_group_entities_cloned(c, *operand);
  5560. }
  5561. // filter by positional argument length
  5562. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5563. Entity *proc = procs[proc_index];
  5564. Type *pt = base_type(proc->type);
  5565. if (!(pt != nullptr && is_type_proc(pt))) {
  5566. proc_index++;
  5567. continue;
  5568. }
  5569. isize param_count = 0;
  5570. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5571. if (param_count_excluding_defaults > max_arg_count) {
  5572. array_unordered_remove(&procs, proc_index);
  5573. continue;
  5574. }
  5575. proc_index++;
  5576. }
  5577. }
  5578. Entity **lhs = nullptr;
  5579. isize lhs_count = -1;
  5580. bool is_variadic = false;
  5581. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5582. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5583. defer (array_free(&positional_operands));
  5584. defer (array_free(&named_operands));
  5585. if (procs.count == 1) {
  5586. Entity *e = procs[0];
  5587. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5588. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5589. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5590. check_call_arguments_single(c, call, operand,
  5591. e, e->type,
  5592. positional_operands, named_operands,
  5593. CallArgumentErrorMode::ShowErrors,
  5594. &data);
  5595. }
  5596. return data;
  5597. }
  5598. {
  5599. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5600. // where the same positional parameter has the same type value (and ellipsis)
  5601. isize proc_arg_count = -1;
  5602. for (Entity *p : procs) {
  5603. Type *pt = base_type(p->type);
  5604. if (pt != nullptr && is_type_proc(pt)) {
  5605. if (proc_arg_count < 0) {
  5606. proc_arg_count = pt->Proc.param_count;
  5607. } else {
  5608. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5609. }
  5610. }
  5611. }
  5612. if (proc_arg_count >= 0) {
  5613. lhs_count = proc_arg_count;
  5614. if (lhs_count > 0) {
  5615. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5616. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5617. Entity *e = nullptr;
  5618. for (Entity *p : procs) {
  5619. Type *pt = base_type(p->type);
  5620. if (!(pt != nullptr && is_type_proc(pt))) {
  5621. continue;
  5622. }
  5623. if (e == nullptr) {
  5624. e = pt->Proc.params->Tuple.variables[param_index];
  5625. } else {
  5626. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5627. if (e == f) {
  5628. continue;
  5629. }
  5630. if (are_types_identical(e->type, f->type)) {
  5631. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5632. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5633. if (ee == fe) {
  5634. continue;
  5635. }
  5636. }
  5637. // NOTE(bill): Entities are not close enough to be used
  5638. e = nullptr;
  5639. break;
  5640. }
  5641. }
  5642. lhs[param_index] = e;
  5643. }
  5644. }
  5645. }
  5646. }
  5647. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5648. for_array(i, named_args) {
  5649. Ast *arg = named_args[i];
  5650. if (arg->kind != Ast_FieldValue) {
  5651. error(arg, "Expected a 'field = value'");
  5652. return data;
  5653. }
  5654. ast_node(fv, FieldValue, arg);
  5655. if (fv->field->kind != Ast_Ident) {
  5656. gbString expr_str = expr_to_string(fv->field);
  5657. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5658. gb_string_free(expr_str);
  5659. return data;
  5660. }
  5661. String key = fv->field->Ident.token.string;
  5662. Ast *value = fv->value;
  5663. Type *type_hint = nullptr;
  5664. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5665. Entity *e = lhs[lhs_idx];
  5666. if (e != nullptr && e->token.string == key &&
  5667. !is_type_polymorphic(e->type)) {
  5668. type_hint = e->type;
  5669. break;
  5670. }
  5671. }
  5672. Operand o = {};
  5673. check_expr_with_type_hint(c, &o, value, type_hint);
  5674. array_add(&named_operands, o);
  5675. }
  5676. gb_free(heap_allocator(), lhs);
  5677. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5678. defer (array_free(&valids));
  5679. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5680. defer (array_free(&proc_entities));
  5681. for (Entity *proc : procs) {
  5682. array_add(&proc_entities, proc);
  5683. }
  5684. gbString expr_name = expr_to_string(operand->expr);
  5685. defer (gb_string_free(expr_name));
  5686. for_array(i, procs) {
  5687. Entity *p = procs[i];
  5688. Type *pt = base_type(p->type);
  5689. if (pt != nullptr && is_type_proc(pt)) {
  5690. CallArgumentData data = {};
  5691. CheckerContext ctx = *c;
  5692. ctx.no_polymorphic_errors = true;
  5693. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5694. ctx.hide_polymorphic_errors = true;
  5695. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5696. p, pt,
  5697. positional_operands, named_operands,
  5698. CallArgumentErrorMode::NoErrors,
  5699. &data);
  5700. if (!is_a_candidate) {
  5701. continue;
  5702. }
  5703. isize index = i;
  5704. ValidIndexAndScore item = {};
  5705. item.score = data.score;
  5706. if (data.gen_entity != nullptr) {
  5707. array_add(&proc_entities, data.gen_entity);
  5708. index = proc_entities.count-1;
  5709. // prefer non-polymorphic procedures over polymorphic
  5710. item.score += assign_score_function(1);
  5711. }
  5712. item.index = index;
  5713. array_add(&valids, item);
  5714. }
  5715. }
  5716. if (valids.count > 1) {
  5717. array_sort(valids, valid_index_and_score_cmp);
  5718. i64 best_score = valids[0].score;
  5719. Entity *best_entity = proc_entities[valids[0].index];
  5720. GB_ASSERT(best_entity != nullptr);
  5721. for (isize i = 1; i < valids.count; i++) {
  5722. if (best_score > valids[i].score) {
  5723. valids.count = i;
  5724. break;
  5725. }
  5726. if (best_entity == proc_entities[valids[i].index]) {
  5727. valids.count = i;
  5728. break;
  5729. }
  5730. }
  5731. }
  5732. auto print_argument_types = [&]() {
  5733. error_line("\tGiven argument types: (");
  5734. isize i = 0;
  5735. for (Operand const &o : positional_operands) {
  5736. if (i++ > 0) error_line(", ");
  5737. gbString type = type_to_string(o.type);
  5738. defer (gb_string_free(type));
  5739. error_line("%s", type);
  5740. }
  5741. for (Operand const &o : named_operands) {
  5742. if (i++ > 0) error_line(", ");
  5743. gbString type = type_to_string(o.type);
  5744. defer (gb_string_free(type));
  5745. if (i < ce->split_args->named.count) {
  5746. Ast *named_field = ce->split_args->named[i];
  5747. ast_node(fv, FieldValue, named_field);
  5748. gbString field = expr_to_string(fv->field);
  5749. defer (gb_string_free(field));
  5750. error_line("%s = %s", field, type);
  5751. } else {
  5752. error_line("%s", type);
  5753. }
  5754. }
  5755. error_line(")\n");
  5756. };
  5757. if (valids.count == 0) {
  5758. ERROR_BLOCK();
  5759. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5760. if (positional_operands.count == 0 && named_operands.count == 0) {
  5761. error_line("\tNo given arguments\n");
  5762. } else {
  5763. print_argument_types();
  5764. }
  5765. if (procs.count == 0) {
  5766. procs = proc_group_entities_cloned(c, *operand);
  5767. }
  5768. if (procs.count > 0) {
  5769. error_line("Did you mean to use one of the following:\n");
  5770. }
  5771. isize max_name_length = 0;
  5772. isize max_type_length = 0;
  5773. for (Entity *proc : procs) {
  5774. Type *t = base_type(proc->type);
  5775. if (t == t_invalid) continue;
  5776. String prefix = {};
  5777. String prefix_sep = {};
  5778. if (proc->pkg) {
  5779. prefix = proc->pkg->name;
  5780. prefix_sep = str_lit(".");
  5781. }
  5782. String name = proc->token.string;
  5783. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5784. gbString pt;
  5785. if (t->Proc.node != nullptr) {
  5786. pt = expr_to_string(t->Proc.node);
  5787. } else {
  5788. pt = type_to_string(t);
  5789. }
  5790. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5791. gb_string_free(pt);
  5792. }
  5793. isize max_spaces = gb_max(max_name_length, max_type_length);
  5794. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5795. for (isize i = 0; i < max_spaces; i++) {
  5796. spaces[i] = ' ';
  5797. }
  5798. spaces[max_spaces] = 0;
  5799. for (Entity *proc : procs) {
  5800. TokenPos pos = proc->token.pos;
  5801. Type *t = base_type(proc->type);
  5802. if (t == t_invalid) continue;
  5803. GB_ASSERT(t->kind == Type_Proc);
  5804. gbString pt;
  5805. defer (gb_string_free(pt));
  5806. if (t->Proc.node != nullptr) {
  5807. pt = expr_to_string(t->Proc.node);
  5808. } else {
  5809. pt = type_to_string(t);
  5810. }
  5811. String prefix = {};
  5812. String prefix_sep = {};
  5813. if (proc->pkg) {
  5814. prefix = proc->pkg->name;
  5815. prefix_sep = str_lit(".");
  5816. }
  5817. String name = proc->token.string;
  5818. isize len = prefix.len + prefix_sep.len + name.len;
  5819. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5820. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5821. char const *sep = "::";
  5822. if (proc->kind == Entity_Variable) {
  5823. sep = ":=";
  5824. }
  5825. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5826. LIT(prefix), LIT(prefix_sep), LIT(name),
  5827. name_padding, spaces,
  5828. sep,
  5829. pt,
  5830. type_padding, spaces,
  5831. token_pos_to_string(pos)
  5832. );
  5833. }
  5834. if (procs.count > 0) {
  5835. error_line("\n");
  5836. }
  5837. data.result_type = t_invalid;
  5838. } else if (valids.count > 1) {
  5839. ERROR_BLOCK();
  5840. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5841. print_argument_types();
  5842. for (auto const &valid : valids) {
  5843. Entity *proc = proc_entities[valid.index];
  5844. GB_ASSERT(proc != nullptr);
  5845. TokenPos pos = proc->token.pos;
  5846. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5847. gbString pt = nullptr;
  5848. defer (gb_string_free(pt));
  5849. if (t->Proc.node != nullptr) {
  5850. pt = expr_to_string(t->Proc.node);
  5851. } else {
  5852. pt = type_to_string(t);
  5853. }
  5854. String name = proc->token.string;
  5855. char const *sep = "::";
  5856. if (proc->kind == Entity_Variable) {
  5857. sep = ":=";
  5858. }
  5859. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5860. if (proc->decl_info->proc_lit != nullptr) {
  5861. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5862. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5863. if (pl->where_token.kind != Token_Invalid) {
  5864. error_line("\n\t\twhere ");
  5865. for_array(j, pl->where_clauses) {
  5866. Ast *clause = pl->where_clauses[j];
  5867. if (j != 0) {
  5868. error_line("\t\t ");
  5869. }
  5870. gbString str = expr_to_string(clause);
  5871. error_line("%s", str);
  5872. gb_string_free(str);
  5873. if (j != pl->where_clauses.count-1) {
  5874. error_line(",");
  5875. }
  5876. }
  5877. error_line("\n\t");
  5878. }
  5879. }
  5880. error_line("at %s\n", token_pos_to_string(pos));
  5881. }
  5882. data.result_type = t_invalid;
  5883. } else {
  5884. GB_ASSERT(valids.count == 1);
  5885. Ast *ident = operand->expr;
  5886. while (ident->kind == Ast_SelectorExpr) {
  5887. Ast *s = ident->SelectorExpr.selector;
  5888. ident = s;
  5889. }
  5890. Entity *e = proc_entities[valids[0].index];
  5891. GB_ASSERT(e != nullptr);
  5892. Array<Operand> named_operands = {};
  5893. check_call_arguments_single(c, call, operand,
  5894. e, e->type,
  5895. positional_operands, named_operands,
  5896. CallArgumentErrorMode::ShowErrors,
  5897. &data);
  5898. return data;
  5899. }
  5900. return data;
  5901. }
  5902. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5903. Type *proc_type = nullptr;
  5904. CallArgumentData data = {};
  5905. data.result_type = t_invalid;
  5906. proc_type = base_type(operand->type);
  5907. TypeProc *pt = nullptr;
  5908. if (proc_type) {
  5909. pt = &proc_type->Proc;
  5910. }
  5911. TEMPORARY_ALLOCATOR_GUARD();
  5912. ast_node(ce, CallExpr, call);
  5913. bool any_failure = false;
  5914. // Split positional and named args into separate arrays/slices
  5915. Slice<Ast *> positional_args = {};
  5916. Slice<Ast *> named_args = {};
  5917. if (ce->split_args == nullptr) {
  5918. positional_args = ce->args;
  5919. for (isize i = 0; i < ce->args.count; i++) {
  5920. Ast *arg = ce->args.data[i];
  5921. if (arg->kind == Ast_FieldValue) {
  5922. positional_args.count = i;
  5923. break;
  5924. }
  5925. }
  5926. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5927. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5928. split_args->positional = positional_args;
  5929. split_args->named = named_args;
  5930. ce->split_args = split_args;
  5931. } else {
  5932. positional_args = ce->split_args->positional;
  5933. named_args = ce->split_args->named;
  5934. }
  5935. if (operand->mode == Addressing_ProcGroup) {
  5936. return check_call_arguments_proc_group(c, operand, call);
  5937. }
  5938. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5939. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5940. defer (array_free(&positional_operands));
  5941. defer (array_free(&named_operands));
  5942. if (positional_args.count > 0) {
  5943. isize lhs_count = -1;
  5944. bool is_variadic = false;
  5945. Entity **lhs = nullptr;
  5946. if (pt != nullptr) {
  5947. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5948. }
  5949. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5950. }
  5951. if (named_args.count > 0) {
  5952. for_array(i, named_args) {
  5953. Ast *arg = named_args[i];
  5954. if (arg->kind != Ast_FieldValue) {
  5955. error(arg, "Expected a 'field = value'");
  5956. return data;
  5957. }
  5958. ast_node(fv, FieldValue, arg);
  5959. if (fv->field->kind != Ast_Ident) {
  5960. gbString expr_str = expr_to_string(fv->field);
  5961. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5962. any_failure = true;
  5963. gb_string_free(expr_str);
  5964. continue;
  5965. }
  5966. String key = fv->field->Ident.token.string;
  5967. Ast *value = fv->value;
  5968. isize param_index = lookup_procedure_parameter(pt, key);
  5969. Type *type_hint = nullptr;
  5970. if (param_index >= 0) {
  5971. Entity *e = pt->params->Tuple.variables[param_index];
  5972. type_hint = e->type;
  5973. }
  5974. Operand o = {};
  5975. check_expr_with_type_hint(c, &o, value, type_hint);
  5976. if (o.mode == Addressing_Invalid) {
  5977. any_failure = true;
  5978. }
  5979. array_add(&named_operands, o);
  5980. }
  5981. }
  5982. if (!any_failure) {
  5983. check_call_arguments_single(c, call, operand,
  5984. nullptr, proc_type,
  5985. positional_operands, named_operands,
  5986. CallArgumentErrorMode::ShowErrors,
  5987. &data);
  5988. } else if (pt) {
  5989. data.result_type = pt->results;
  5990. }
  5991. return data;
  5992. }
  5993. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5994. if (!is_type_polymorphic_record(t)) {
  5995. return -1;
  5996. }
  5997. TypeTuple *params = get_record_polymorphic_params(t);
  5998. if (params == nullptr) {
  5999. return -1;
  6000. }
  6001. for_array(i, params->variables) {
  6002. Entity *e = params->variables[i];
  6003. String name = e->token.string;
  6004. if (is_blank_ident(name)) {
  6005. continue;
  6006. }
  6007. if (name == parameter_name) {
  6008. return i;
  6009. }
  6010. }
  6011. return -1;
  6012. }
  6013. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6014. ast_node(ce, CallExpr, call);
  6015. Type *original_type = operand->type;
  6016. GB_ASSERT(is_type_polymorphic_record(original_type));
  6017. bool show_error = true;
  6018. Array<Operand> operands = {};
  6019. defer (array_free(&operands));
  6020. bool named_fields = false;
  6021. {
  6022. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6023. auto prev_type_path = c->type_path;
  6024. c->type_path = new_checker_type_path();
  6025. defer ({
  6026. destroy_checker_type_path(c->type_path);
  6027. c->type_path = prev_type_path;
  6028. });
  6029. if (is_call_expr_field_value(ce)) {
  6030. named_fields = true;
  6031. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6032. for_array(i, ce->args) {
  6033. Ast *arg = ce->args[i];
  6034. ast_node(fv, FieldValue, arg);
  6035. if (fv->field->kind == Ast_Ident) {
  6036. String name = fv->field->Ident.token.string;
  6037. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6038. if (index >= 0) {
  6039. TypeTuple *params = get_record_polymorphic_params(original_type);
  6040. Entity *e = params->variables[index];
  6041. if (e->kind == Entity_Constant) {
  6042. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6043. continue;
  6044. }
  6045. }
  6046. }
  6047. check_expr_or_type(c, &operands[i], fv->value);
  6048. }
  6049. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6050. if (vari_expand) {
  6051. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6052. }
  6053. } else {
  6054. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6055. Entity **lhs = nullptr;
  6056. isize lhs_count = -1;
  6057. TypeTuple *params = get_record_polymorphic_params(original_type);
  6058. if (params != nullptr) {
  6059. lhs = params->variables.data;
  6060. lhs_count = params->variables.count;
  6061. }
  6062. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6063. }
  6064. }
  6065. CallArgumentError err = CallArgumentError_None;
  6066. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6067. isize param_count = tuple->variables.count;
  6068. isize minimum_param_count = param_count;
  6069. for (; minimum_param_count > 0; minimum_param_count--) {
  6070. Entity *e = tuple->variables[minimum_param_count-1];
  6071. if (e->kind != Entity_Constant) {
  6072. break;
  6073. }
  6074. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6075. break;
  6076. }
  6077. }
  6078. Array<Operand> ordered_operands = operands;
  6079. if (!named_fields) {
  6080. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6081. array_copy(&ordered_operands, operands, 0);
  6082. } else {
  6083. TEMPORARY_ALLOCATOR_GUARD();
  6084. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6085. // LEAK(bill)
  6086. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6087. for_array(i, ce->args) {
  6088. Ast *arg = ce->args[i];
  6089. ast_node(fv, FieldValue, arg);
  6090. if (fv->field->kind != Ast_Ident) {
  6091. if (show_error) {
  6092. gbString expr_str = expr_to_string(fv->field);
  6093. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6094. gb_string_free(expr_str);
  6095. }
  6096. err = CallArgumentError_InvalidFieldValue;
  6097. continue;
  6098. }
  6099. String name = fv->field->Ident.token.string;
  6100. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6101. if (index < 0) {
  6102. if (show_error) {
  6103. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6104. }
  6105. err = CallArgumentError_ParameterNotFound;
  6106. continue;
  6107. }
  6108. if (visited[index]) {
  6109. if (show_error) {
  6110. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6111. }
  6112. err = CallArgumentError_DuplicateParameter;
  6113. continue;
  6114. }
  6115. visited[index] = true;
  6116. ordered_operands[index] = operands[i];
  6117. }
  6118. for (isize i = 0; i < param_count; i++) {
  6119. if (!visited[i]) {
  6120. Entity *e = tuple->variables[i];
  6121. if (is_blank_ident(e->token)) {
  6122. continue;
  6123. }
  6124. if (show_error) {
  6125. if (e->kind == Entity_TypeName) {
  6126. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6127. LIT(e->token.string));
  6128. } else {
  6129. gbString str = type_to_string(e->type);
  6130. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6131. LIT(e->token.string), str);
  6132. gb_string_free(str);
  6133. }
  6134. }
  6135. err = CallArgumentError_ParameterMissing;
  6136. }
  6137. }
  6138. }
  6139. if (err != 0) {
  6140. operand->mode = Addressing_Invalid;
  6141. return err;
  6142. }
  6143. while (ordered_operands.count > 0) {
  6144. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6145. break;
  6146. }
  6147. array_pop(&ordered_operands);
  6148. }
  6149. if (minimum_param_count != param_count) {
  6150. if (param_count < ordered_operands.count) {
  6151. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6152. err = CallArgumentError_TooManyArguments;
  6153. } else if (minimum_param_count > ordered_operands.count) {
  6154. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6155. err = CallArgumentError_TooFewArguments;
  6156. }
  6157. } else {
  6158. if (param_count < ordered_operands.count) {
  6159. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6160. err = CallArgumentError_TooManyArguments;
  6161. } else if (param_count > ordered_operands.count) {
  6162. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6163. err = CallArgumentError_TooFewArguments;
  6164. }
  6165. }
  6166. if (err != 0) {
  6167. return err;
  6168. }
  6169. if (minimum_param_count != param_count) {
  6170. array_resize(&ordered_operands, param_count);
  6171. isize missing_count = 0;
  6172. // NOTE(bill): Replace missing operands with the default values (if possible)
  6173. for_array(i, ordered_operands) {
  6174. Operand *o = &ordered_operands[i];
  6175. if (o->expr == nullptr) {
  6176. Entity *e = tuple->variables[i];
  6177. if (e->kind == Entity_Constant) {
  6178. missing_count += 1;
  6179. o->mode = Addressing_Constant;
  6180. o->type = default_type(e->type);
  6181. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6182. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6183. o->value = e->Constant.param_value.value;
  6184. }
  6185. } else if (e->kind == Entity_TypeName) {
  6186. missing_count += 1;
  6187. o->mode = Addressing_Type;
  6188. o->type = e->type;
  6189. o->expr = e->identifier;
  6190. }
  6191. }
  6192. }
  6193. }
  6194. isize oo_count = gb_min(param_count, ordered_operands.count);
  6195. i64 score = 0;
  6196. for (isize i = 0; i < oo_count; i++) {
  6197. Entity *e = tuple->variables[i];
  6198. Operand *o = &ordered_operands[i];
  6199. if (o->mode == Addressing_Invalid) {
  6200. continue;
  6201. }
  6202. if (e->kind == Entity_TypeName) {
  6203. if (o->mode != Addressing_Type) {
  6204. if (show_error) {
  6205. gbString expr = expr_to_string(o->expr);
  6206. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6207. gb_string_free(expr);
  6208. }
  6209. err = CallArgumentError_WrongTypes;
  6210. }
  6211. if (are_types_identical(e->type, o->type)) {
  6212. score += assign_score_function(1);
  6213. } else {
  6214. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6215. }
  6216. } else {
  6217. i64 s = 0;
  6218. if (o->type->kind == Type_Generic) {
  6219. // Polymorphic name!
  6220. score += assign_score_function(1);
  6221. continue;
  6222. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6223. if (show_error) {
  6224. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6225. }
  6226. err = CallArgumentError_WrongTypes;
  6227. }
  6228. o->type = e->type;
  6229. if (o->mode != Addressing_Constant) {
  6230. bool valid = false;
  6231. if (is_type_proc(o->type)) {
  6232. Entity *proc_entity = entity_from_expr(o->expr);
  6233. valid = proc_entity != nullptr;
  6234. }
  6235. if (!valid) {
  6236. if (show_error) {
  6237. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6238. }
  6239. err = CallArgumentError_NoneConstantParameter;
  6240. }
  6241. }
  6242. score += s;
  6243. }
  6244. // NOTE(bill): Add type info the parameters
  6245. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6246. // add_type_info_type(c, o->type);
  6247. }
  6248. if (show_error && err) {
  6249. return err;
  6250. }
  6251. {
  6252. bool failure = false;
  6253. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  6254. if (found_entity) {
  6255. operand->mode = Addressing_Type;
  6256. operand->type = found_entity->type;
  6257. return err;
  6258. }
  6259. CheckerContext ctx = *c;
  6260. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6261. ctx.scope = polymorphic_record_parent_scope(original_type);
  6262. GB_ASSERT(ctx.scope != nullptr);
  6263. Type *bt = base_type(original_type);
  6264. String generated_name = make_string_c(expr_to_string(call));
  6265. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6266. if (bt->kind == Type_Struct) {
  6267. Ast *node = clone_ast(bt->Struct.node);
  6268. Type *struct_type = alloc_type_struct();
  6269. struct_type->Struct.node = node;
  6270. struct_type->Struct.polymorphic_parent = original_type;
  6271. set_base_type(named_type, struct_type);
  6272. check_open_scope(&ctx, node);
  6273. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6274. check_close_scope(&ctx);
  6275. } else if (bt->kind == Type_Union) {
  6276. Ast *node = clone_ast(bt->Union.node);
  6277. Type *union_type = alloc_type_union();
  6278. union_type->Union.node = node;
  6279. union_type->Union.polymorphic_parent = original_type;
  6280. set_base_type(named_type, union_type);
  6281. check_open_scope(&ctx, node);
  6282. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6283. check_close_scope(&ctx);
  6284. } else {
  6285. GB_PANIC("Unsupported parametric polymorphic record type");
  6286. }
  6287. bt = base_type(named_type);
  6288. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6289. GB_ASSERT(original_type->kind == Type_Named);
  6290. Entity *e = original_type->Named.type_name;
  6291. GB_ASSERT(e->kind == Entity_TypeName);
  6292. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6293. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6294. Type *params = nullptr;
  6295. switch (bt->kind) {
  6296. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6297. case Type_Union: params = bt->Union.polymorphic_params; break;
  6298. }
  6299. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6300. Entity *v = params->Tuple.variables[i];
  6301. String name = v->token.string;
  6302. if (i > 0) {
  6303. s = gb_string_append_fmt(s, ", ");
  6304. }
  6305. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6306. if (v->kind == Entity_TypeName) {
  6307. if (v->type->kind != Type_Generic) {
  6308. s = gb_string_append_fmt(s, "=");
  6309. s = write_type_to_string(s, v->type, false);
  6310. }
  6311. } else if (v->kind == Entity_Constant) {
  6312. s = gb_string_append_fmt(s, "=");
  6313. s = write_exact_value_to_string(s, v->Constant.value);
  6314. }
  6315. }
  6316. s = gb_string_append_fmt(s, ")");
  6317. String new_name = make_string_c(s);
  6318. named_type->Named.name = new_name;
  6319. if (named_type->Named.type_name) {
  6320. named_type->Named.type_name->token.string = new_name;
  6321. }
  6322. }
  6323. operand->mode = Addressing_Type;
  6324. operand->type = named_type;
  6325. }
  6326. return err;
  6327. }
  6328. // returns true on success
  6329. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6330. bool success = true;
  6331. if (args.count > 0) {
  6332. if (allow_mixed) {
  6333. bool was_named = false;
  6334. for (Ast *arg : args) {
  6335. if (was_named && arg->kind != Ast_FieldValue) {
  6336. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6337. success = false;
  6338. break;
  6339. }
  6340. was_named = was_named || arg->kind == Ast_FieldValue;
  6341. }
  6342. } else {
  6343. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6344. for (Ast *arg : args) {
  6345. bool mix = false;
  6346. if (first_is_field_value) {
  6347. mix = arg->kind != Ast_FieldValue;
  6348. } else {
  6349. mix = arg->kind == Ast_FieldValue;
  6350. }
  6351. if (mix) {
  6352. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6353. success = false;
  6354. }
  6355. }
  6356. }
  6357. }
  6358. return success;
  6359. }
  6360. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6361. operand->mode = Addressing_Invalid; \
  6362. operand->expr = call; \
  6363. return Expr_Stmt; \
  6364. }
  6365. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6366. if (proc != nullptr &&
  6367. proc->kind == Ast_BasicDirective) {
  6368. ast_node(bd, BasicDirective, proc);
  6369. String name = bd->name.string;
  6370. if (
  6371. name == "location" ||
  6372. name == "assert" ||
  6373. name == "panic" ||
  6374. name == "defined" ||
  6375. name == "config" ||
  6376. name == "load" ||
  6377. name == "load_directory" ||
  6378. name == "load_hash"
  6379. ) {
  6380. operand->mode = Addressing_Builtin;
  6381. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6382. operand->expr = proc;
  6383. operand->type = t_invalid;
  6384. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6385. } else {
  6386. error(proc, "Unknown directive: #%.*s", LIT(name));
  6387. operand->expr = proc;
  6388. operand->type = t_invalid;
  6389. operand->mode = Addressing_Invalid;
  6390. return Expr_Expr;
  6391. }
  6392. if (inlining != ProcInlining_none) {
  6393. error(call, "Inlining operators are not allowed on built-in procedures");
  6394. }
  6395. } else {
  6396. if (proc != nullptr) {
  6397. check_expr_or_type(c, operand, proc);
  6398. } else {
  6399. GB_ASSERT(operand->expr != nullptr);
  6400. }
  6401. }
  6402. if (operand->mode == Addressing_Invalid) {
  6403. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6404. for (Ast *arg : args) {
  6405. if (arg->kind == Ast_FieldValue) {
  6406. arg = arg->FieldValue.value;
  6407. }
  6408. check_expr_base(c, operand, arg, nullptr);
  6409. }
  6410. operand->mode = Addressing_Invalid;
  6411. operand->expr = call;
  6412. return Expr_Stmt;
  6413. }
  6414. if (operand->mode == Addressing_Type) {
  6415. Type *t = operand->type;
  6416. if (is_type_polymorphic_record(t)) {
  6417. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6418. if (!is_type_named(t)) {
  6419. gbString s = expr_to_string(operand->expr);
  6420. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6421. gb_string_free(s);
  6422. operand->mode = Addressing_Invalid;
  6423. operand->type = t_invalid;;
  6424. return Expr_Expr;
  6425. }
  6426. auto err = check_polymorphic_record_type(c, operand, call);
  6427. if (err == 0) {
  6428. Ast *ident = operand->expr;
  6429. while (ident->kind == Ast_SelectorExpr) {
  6430. Ast *s = ident->SelectorExpr.selector;
  6431. ident = s;
  6432. }
  6433. Type *ot = operand->type;
  6434. GB_ASSERT(ot->kind == Type_Named);
  6435. Entity *e = ot->Named.type_name;
  6436. add_entity_use(c, ident, e);
  6437. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6438. } else {
  6439. operand->mode = Addressing_Invalid;
  6440. operand->type = t_invalid;
  6441. }
  6442. } else {
  6443. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6444. operand->mode = Addressing_Invalid;
  6445. isize arg_count = args.count;
  6446. switch (arg_count) {
  6447. case 0:
  6448. {
  6449. gbString str = type_to_string(t);
  6450. error(call, "Missing argument in conversion to '%s'", str);
  6451. gb_string_free(str);
  6452. } break;
  6453. default:
  6454. {
  6455. gbString str = type_to_string(t);
  6456. error(call, "Too many arguments in conversion to '%s'", str);
  6457. gb_string_free(str);
  6458. } break;
  6459. case 1: {
  6460. Ast *arg = args[0];
  6461. if (arg->kind == Ast_FieldValue) {
  6462. error(call, "'field = value' cannot be used in a type conversion");
  6463. arg = arg->FieldValue.value;
  6464. // NOTE(bill): Carry on the cast regardless
  6465. }
  6466. check_expr_with_type_hint(c, operand, arg, t);
  6467. if (operand->mode != Addressing_Invalid) {
  6468. if (is_type_polymorphic(t)) {
  6469. error(call, "A polymorphic type cannot be used in a type conversion");
  6470. } else {
  6471. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6472. // as it assumes it is determining the type
  6473. check_cast(c, operand, t);
  6474. }
  6475. }
  6476. operand->type = t;
  6477. operand->expr = call;
  6478. if (operand->mode != Addressing_Invalid) {
  6479. update_untyped_expr_type(c, arg, t, false);
  6480. }
  6481. break;
  6482. }
  6483. }
  6484. }
  6485. return Expr_Expr;
  6486. }
  6487. if (operand->mode == Addressing_Builtin) {
  6488. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6489. i32 id = operand->builtin_id;
  6490. Entity *e = entity_of_node(operand->expr);
  6491. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6492. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6493. }
  6494. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6495. operand->mode = Addressing_Invalid;
  6496. operand->type = t_invalid;
  6497. }
  6498. operand->expr = call;
  6499. return builtin_procs[id].kind;
  6500. }
  6501. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6502. Entity *initial_entity = entity_of_node(operand->expr);
  6503. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6504. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6505. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6506. if (c->decl) {
  6507. c->decl->defer_used += 1;
  6508. }
  6509. }
  6510. add_entity_use(c, operand->expr, initial_entity);
  6511. if (initial_entity->Procedure.entry_point_only) {
  6512. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6513. // Okay
  6514. } else {
  6515. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6516. }
  6517. }
  6518. }
  6519. if (operand->mode != Addressing_ProcGroup) {
  6520. Type *proc_type = base_type(operand->type);
  6521. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6522. bool valid_mode = is_operand_value(*operand);
  6523. if (!valid_type || !valid_mode) {
  6524. Ast *e = operand->expr;
  6525. gbString str = expr_to_string(e);
  6526. gbString type_str = type_to_string(operand->type);
  6527. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6528. gb_string_free(type_str);
  6529. gb_string_free(str);
  6530. operand->mode = Addressing_Invalid;
  6531. operand->expr = call;
  6532. return Expr_Stmt;
  6533. }
  6534. }
  6535. CallArgumentData data = check_call_arguments(c, operand, call);
  6536. Type *result_type = data.result_type;
  6537. gb_zero_item(operand);
  6538. operand->expr = call;
  6539. if (result_type == t_invalid) {
  6540. operand->mode = Addressing_Invalid;
  6541. operand->type = t_invalid;
  6542. return Expr_Stmt;
  6543. }
  6544. Type *pt = base_type(operand->type);
  6545. if (pt == nullptr) {
  6546. pt = t_invalid;
  6547. }
  6548. if (pt == t_invalid) {
  6549. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6550. pt = type_of_expr(operand->expr->CallExpr.proc);
  6551. }
  6552. if (pt == t_invalid && data.gen_entity) {
  6553. pt = data.gen_entity->type;
  6554. }
  6555. }
  6556. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6557. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6558. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6559. }
  6560. }
  6561. if (result_type == nullptr) {
  6562. operand->mode = Addressing_NoValue;
  6563. } else {
  6564. GB_ASSERT(is_type_tuple(result_type));
  6565. isize count = result_type->Tuple.variables.count;
  6566. switch (count) {
  6567. case 0:
  6568. operand->mode = Addressing_NoValue;
  6569. break;
  6570. case 1:
  6571. operand->mode = Addressing_Value;
  6572. operand->type = result_type->Tuple.variables[0]->type;
  6573. break;
  6574. default:
  6575. operand->mode = Addressing_Value;
  6576. operand->type = result_type;
  6577. break;
  6578. }
  6579. }
  6580. switch (inlining) {
  6581. case ProcInlining_inline:
  6582. if (proc != nullptr) {
  6583. Entity *e = entity_from_expr(proc);
  6584. if (e != nullptr && e->kind == Entity_Procedure) {
  6585. DeclInfo *decl = e->decl_info;
  6586. if (decl->proc_lit) {
  6587. ast_node(pl, ProcLit, decl->proc_lit);
  6588. if (pl->inlining == ProcInlining_no_inline) {
  6589. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6590. }
  6591. }
  6592. }
  6593. }
  6594. break;
  6595. case ProcInlining_no_inline:
  6596. break;
  6597. }
  6598. operand->expr = call;
  6599. {
  6600. Type *type = nullptr;
  6601. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6602. type = type_of_expr(operand->expr->CallExpr.proc);
  6603. }
  6604. if (type == nullptr) {
  6605. type = pt;
  6606. }
  6607. type = base_type(type);
  6608. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6609. operand->mode = Addressing_OptionalOk;
  6610. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6611. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6612. operand->expr->CallExpr.optional_ok_one = true;
  6613. }
  6614. }
  6615. }
  6616. return Expr_Expr;
  6617. }
  6618. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6619. check_expr_base(c, o, e, t);
  6620. check_not_tuple(c, o);
  6621. char const *err_str = nullptr;
  6622. switch (o->mode) {
  6623. case Addressing_NoValue:
  6624. err_str = "used as a value";
  6625. break;
  6626. case Addressing_Type:
  6627. if (t == nullptr || !is_type_typeid(t)) {
  6628. err_str = "is not an expression but a type, in this context it is ambiguous";
  6629. }
  6630. break;
  6631. case Addressing_Builtin:
  6632. err_str = "must be called";
  6633. break;
  6634. }
  6635. if (err_str != nullptr) {
  6636. gbString str = expr_to_string(e);
  6637. error(e, "'%s' %s", str, err_str);
  6638. gb_string_free(str);
  6639. o->mode = Addressing_Invalid;
  6640. }
  6641. }
  6642. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6643. switch (t->kind) {
  6644. case Type_Basic:
  6645. if (t->Basic.kind == Basic_string) {
  6646. if (o->mode == Addressing_Constant) {
  6647. *max_count = o->value.value_string.len;
  6648. }
  6649. if (o->mode != Addressing_Constant) {
  6650. o->mode = Addressing_Value;
  6651. }
  6652. o->type = t_u8;
  6653. return true;
  6654. } else if (t->Basic.kind == Basic_UntypedString) {
  6655. if (o->mode == Addressing_Constant) {
  6656. *max_count = o->value.value_string.len;
  6657. o->type = t_u8;
  6658. return true;
  6659. }
  6660. return false;
  6661. }
  6662. break;
  6663. case Type_MultiPointer:
  6664. o->type = t->MultiPointer.elem;
  6665. if (o->mode != Addressing_Constant) {
  6666. o->mode = Addressing_Variable;
  6667. }
  6668. return true;
  6669. case Type_Array:
  6670. *max_count = t->Array.count;
  6671. if (indirection) {
  6672. o->mode = Addressing_Variable;
  6673. } else if (o->mode != Addressing_Variable &&
  6674. o->mode != Addressing_Constant) {
  6675. o->mode = Addressing_Value;
  6676. }
  6677. o->type = t->Array.elem;
  6678. return true;
  6679. case Type_EnumeratedArray:
  6680. *max_count = t->EnumeratedArray.count;
  6681. if (indirection) {
  6682. o->mode = Addressing_Variable;
  6683. } else if (o->mode != Addressing_Variable &&
  6684. o->mode != Addressing_Constant) {
  6685. o->mode = Addressing_Value;
  6686. }
  6687. o->type = t->EnumeratedArray.elem;
  6688. return true;
  6689. case Type_Matrix:
  6690. *max_count = t->Matrix.column_count;
  6691. if (indirection) {
  6692. o->mode = Addressing_Variable;
  6693. } else if (o->mode != Addressing_Variable) {
  6694. o->mode = Addressing_Value;
  6695. }
  6696. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6697. return true;
  6698. case Type_Slice:
  6699. o->type = t->Slice.elem;
  6700. if (o->mode != Addressing_Constant) {
  6701. o->mode = Addressing_Variable;
  6702. }
  6703. return true;
  6704. case Type_RelativeMultiPointer:
  6705. {
  6706. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6707. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6708. o->type = pointer_type->MultiPointer.elem;
  6709. if (o->mode != Addressing_Constant) {
  6710. o->mode = Addressing_Variable;
  6711. }
  6712. }
  6713. return true;
  6714. case Type_DynamicArray:
  6715. o->type = t->DynamicArray.elem;
  6716. if (o->mode != Addressing_Constant) {
  6717. o->mode = Addressing_Variable;
  6718. }
  6719. return true;
  6720. case Type_Struct:
  6721. if (t->Struct.soa_kind != StructSoa_None) {
  6722. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6723. *max_count = t->Struct.soa_count;
  6724. }
  6725. o->type = t->Struct.soa_elem;
  6726. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  6727. o->mode = Addressing_SoaVariable;
  6728. } else {
  6729. o->mode = Addressing_Value;
  6730. }
  6731. return true;
  6732. }
  6733. return false;
  6734. }
  6735. if (is_type_pointer(original_type) && indirection) {
  6736. Type *ptr = base_type(original_type);
  6737. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6738. o->type = ptr->Pointer.elem;
  6739. o->mode = Addressing_Value;
  6740. return true;
  6741. }
  6742. }
  6743. return false;
  6744. }
  6745. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6746. if (is_type_untyped_uninit(x)) {
  6747. return true;
  6748. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6749. return true;
  6750. } else if (is_type_untyped_uninit(y)) {
  6751. return true;
  6752. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6753. return true;
  6754. }
  6755. return are_types_identical(x, y);
  6756. }
  6757. 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) {
  6758. if (!is_ast_range(node)) {
  6759. return false;
  6760. }
  6761. ast_node(ie, BinaryExpr, node);
  6762. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6763. if (x->mode == Addressing_Invalid) {
  6764. return false;
  6765. }
  6766. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6767. if (y->mode == Addressing_Invalid) {
  6768. return false;
  6769. }
  6770. convert_to_typed(c, x, y->type);
  6771. if (x->mode == Addressing_Invalid) {
  6772. return false;
  6773. }
  6774. convert_to_typed(c, y, x->type);
  6775. if (y->mode == Addressing_Invalid) {
  6776. return false;
  6777. }
  6778. convert_to_typed(c, x, default_type(y->type));
  6779. if (x->mode == Addressing_Invalid) {
  6780. return false;
  6781. }
  6782. convert_to_typed(c, y, default_type(x->type));
  6783. if (y->mode == Addressing_Invalid) {
  6784. return false;
  6785. }
  6786. if (!are_types_identical(x->type, y->type)) {
  6787. if (x->type != t_invalid &&
  6788. y->type != t_invalid) {
  6789. gbString xt = type_to_string(x->type);
  6790. gbString yt = type_to_string(y->type);
  6791. gbString expr_str = expr_to_string(x->expr);
  6792. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6793. gb_string_free(expr_str);
  6794. gb_string_free(yt);
  6795. gb_string_free(xt);
  6796. }
  6797. return false;
  6798. }
  6799. Type *type = x->type;
  6800. if (is_for_loop) {
  6801. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6802. error(ie->op, "Only numerical types are allowed within interval expressions");
  6803. return false;
  6804. }
  6805. } else {
  6806. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6807. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6808. return false;
  6809. }
  6810. }
  6811. if (x->mode == Addressing_Constant &&
  6812. y->mode == Addressing_Constant) {
  6813. ExactValue a = x->value;
  6814. ExactValue b = y->value;
  6815. GB_ASSERT(are_types_identical(x->type, y->type));
  6816. TokenKind op = Token_Lt;
  6817. switch (ie->op.kind) {
  6818. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6819. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6820. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6821. default: error(ie->op, "Invalid range operator"); break;
  6822. }
  6823. bool ok = compare_exact_values(op, a, b);
  6824. if (!ok) {
  6825. // TODO(bill): Better error message
  6826. error(ie->op, "Invalid interval range");
  6827. return false;
  6828. }
  6829. ExactValue inline_for_depth = exact_value_sub(b, a);
  6830. if (ie->op.kind != Token_RangeHalf) {
  6831. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6832. }
  6833. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6834. } else if (inline_for_depth_ != nullptr) {
  6835. error(ie->op, "Interval expressions must be constant");
  6836. return false;
  6837. }
  6838. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6839. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6840. return true;
  6841. }
  6842. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6843. if (is_operand_nil(*o)) {
  6844. return true;
  6845. }
  6846. Ast *expr = unparen_expr(o->expr);
  6847. if (expr != nullptr) {
  6848. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6849. if (e != nullptr && e->kind == Entity_Procedure) {
  6850. return true;
  6851. }
  6852. if (expr->kind == Ast_ProcLit) {
  6853. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6854. return true;
  6855. }
  6856. }
  6857. return o->mode == Addressing_Constant;
  6858. }
  6859. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6860. if (is_type_enum(th)) {
  6861. Type *enum_type = base_type(th);
  6862. GB_ASSERT(enum_type->kind == Type_Enum);
  6863. String name = ise->selector->Ident.token.string;
  6864. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6865. if (e == nullptr) {
  6866. return false;
  6867. }
  6868. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6869. GB_ASSERT(e->kind == Entity_Constant);
  6870. o->value = e->Constant.value;
  6871. o->mode = Addressing_Constant;
  6872. o->type = e->type;
  6873. return true;
  6874. }
  6875. if (is_type_union(th)) {
  6876. TEMPORARY_ALLOCATOR_GUARD();
  6877. Type *union_type = base_type(th);
  6878. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6879. for (Type *vt : union_type->Union.variants) {
  6880. Operand x = {};
  6881. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6882. array_add(&operands, x);
  6883. }
  6884. }
  6885. if (operands.count == 1) {
  6886. *o = operands[0];
  6887. return true;
  6888. }
  6889. }
  6890. return false;
  6891. }
  6892. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6893. ast_node(ise, ImplicitSelectorExpr, node);
  6894. o->type = t_invalid;
  6895. o->expr = node;
  6896. o->mode = Addressing_Invalid;
  6897. Type *th = type_hint;
  6898. if (th == nullptr) {
  6899. gbString str = expr_to_string(node);
  6900. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6901. gb_string_free(str);
  6902. return Expr_Expr;
  6903. }
  6904. o->type = th;
  6905. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6906. if (!ok) {
  6907. String name = ise->selector->Ident.token.string;
  6908. if (is_type_enum(th)) {
  6909. ERROR_BLOCK();
  6910. Type *bt = base_type(th);
  6911. GB_ASSERT(bt->kind == Type_Enum);
  6912. gbString typ = type_to_string(th);
  6913. defer (gb_string_free(typ));
  6914. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6915. check_did_you_mean_type(name, bt->Enum.fields);
  6916. } else {
  6917. gbString typ = type_to_string(th);
  6918. gbString str = expr_to_string(node);
  6919. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6920. gb_string_free(str);
  6921. gb_string_free(typ);
  6922. }
  6923. }
  6924. o->expr = node;
  6925. return Expr_Expr;
  6926. }
  6927. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  6928. switch (x->mode) {
  6929. case Addressing_MapIndex:
  6930. case Addressing_OptionalOk:
  6931. case Addressing_OptionalOkPtr:
  6932. if (val_type_) *val_type_ = x->type;
  6933. break;
  6934. default:
  6935. if (ok_type_) *ok_type_ = x->type;
  6936. return;
  6937. }
  6938. Ast *expr = unparen_expr(x->expr);
  6939. if (expr->kind == Ast_CallExpr) {
  6940. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6941. if (is_type_proc(pt)) {
  6942. Type *tuple = pt->Proc.results;
  6943. if (pt->Proc.result_count >= 2) {
  6944. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6945. }
  6946. if (change_operand) {
  6947. expr->CallExpr.optional_ok_one = false;
  6948. x->type = tuple;
  6949. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6950. }
  6951. return;
  6952. }
  6953. }
  6954. Type *tuple = make_optional_ok_type(x->type);
  6955. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6956. if (change_operand) {
  6957. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6958. x->type = tuple;
  6959. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6960. }
  6961. }
  6962. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6963. ast_node(ie, MatrixIndexExpr, node);
  6964. check_expr(c, o, ie->expr);
  6965. node->viral_state_flags |= ie->expr->viral_state_flags;
  6966. if (o->mode == Addressing_Invalid) {
  6967. o->expr = node;
  6968. return;
  6969. }
  6970. Type *t = base_type(type_deref(o->type));
  6971. bool is_ptr = is_type_pointer(o->type);
  6972. bool is_const = o->mode == Addressing_Constant;
  6973. if (t->kind != Type_Matrix) {
  6974. gbString str = expr_to_string(o->expr);
  6975. gbString type_str = type_to_string(o->type);
  6976. defer (gb_string_free(str));
  6977. defer (gb_string_free(type_str));
  6978. if (is_const) {
  6979. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6980. } else {
  6981. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6982. }
  6983. o->mode = Addressing_Invalid;
  6984. o->expr = node;
  6985. return;
  6986. }
  6987. o->type = t->Matrix.elem;
  6988. if (is_ptr) {
  6989. o->mode = Addressing_Variable;
  6990. } else if (o->mode != Addressing_Variable) {
  6991. o->mode = Addressing_Value;
  6992. }
  6993. if (ie->row_index == nullptr) {
  6994. gbString str = expr_to_string(o->expr);
  6995. error(o->expr, "Missing row index for '%s'", str);
  6996. gb_string_free(str);
  6997. o->mode = Addressing_Invalid;
  6998. o->expr = node;
  6999. return;
  7000. }
  7001. if (ie->column_index == nullptr) {
  7002. gbString str = expr_to_string(o->expr);
  7003. error(o->expr, "Missing column index for '%s'", str);
  7004. gb_string_free(str);
  7005. o->mode = Addressing_Invalid;
  7006. o->expr = node;
  7007. return;
  7008. }
  7009. i64 row_count = t->Matrix.row_count;
  7010. i64 column_count = t->Matrix.column_count;
  7011. i64 row_index = 0;
  7012. i64 column_index = 0;
  7013. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7014. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7015. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7016. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7017. }
  7018. gb_unused(row_ok);
  7019. gb_unused(column_ok);
  7020. }
  7021. struct TypeAndToken {
  7022. Type *type;
  7023. Token token;
  7024. };
  7025. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7026. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7027. if (operand.mode != Addressing_Constant) {
  7028. return;
  7029. }
  7030. if (operand.value.kind == ExactValue_Invalid) {
  7031. return;
  7032. }
  7033. uintptr key = hash_exact_value(operand.value);
  7034. TypeAndToken *found = map_get(seen, key);
  7035. if (found != nullptr) {
  7036. TEMPORARY_ALLOCATOR_GUARD();
  7037. isize count = multi_map_count(seen, key);
  7038. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7039. multi_map_get_all(seen, key, taps);
  7040. for (isize i = 0; i < count; i++) {
  7041. TypeAndToken tap = taps[i];
  7042. Operand to = {};
  7043. to.mode = Addressing_Value;
  7044. to.type = tap.type;
  7045. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7046. continue;
  7047. }
  7048. TokenPos pos = tap.token.pos;
  7049. if (use_expr) {
  7050. gbString expr_str = expr_to_string(operand.expr);
  7051. error(operand.expr,
  7052. "Duplicate case '%s'\n"
  7053. "\tprevious case at %s",
  7054. expr_str,
  7055. token_pos_to_string(pos));
  7056. gb_string_free(expr_str);
  7057. } else {
  7058. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7059. }
  7060. return;
  7061. }
  7062. }
  7063. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7064. multi_map_insert(seen, key, tap);
  7065. }
  7066. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7067. if (is_type_enum(x.type)) {
  7068. // TODO(bill): Fix this logic so it's fast!!!
  7069. i64 v0 = exact_value_to_i64(lhs.value);
  7070. i64 v1 = exact_value_to_i64(rhs.value);
  7071. Operand v = {};
  7072. v.mode = Addressing_Constant;
  7073. v.type = x.type;
  7074. v.expr = x.expr;
  7075. Type *bt = base_type(x.type);
  7076. GB_ASSERT(bt->kind == Type_Enum);
  7077. for (i64 vi = v0; vi <= v1; vi++) {
  7078. if (upper_op != Token_LtEq && vi == v1) {
  7079. break;
  7080. }
  7081. v.value = exact_value_i64(vi);
  7082. add_constant_switch_case(ctx, seen, v);
  7083. }
  7084. } else {
  7085. add_constant_switch_case(ctx, seen, lhs);
  7086. if (upper_op == Token_LtEq) {
  7087. add_constant_switch_case(ctx, seen, rhs);
  7088. }
  7089. }
  7090. }
  7091. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7092. add_constant_switch_case(ctx, seen, x);
  7093. }
  7094. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7095. ast_node(bd, BasicDirective, node);
  7096. ExprKind kind = Expr_Expr;
  7097. o->mode = Addressing_Constant;
  7098. String name = bd->name.string;
  7099. if (name == "file") {
  7100. o->type = t_untyped_string;
  7101. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  7102. } else if (name == "line") {
  7103. o->type = t_untyped_integer;
  7104. o->value = exact_value_i64(bd->token.pos.line);
  7105. } else if (name == "procedure") {
  7106. if (c->curr_proc_decl == nullptr) {
  7107. error(node, "#procedure may only be used within procedures");
  7108. o->type = t_untyped_string;
  7109. o->value = exact_value_string(str_lit(""));
  7110. } else {
  7111. o->type = t_untyped_string;
  7112. o->value = exact_value_string(c->proc_name);
  7113. }
  7114. } else if (name == "caller_location") {
  7115. init_core_source_code_location(c->checker);
  7116. error(node, "#caller_location may only be used as a default argument parameter");
  7117. o->type = t_source_code_location;
  7118. o->mode = Addressing_Value;
  7119. } else {
  7120. if (name == "location") {
  7121. init_core_source_code_location(c->checker);
  7122. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7123. o->type = t_source_code_location;
  7124. o->mode = Addressing_Value;
  7125. } else if (
  7126. name == "assert" ||
  7127. name == "defined" ||
  7128. name == "config" ||
  7129. name == "load" ||
  7130. name == "load_hash" ||
  7131. name == "load_directory" ||
  7132. name == "load_or"
  7133. ) {
  7134. error(node, "'#%.*s' must be used as a call", LIT(name));
  7135. o->type = t_invalid;
  7136. o->mode = Addressing_Invalid;
  7137. } else {
  7138. error(node, "Unknown directive: #%.*s", LIT(name));
  7139. o->type = t_invalid;
  7140. o->mode = Addressing_Invalid;
  7141. }
  7142. }
  7143. return kind;
  7144. }
  7145. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7146. ExprKind kind = Expr_Expr;
  7147. Operand cond = {Addressing_Invalid};
  7148. ast_node(te, TernaryIfExpr, node);
  7149. check_expr(c, &cond, te->cond);
  7150. node->viral_state_flags |= te->cond->viral_state_flags;
  7151. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7152. error(te->cond, "Non-boolean condition in ternary if expression");
  7153. }
  7154. Operand x = {Addressing_Invalid};
  7155. Operand y = {Addressing_Invalid};
  7156. check_expr_or_type(c, &x, te->x, type_hint);
  7157. node->viral_state_flags |= te->x->viral_state_flags;
  7158. if (te->y != nullptr) {
  7159. Type *th = type_hint;
  7160. if (type_hint == nullptr && is_type_typed(x.type)) {
  7161. th = x.type;
  7162. }
  7163. check_expr_or_type(c, &y, te->y, th);
  7164. node->viral_state_flags |= te->y->viral_state_flags;
  7165. } else {
  7166. error(node, "A ternary expression must have an else clause");
  7167. return kind;
  7168. }
  7169. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7170. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7171. gbString type_string = expr_to_string(type_expr);
  7172. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7173. gb_string_free(type_string);
  7174. return kind;
  7175. }
  7176. if (x.type == nullptr || x.type == t_invalid ||
  7177. y.type == nullptr || y.type == t_invalid) {
  7178. return kind;
  7179. }
  7180. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7181. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7182. if (x.mode == Addressing_Invalid) {
  7183. return kind;
  7184. }
  7185. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7186. if (y.mode == Addressing_Invalid) {
  7187. x.mode = Addressing_Invalid;
  7188. return kind;
  7189. }
  7190. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7191. // x: union{f32} = f32(123) if cond else nil
  7192. if (type_hint && !is_type_any(type_hint)) {
  7193. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7194. check_cast(c, &x, type_hint);
  7195. check_cast(c, &y, type_hint);
  7196. }
  7197. }
  7198. if (!ternary_compare_types(x.type, y.type)) {
  7199. gbString its = type_to_string(x.type);
  7200. gbString ets = type_to_string(y.type);
  7201. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7202. gb_string_free(ets);
  7203. gb_string_free(its);
  7204. return kind;
  7205. }
  7206. o->type = x.type;
  7207. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7208. o->type = y.type;
  7209. }
  7210. o->mode = Addressing_Value;
  7211. o->expr = node;
  7212. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7213. if (check_cast_internal(c, &x, type_hint) &&
  7214. check_cast_internal(c, &y, type_hint)) {
  7215. convert_to_typed(c, o, type_hint);
  7216. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7217. o->type = type_hint;
  7218. }
  7219. }
  7220. return kind;
  7221. }
  7222. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7223. ExprKind kind = Expr_Expr;
  7224. Operand cond = {};
  7225. ast_node(te, TernaryWhenExpr, node);
  7226. check_expr(c, &cond, te->cond);
  7227. node->viral_state_flags |= te->cond->viral_state_flags;
  7228. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7229. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7230. return kind;
  7231. }
  7232. if (cond.value.value_bool) {
  7233. check_expr_or_type(c, o, te->x, type_hint);
  7234. node->viral_state_flags |= te->x->viral_state_flags;
  7235. } else {
  7236. if (te->y != nullptr) {
  7237. check_expr_or_type(c, o, te->y, type_hint);
  7238. node->viral_state_flags |= te->y->viral_state_flags;
  7239. } else {
  7240. error(node, "A ternary when expression must have an else clause");
  7241. return kind;
  7242. }
  7243. }
  7244. return kind;
  7245. }
  7246. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7247. ast_node(oe, OrElseExpr, node);
  7248. String name = oe->token.string;
  7249. Ast *arg = oe->x;
  7250. Ast *default_value = oe->y;
  7251. Operand x = {};
  7252. Operand y = {};
  7253. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7254. if (is_load_directive_call(arg)) {
  7255. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7256. // Allow for chaining of '#load(path) or_else #load(path)'
  7257. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7258. bool y_is_diverging = false;
  7259. check_expr_base(c, &y, default_value, x.type);
  7260. switch (y.mode) {
  7261. case Addressing_NoValue:
  7262. if (is_diverging_expr(y.expr)) {
  7263. // Allow
  7264. y.mode = Addressing_Value;
  7265. y_is_diverging = true;
  7266. } else {
  7267. error_operand_no_value(&y);
  7268. y.mode = Addressing_Invalid;
  7269. }
  7270. break;
  7271. case Addressing_Type:
  7272. error_operand_not_expression(&y);
  7273. y.mode = Addressing_Invalid;
  7274. break;
  7275. }
  7276. if (y.mode == Addressing_Invalid) {
  7277. o->mode = Addressing_Value;
  7278. o->type = t_invalid;
  7279. o->expr = node;
  7280. return Expr_Expr;
  7281. }
  7282. if (!y_is_diverging) {
  7283. check_assignment(c, &y, x.type, name);
  7284. if (y.mode != Addressing_Constant) {
  7285. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7286. }
  7287. }
  7288. }
  7289. if (res == LoadDirective_Success) {
  7290. *o = x;
  7291. } else {
  7292. *o = y;
  7293. }
  7294. o->expr = node;
  7295. return Expr_Expr;
  7296. }
  7297. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7298. if (x.mode == Addressing_Invalid) {
  7299. o->mode = Addressing_Value;
  7300. o->type = t_invalid;
  7301. o->expr = node;
  7302. return Expr_Expr;
  7303. }
  7304. bool y_is_diverging = false;
  7305. check_expr_base(c, &y, default_value, x.type);
  7306. switch (y.mode) {
  7307. case Addressing_NoValue:
  7308. if (is_diverging_expr(y.expr)) {
  7309. // Allow
  7310. y.mode = Addressing_Value;
  7311. y_is_diverging = true;
  7312. } else {
  7313. error_operand_no_value(&y);
  7314. y.mode = Addressing_Invalid;
  7315. }
  7316. break;
  7317. case Addressing_Type:
  7318. error_operand_not_expression(&y);
  7319. y.mode = Addressing_Invalid;
  7320. break;
  7321. }
  7322. if (y.mode == Addressing_Invalid) {
  7323. o->mode = Addressing_Value;
  7324. o->type = t_invalid;
  7325. o->expr = node;
  7326. return Expr_Expr;
  7327. }
  7328. Type *left_type = nullptr;
  7329. Type *right_type = nullptr;
  7330. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7331. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7332. if (left_type != nullptr) {
  7333. if (!y_is_diverging) {
  7334. check_assignment(c, &y, left_type, name);
  7335. }
  7336. } else {
  7337. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7338. }
  7339. if (left_type == nullptr) {
  7340. left_type = t_invalid;
  7341. }
  7342. o->mode = Addressing_Value;
  7343. o->type = left_type;
  7344. o->expr = node;
  7345. return Expr_Expr;
  7346. }
  7347. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7348. ast_node(re, OrReturnExpr, node);
  7349. String name = re->token.string;
  7350. Operand x = {};
  7351. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7352. if (x.mode == Addressing_Invalid) {
  7353. o->mode = Addressing_Value;
  7354. o->type = t_invalid;
  7355. o->expr = node;
  7356. return Expr_Expr;
  7357. }
  7358. Type *left_type = nullptr;
  7359. Type *right_type = nullptr;
  7360. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7361. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7362. if (right_type == nullptr) {
  7363. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7364. } else {
  7365. Type *proc_type = base_type(c->curr_proc_sig);
  7366. GB_ASSERT(proc_type->kind == Type_Proc);
  7367. Type *result_type = proc_type->Proc.results;
  7368. if (result_type == nullptr) {
  7369. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7370. } else {
  7371. GB_ASSERT(result_type->kind == Type_Tuple);
  7372. auto const &vars = result_type->Tuple.variables;
  7373. Type *end_type = vars[vars.count-1]->type;
  7374. if (vars.count > 1) {
  7375. if (!proc_type->Proc.has_named_results) {
  7376. 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));
  7377. }
  7378. }
  7379. Operand rhs = {};
  7380. rhs.type = right_type;
  7381. rhs.mode = Addressing_Value;
  7382. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7383. // NOTE(bill): allow implicit conversion between boolean types
  7384. // within 'or_return' to improve the experience using third-party code
  7385. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7386. // TODO(bill): better error message
  7387. gbString a = type_to_string(right_type);
  7388. gbString b = type_to_string(end_type);
  7389. gbString ret_type = type_to_string(result_type);
  7390. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7391. if (vars.count == 1) {
  7392. error_line("\tProcedure return value type: %s\n", ret_type);
  7393. } else {
  7394. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7395. }
  7396. gb_string_free(ret_type);
  7397. gb_string_free(b);
  7398. gb_string_free(a);
  7399. }
  7400. }
  7401. }
  7402. o->expr = node;
  7403. o->type = left_type;
  7404. if (left_type != nullptr) {
  7405. o->mode = Addressing_Value;
  7406. } else {
  7407. o->mode = Addressing_NoValue;
  7408. }
  7409. if (c->curr_proc_sig == nullptr) {
  7410. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7411. }
  7412. if (c->in_defer) {
  7413. error(node, "'or_return' cannot be used within a defer statement");
  7414. }
  7415. return Expr_Expr;
  7416. }
  7417. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7418. ast_node(be, OrBranchExpr, node);
  7419. String name = be->token.string;
  7420. Operand x = {};
  7421. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7422. if (x.mode == Addressing_Invalid) {
  7423. o->mode = Addressing_Value;
  7424. o->type = t_invalid;
  7425. o->expr = node;
  7426. return Expr_Expr;
  7427. }
  7428. Type *left_type = nullptr;
  7429. Type *right_type = nullptr;
  7430. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7431. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7432. if (right_type == nullptr) {
  7433. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7434. } else {
  7435. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7436. // okay
  7437. } else {
  7438. gbString s = type_to_string(right_type);
  7439. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7440. gb_string_free(s);
  7441. }
  7442. }
  7443. o->expr = node;
  7444. o->type = left_type;
  7445. if (left_type != nullptr) {
  7446. o->mode = Addressing_Value;
  7447. } else {
  7448. o->mode = Addressing_NoValue;
  7449. }
  7450. if (c->curr_proc_sig == nullptr) {
  7451. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7452. }
  7453. Ast *label = be->label;
  7454. switch (be->token.kind) {
  7455. case Token_or_break:
  7456. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  7457. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7458. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7459. }
  7460. break;
  7461. case Token_or_continue:
  7462. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7463. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7464. }
  7465. break;
  7466. }
  7467. if (label != nullptr) {
  7468. if (label->kind != Ast_Ident) {
  7469. error(label, "A branch statement's label name must be an identifier");
  7470. return Expr_Expr;
  7471. }
  7472. Ast *ident = label;
  7473. String name = ident->Ident.token.string;
  7474. Operand o = {};
  7475. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7476. if (e == nullptr) {
  7477. error(ident, "Undeclared label name: %.*s", LIT(name));
  7478. return Expr_Expr;
  7479. }
  7480. add_entity_use(c, ident, e);
  7481. if (e->kind != Entity_Label) {
  7482. error(ident, "'%.*s' is not a label", LIT(name));
  7483. return Expr_Expr;
  7484. }
  7485. Ast *parent = e->Label.parent;
  7486. GB_ASSERT(parent != nullptr);
  7487. switch (parent->kind) {
  7488. case Ast_BlockStmt:
  7489. case Ast_IfStmt:
  7490. case Ast_SwitchStmt:
  7491. if (be->token.kind != Token_or_break) {
  7492. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7493. }
  7494. break;
  7495. case Ast_RangeStmt:
  7496. case Ast_ForStmt:
  7497. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7498. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7499. }
  7500. break;
  7501. }
  7502. }
  7503. return Expr_Expr;
  7504. }
  7505. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7506. Type *bt = base_type(type);
  7507. StringSet fields_visited = {};
  7508. defer (string_set_destroy(&fields_visited));
  7509. StringMap<String> fields_visited_through_raw_union = {};
  7510. defer (string_map_destroy(&fields_visited_through_raw_union));
  7511. String assignment_str = str_lit("structure literal");
  7512. if (bt->kind == Type_BitField) {
  7513. assignment_str = str_lit("bit_field literal");
  7514. }
  7515. for (Ast *elem : elems) {
  7516. if (elem->kind != Ast_FieldValue) {
  7517. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7518. continue;
  7519. }
  7520. ast_node(fv, FieldValue, elem);
  7521. Ast *ident = fv->field;
  7522. if (ident->kind == Ast_ImplicitSelectorExpr) {
  7523. gbString expr_str = expr_to_string(ident);
  7524. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  7525. gb_string_free(expr_str);
  7526. ident = ident->ImplicitSelectorExpr.selector;
  7527. }
  7528. if (ident->kind != Ast_Ident) {
  7529. gbString expr_str = expr_to_string(ident);
  7530. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7531. gb_string_free(expr_str);
  7532. continue;
  7533. }
  7534. String name = ident->Ident.token.string;
  7535. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7536. bool is_unknown = sel.entity == nullptr;
  7537. if (is_unknown) {
  7538. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  7539. continue;
  7540. }
  7541. Entity *field = nullptr;
  7542. if (bt->kind == Type_Struct) {
  7543. field = bt->Struct.fields[sel.index[0]];
  7544. } else if (bt->kind == Type_BitField) {
  7545. field = bt->BitField.fields[sel.index[0]];
  7546. } else {
  7547. GB_PANIC("Unknown type");
  7548. }
  7549. add_entity_use(c, ident, field);
  7550. if (string_set_update(&fields_visited, name)) {
  7551. if (sel.index.count > 1) {
  7552. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7553. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7554. } else {
  7555. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  7556. }
  7557. } else {
  7558. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  7559. }
  7560. continue;
  7561. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7562. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7563. continue;
  7564. }
  7565. if (sel.indirect) {
  7566. 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));
  7567. continue;
  7568. }
  7569. if (sel.index.count > 1) {
  7570. GB_ASSERT(bt->kind == Type_Struct);
  7571. if (is_constant) {
  7572. Type *ft = type;
  7573. for (i32 index : sel.index) {
  7574. Type *bt = base_type(ft);
  7575. switch (bt->kind) {
  7576. case Type_Struct:
  7577. if (bt->Struct.is_raw_union) {
  7578. is_constant = false;
  7579. break;
  7580. }
  7581. ft = bt->Struct.fields[index]->type;
  7582. break;
  7583. case Type_Array:
  7584. ft = bt->Array.elem;
  7585. break;
  7586. default:
  7587. GB_PANIC("invalid type: %s", type_to_string(ft));
  7588. break;
  7589. }
  7590. }
  7591. if (is_constant &&
  7592. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7593. is_constant = false;
  7594. }
  7595. }
  7596. Type *nested_ft = bt;
  7597. for (i32 index : sel.index) {
  7598. Type *bt = base_type(nested_ft);
  7599. switch (bt->kind) {
  7600. case Type_Struct:
  7601. if (bt->Struct.is_raw_union) {
  7602. for (Entity *re : bt->Struct.fields) {
  7603. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7604. }
  7605. }
  7606. nested_ft = bt->Struct.fields[index]->type;
  7607. break;
  7608. case Type_Array:
  7609. nested_ft = bt->Array.elem;
  7610. break;
  7611. default:
  7612. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7613. break;
  7614. }
  7615. }
  7616. field = sel.entity;
  7617. }
  7618. Operand o = {};
  7619. check_expr_or_type(c, &o, fv->value, field->type);
  7620. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7621. is_constant = false;
  7622. }
  7623. if (is_constant) {
  7624. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7625. }
  7626. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  7627. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  7628. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  7629. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  7630. }
  7631. check_assignment(c, &o, field->type, assignment_str);
  7632. c->bit_field_bit_size = prev_bit_field_bit_size;
  7633. }
  7634. }
  7635. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  7636. type_expr = unparen_expr(type_expr);
  7637. if (type_expr == nullptr) {
  7638. return false;
  7639. }
  7640. // [?]Type
  7641. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7642. Ast *count = type_expr->ArrayType.count;
  7643. if (count->kind == Ast_UnaryExpr &&
  7644. count->UnaryExpr.op.kind == Token_Question) {
  7645. return true;
  7646. }
  7647. }
  7648. return false;
  7649. }
  7650. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7651. ExprKind kind = Expr_Expr;
  7652. ast_node(cl, CompoundLit, node);
  7653. Type *type = type_hint;
  7654. if (type != nullptr && is_type_untyped(type)) {
  7655. type = nullptr;
  7656. }
  7657. bool is_to_be_determined_array_count = false;
  7658. bool is_constant = true;
  7659. Ast *type_expr = cl->type;
  7660. bool used_type_hint_expr = false;
  7661. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  7662. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  7663. type_expr = clone_ast(c->type_hint_expr);
  7664. used_type_hint_expr = true;
  7665. }
  7666. }
  7667. if (type_expr != nullptr) {
  7668. type = nullptr;
  7669. // [?]Type
  7670. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7671. Ast *count = type_expr->ArrayType.count;
  7672. if (count->kind == Ast_UnaryExpr &&
  7673. count->UnaryExpr.op.kind == Token_Question) {
  7674. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  7675. is_to_be_determined_array_count = true;
  7676. }
  7677. if (cl->elems.count > 0) {
  7678. if (type_expr->ArrayType.tag != nullptr) {
  7679. Ast *tag = type_expr->ArrayType.tag;
  7680. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7681. String name = tag->BasicDirective.name.string;
  7682. if (name == "soa") {
  7683. error(node, "#soa arrays are not supported for compound literals");
  7684. return kind;
  7685. }
  7686. }
  7687. }
  7688. }
  7689. if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  7690. if (cl->elems.count > 0) {
  7691. Ast *tag = type_expr->DynamicArrayType.tag;
  7692. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7693. String name = tag->BasicDirective.name.string;
  7694. if (name == "soa") {
  7695. error(node, "#soa arrays are not supported for compound literals");
  7696. return kind;
  7697. }
  7698. }
  7699. }
  7700. if (type == nullptr) {
  7701. type = check_type(c, type_expr);
  7702. }
  7703. }
  7704. if (type == nullptr) {
  7705. error(node, "Missing type in compound literal");
  7706. return kind;
  7707. }
  7708. Type *t = base_type(type);
  7709. if (is_type_polymorphic(t)) {
  7710. gbString str = type_to_string(type);
  7711. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7712. o->expr = node;
  7713. o->type = type;
  7714. gb_string_free(str);
  7715. return kind;
  7716. }
  7717. switch (t->kind) {
  7718. case Type_Struct: {
  7719. if (cl->elems.count == 0) {
  7720. break; // NOTE(bill): No need to init
  7721. }
  7722. if (t->Struct.is_raw_union) {
  7723. if (cl->elems.count > 0) {
  7724. // NOTE: unions cannot be constant
  7725. is_constant = false;
  7726. if (cl->elems[0]->kind != Ast_FieldValue) {
  7727. gbString type_str = type_to_string(type);
  7728. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7729. gb_string_free(type_str);
  7730. } else {
  7731. if (cl->elems.count != 1) {
  7732. gbString type_str = type_to_string(type);
  7733. 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);
  7734. gb_string_free(type_str);
  7735. } else {
  7736. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7737. }
  7738. }
  7739. }
  7740. break;
  7741. }
  7742. isize field_count = t->Struct.fields.count;
  7743. isize min_field_count = t->Struct.fields.count;
  7744. for (isize i = min_field_count-1; i >= 0; i--) {
  7745. Entity *e = t->Struct.fields[i];
  7746. GB_ASSERT(e->kind == Entity_Variable);
  7747. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7748. min_field_count--;
  7749. } else {
  7750. break;
  7751. }
  7752. }
  7753. if (cl->elems[0]->kind == Ast_FieldValue) {
  7754. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7755. } else {
  7756. bool seen_field_value = false;
  7757. for_array(index, cl->elems) {
  7758. Entity *field = nullptr;
  7759. Ast *elem = cl->elems[index];
  7760. if (elem->kind == Ast_FieldValue) {
  7761. seen_field_value = true;
  7762. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7763. continue;
  7764. } else if (seen_field_value) {
  7765. error(elem, "Value elements cannot be used after a 'field = value'");
  7766. continue;
  7767. }
  7768. if (index >= field_count) {
  7769. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7770. break;
  7771. }
  7772. if (field == nullptr) {
  7773. field = t->Struct.fields[index];
  7774. }
  7775. Operand o = {};
  7776. check_expr_or_type(c, &o, elem, field->type);
  7777. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7778. is_constant = false;
  7779. }
  7780. if (is_constant) {
  7781. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7782. }
  7783. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7784. }
  7785. if (cl->elems.count < field_count) {
  7786. if (min_field_count < field_count) {
  7787. if (cl->elems.count < min_field_count) {
  7788. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7789. }
  7790. } else {
  7791. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7792. }
  7793. }
  7794. }
  7795. break;
  7796. }
  7797. case Type_Slice:
  7798. case Type_Array:
  7799. case Type_DynamicArray:
  7800. case Type_SimdVector:
  7801. case Type_Matrix:
  7802. {
  7803. Type *elem_type = nullptr;
  7804. String context_name = {};
  7805. i64 max_type_count = -1;
  7806. if (t->kind == Type_Slice) {
  7807. elem_type = t->Slice.elem;
  7808. context_name = str_lit("slice literal");
  7809. } else if (t->kind == Type_Array) {
  7810. elem_type = t->Array.elem;
  7811. context_name = str_lit("array literal");
  7812. if (!is_to_be_determined_array_count) {
  7813. max_type_count = t->Array.count;
  7814. }
  7815. } else if (t->kind == Type_DynamicArray) {
  7816. elem_type = t->DynamicArray.elem;
  7817. context_name = str_lit("dynamic array literal");
  7818. is_constant = false;
  7819. if (!build_context.no_dynamic_literals) {
  7820. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7821. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7822. }
  7823. } else if (t->kind == Type_SimdVector) {
  7824. elem_type = t->SimdVector.elem;
  7825. context_name = str_lit("simd vector literal");
  7826. max_type_count = t->SimdVector.count;
  7827. } else if (t->kind == Type_Matrix) {
  7828. elem_type = t->Matrix.elem;
  7829. context_name = str_lit("matrix literal");
  7830. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7831. } else {
  7832. GB_PANIC("unreachable");
  7833. }
  7834. i64 max = 0;
  7835. Type *bet = base_type(elem_type);
  7836. if (!elem_type_can_be_constant(bet)) {
  7837. is_constant = false;
  7838. }
  7839. if (bet == t_invalid) {
  7840. break;
  7841. }
  7842. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7843. RangeCache rc = range_cache_make(heap_allocator());
  7844. defer (range_cache_destroy(&rc));
  7845. for (Ast *elem : cl->elems) {
  7846. if (elem->kind != Ast_FieldValue) {
  7847. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7848. continue;
  7849. }
  7850. ast_node(fv, FieldValue, elem);
  7851. if (is_ast_range(fv->field)) {
  7852. Token op = fv->field->BinaryExpr.op;
  7853. Operand x = {};
  7854. Operand y = {};
  7855. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7856. if (!ok) {
  7857. continue;
  7858. }
  7859. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7860. error(x.expr, "Expected a constant integer as an array field");
  7861. continue;
  7862. }
  7863. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7864. error(y.expr, "Expected a constant integer as an array field");
  7865. continue;
  7866. }
  7867. i64 lo = exact_value_to_i64(x.value);
  7868. i64 hi = exact_value_to_i64(y.value);
  7869. i64 max_index = hi;
  7870. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7871. hi -= 1;
  7872. } else { // .. (inclusive)
  7873. max_index += 1;
  7874. }
  7875. bool new_range = range_cache_add_range(&rc, lo, hi);
  7876. if (!new_range) {
  7877. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7878. continue;
  7879. }
  7880. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7881. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7882. continue;
  7883. }
  7884. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7885. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7886. continue;
  7887. }
  7888. if (max < hi) {
  7889. max = max_index;
  7890. }
  7891. Operand operand = {};
  7892. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7893. check_assignment(c, &operand, elem_type, context_name);
  7894. is_constant = is_constant && operand.mode == Addressing_Constant;
  7895. } else {
  7896. Operand op_index = {};
  7897. check_expr(c, &op_index, fv->field);
  7898. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7899. error(elem, "Expected a constant integer as an array field");
  7900. continue;
  7901. }
  7902. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7903. i64 index = exact_value_to_i64(op_index.value);
  7904. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7905. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7906. continue;
  7907. }
  7908. bool new_index = range_cache_add_index(&rc, index);
  7909. if (!new_index) {
  7910. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7911. continue;
  7912. }
  7913. if (max < index+1) {
  7914. max = index+1;
  7915. }
  7916. Operand operand = {};
  7917. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7918. check_assignment(c, &operand, elem_type, context_name);
  7919. is_constant = is_constant && operand.mode == Addressing_Constant;
  7920. }
  7921. }
  7922. cl->max_count = max;
  7923. } else {
  7924. isize index = 0;
  7925. for (; index < cl->elems.count; index++) {
  7926. Ast *e = cl->elems[index];
  7927. if (e == nullptr) {
  7928. error(node, "Invalid literal element");
  7929. continue;
  7930. }
  7931. if (e->kind == Ast_FieldValue) {
  7932. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7933. continue;
  7934. }
  7935. if (0 <= max_type_count && max_type_count <= index) {
  7936. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7937. }
  7938. Operand operand = {};
  7939. check_expr_with_type_hint(c, &operand, e, elem_type);
  7940. check_assignment(c, &operand, elem_type, context_name);
  7941. is_constant = is_constant && operand.mode == Addressing_Constant;
  7942. }
  7943. if (max < index) {
  7944. max = index;
  7945. }
  7946. }
  7947. if (t->kind == Type_Array) {
  7948. if (is_to_be_determined_array_count) {
  7949. t->Array.count = max;
  7950. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7951. if (0 < max && max < t->Array.count) {
  7952. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7953. }
  7954. }
  7955. }
  7956. if (t->kind == Type_SimdVector) {
  7957. if (!is_constant) {
  7958. // error(node, "Expected all constant elements for a simd vector");
  7959. }
  7960. }
  7961. if (t->kind == Type_DynamicArray) {
  7962. if (build_context.no_dynamic_literals && cl->elems.count) {
  7963. error(node, "Compound literals of dynamic types have been disabled");
  7964. }
  7965. }
  7966. if (t->kind == Type_Matrix) {
  7967. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7968. if (0 < max && max < max_type_count) {
  7969. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7970. }
  7971. }
  7972. }
  7973. break;
  7974. }
  7975. case Type_EnumeratedArray:
  7976. {
  7977. Type *elem_type = t->EnumeratedArray.elem;
  7978. Type *index_type = t->EnumeratedArray.index;
  7979. String context_name = str_lit("enumerated array literal");
  7980. i64 max_type_count = t->EnumeratedArray.count;
  7981. gbString index_type_str = type_to_string(index_type);
  7982. defer (gb_string_free(index_type_str));
  7983. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7984. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7985. String total_lo_string = {};
  7986. String total_hi_string = {};
  7987. GB_ASSERT(is_type_enum(index_type));
  7988. {
  7989. Type *bt = base_type(index_type);
  7990. GB_ASSERT(bt->kind == Type_Enum);
  7991. for (Entity *f : bt->Enum.fields) {
  7992. if (f->kind != Entity_Constant) {
  7993. continue;
  7994. }
  7995. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7996. total_lo_string = f->token.string;
  7997. }
  7998. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7999. total_hi_string = f->token.string;
  8000. }
  8001. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8002. break;
  8003. }
  8004. }
  8005. }
  8006. i64 max = 0;
  8007. Type *bet = base_type(elem_type);
  8008. if (!elem_type_can_be_constant(bet)) {
  8009. is_constant = false;
  8010. }
  8011. if (bet == t_invalid) {
  8012. break;
  8013. }
  8014. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8015. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8016. defer (map_destroy(&seen));
  8017. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8018. RangeCache rc = range_cache_make(heap_allocator());
  8019. defer (range_cache_destroy(&rc));
  8020. for (Ast *elem : cl->elems) {
  8021. if (elem->kind != Ast_FieldValue) {
  8022. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8023. continue;
  8024. }
  8025. ast_node(fv, FieldValue, elem);
  8026. if (is_ast_range(fv->field)) {
  8027. Token op = fv->field->BinaryExpr.op;
  8028. Operand x = {};
  8029. Operand y = {};
  8030. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8031. if (!ok) {
  8032. continue;
  8033. }
  8034. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8035. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8036. continue;
  8037. }
  8038. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8039. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8040. continue;
  8041. }
  8042. i64 lo = exact_value_to_i64(x.value);
  8043. i64 hi = exact_value_to_i64(y.value);
  8044. i64 max_index = hi;
  8045. if (op.kind == Token_RangeHalf) {
  8046. hi -= 1;
  8047. }
  8048. bool new_range = range_cache_add_range(&rc, lo, hi);
  8049. if (!new_range) {
  8050. gbString lo_str = expr_to_string(x.expr);
  8051. gbString hi_str = expr_to_string(y.expr);
  8052. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8053. gb_string_free(hi_str);
  8054. gb_string_free(lo_str);
  8055. continue;
  8056. }
  8057. // NOTE(bill): These are sanity checks for invalid enum values
  8058. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8059. gbString lo_str = expr_to_string(x.expr);
  8060. 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));
  8061. gb_string_free(lo_str);
  8062. continue;
  8063. }
  8064. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8065. gbString hi_str = expr_to_string(y.expr);
  8066. 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));
  8067. gb_string_free(hi_str);
  8068. continue;
  8069. }
  8070. if (max < hi) {
  8071. max = max_index;
  8072. }
  8073. Operand operand = {};
  8074. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8075. check_assignment(c, &operand, elem_type, context_name);
  8076. is_constant = is_constant && operand.mode == Addressing_Constant;
  8077. TokenKind upper_op = Token_LtEq;
  8078. if (op.kind == Token_RangeHalf) {
  8079. upper_op = Token_Lt;
  8080. }
  8081. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8082. } else {
  8083. Operand op_index = {};
  8084. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8085. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8086. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8087. continue;
  8088. }
  8089. i64 index = exact_value_to_i64(op_index.value);
  8090. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8091. gbString idx_str = expr_to_string(op_index.expr);
  8092. 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));
  8093. gb_string_free(idx_str);
  8094. continue;
  8095. }
  8096. bool new_index = range_cache_add_index(&rc, index);
  8097. if (!new_index) {
  8098. gbString idx_str = expr_to_string(op_index.expr);
  8099. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8100. gb_string_free(idx_str);
  8101. continue;
  8102. }
  8103. if (max < index+1) {
  8104. max = index+1;
  8105. }
  8106. Operand operand = {};
  8107. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8108. check_assignment(c, &operand, elem_type, context_name);
  8109. is_constant = is_constant && operand.mode == Addressing_Constant;
  8110. add_to_seen_map(c, &seen, op_index);
  8111. }
  8112. }
  8113. cl->max_count = max;
  8114. } else {
  8115. isize index = 0;
  8116. for (; index < cl->elems.count; index++) {
  8117. Ast *e = cl->elems[index];
  8118. if (e == nullptr) {
  8119. error(node, "Invalid literal element");
  8120. continue;
  8121. }
  8122. if (e->kind == Ast_FieldValue) {
  8123. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8124. continue;
  8125. }
  8126. if (0 <= max_type_count && max_type_count <= index) {
  8127. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8128. }
  8129. Operand operand = {};
  8130. check_expr_with_type_hint(c, &operand, e, elem_type);
  8131. check_assignment(c, &operand, elem_type, context_name);
  8132. is_constant = is_constant && operand.mode == Addressing_Constant;
  8133. }
  8134. if (max < index) {
  8135. max = index;
  8136. }
  8137. }
  8138. bool was_error = false;
  8139. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8140. if (0 < max && max < t->EnumeratedArray.count) {
  8141. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8142. was_error = true;
  8143. } else {
  8144. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8145. was_error = true;
  8146. }
  8147. }
  8148. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8149. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8150. TEMPORARY_ALLOCATOR_GUARD();
  8151. Type *et = base_type(index_type);
  8152. GB_ASSERT(et->kind == Type_Enum);
  8153. auto fields = et->Enum.fields;
  8154. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8155. for (Entity *f : fields) {
  8156. if (f->kind != Entity_Constant) {
  8157. continue;
  8158. }
  8159. ExactValue v = f->Constant.value;
  8160. auto found = map_get(&seen, hash_exact_value(v));
  8161. if (!found) {
  8162. array_add(&unhandled, f);
  8163. }
  8164. }
  8165. if (unhandled.count > 0) {
  8166. ERROR_BLOCK();
  8167. if (unhandled.count == 1) {
  8168. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8169. } else {
  8170. error(node, "Unhandled enumerated array cases:");
  8171. for_array(i, unhandled) {
  8172. Entity *f = unhandled[i];
  8173. error_line("\t%.*s\n", LIT(f->token.string));
  8174. }
  8175. }
  8176. if (!build_context.terse_errors) {
  8177. error_line("\n");
  8178. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8179. }
  8180. }
  8181. }
  8182. break;
  8183. }
  8184. case Type_Basic: {
  8185. if (!is_type_any(t)) {
  8186. if (cl->elems.count != 0) {
  8187. gbString s = type_to_string(t);
  8188. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8189. gb_string_free(s);
  8190. is_constant = false;
  8191. }
  8192. break;
  8193. }
  8194. if (cl->elems.count == 0) {
  8195. break; // NOTE(bill): No need to init
  8196. }
  8197. { // Checker values
  8198. Type *field_types[2] = {t_rawptr, t_typeid};
  8199. isize field_count = 2;
  8200. if (cl->elems[0]->kind == Ast_FieldValue) {
  8201. bool fields_visited[2] = {};
  8202. for_array(i, cl->elems) {
  8203. Ast *elem = cl->elems[i];
  8204. if (elem->kind != Ast_FieldValue) {
  8205. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8206. continue;
  8207. }
  8208. ast_node(fv, FieldValue, elem);
  8209. if (fv->field->kind != Ast_Ident) {
  8210. gbString expr_str = expr_to_string(fv->field);
  8211. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8212. gb_string_free(expr_str);
  8213. continue;
  8214. }
  8215. String name = fv->field->Ident.token.string;
  8216. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8217. if (sel.entity == nullptr) {
  8218. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8219. continue;
  8220. }
  8221. isize index = sel.index[0];
  8222. if (fields_visited[index]) {
  8223. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8224. continue;
  8225. }
  8226. fields_visited[index] = true;
  8227. check_expr(c, o, fv->value);
  8228. // NOTE(bill): 'any' literals can never be constant
  8229. is_constant = false;
  8230. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8231. }
  8232. } else {
  8233. for_array(index, cl->elems) {
  8234. Ast *elem = cl->elems[index];
  8235. if (elem->kind == Ast_FieldValue) {
  8236. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8237. continue;
  8238. }
  8239. check_expr(c, o, elem);
  8240. if (index >= field_count) {
  8241. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8242. break;
  8243. }
  8244. // NOTE(bill): 'any' literals can never be constant
  8245. is_constant = false;
  8246. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8247. }
  8248. if (cl->elems.count < field_count) {
  8249. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8250. }
  8251. }
  8252. }
  8253. break;
  8254. }
  8255. case Type_Map: {
  8256. if (cl->elems.count == 0) {
  8257. break;
  8258. }
  8259. is_constant = false;
  8260. { // Checker values
  8261. bool key_is_typeid = is_type_typeid(t->Map.key);
  8262. bool value_is_typeid = is_type_typeid(t->Map.value);
  8263. for (Ast *elem : cl->elems) {
  8264. if (elem->kind != Ast_FieldValue) {
  8265. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8266. continue;
  8267. }
  8268. ast_node(fv, FieldValue, elem);
  8269. if (key_is_typeid) {
  8270. check_expr_or_type(c, o, fv->field, t->Map.key);
  8271. } else {
  8272. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8273. }
  8274. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8275. if (o->mode == Addressing_Invalid) {
  8276. continue;
  8277. }
  8278. if (value_is_typeid) {
  8279. check_expr_or_type(c, o, fv->value, t->Map.value);
  8280. } else {
  8281. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8282. }
  8283. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8284. }
  8285. }
  8286. if (build_context.no_dynamic_literals && cl->elems.count) {
  8287. error(node, "Compound literals of dynamic types have been disabled");
  8288. } else {
  8289. add_map_reserve_dependencies(c);
  8290. add_map_set_dependencies(c);
  8291. }
  8292. break;
  8293. }
  8294. case Type_BitSet: {
  8295. if (cl->elems.count == 0) {
  8296. break; // NOTE(bill): No need to init
  8297. }
  8298. Type *et = base_type(t->BitSet.elem);
  8299. isize field_count = 0;
  8300. if (et->kind == Type_Enum) {
  8301. field_count = et->Enum.fields.count;
  8302. }
  8303. if (cl->elems[0]->kind == Ast_FieldValue) {
  8304. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8305. is_constant = false;
  8306. } else {
  8307. for (Ast *elem : cl->elems) {
  8308. if (elem->kind == Ast_FieldValue) {
  8309. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8310. continue;
  8311. }
  8312. check_expr_with_type_hint(c, o, elem, et);
  8313. if (is_constant) {
  8314. is_constant = o->mode == Addressing_Constant;
  8315. }
  8316. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8317. if (o->mode == Addressing_Constant) {
  8318. i64 lower = t->BitSet.lower;
  8319. i64 upper = t->BitSet.upper;
  8320. i64 v = exact_value_to_i64(o->value);
  8321. if (lower <= v && v <= upper) {
  8322. // okay
  8323. } else {
  8324. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8325. continue;
  8326. }
  8327. }
  8328. }
  8329. }
  8330. break;
  8331. }
  8332. case Type_BitField: {
  8333. if (cl->elems.count == 0) {
  8334. break; // NOTE(bill): No need to init
  8335. }
  8336. is_constant = false;
  8337. if (cl->elems[0]->kind != Ast_FieldValue) {
  8338. gbString type_str = type_to_string(type);
  8339. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8340. gb_string_free(type_str);
  8341. } else {
  8342. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8343. }
  8344. break;
  8345. }
  8346. default: {
  8347. if (cl->elems.count == 0) {
  8348. break; // NOTE(bill): No need to init
  8349. }
  8350. gbString str = type_to_string(type);
  8351. error(node, "Invalid compound literal type '%s'", str);
  8352. gb_string_free(str);
  8353. return kind;
  8354. }
  8355. }
  8356. if (is_constant) {
  8357. o->mode = Addressing_Constant;
  8358. if (is_type_bit_set(type)) {
  8359. // NOTE(bill): Encode as an integer
  8360. Type *bt = base_type(type);
  8361. BigInt bits = {};
  8362. BigInt one = {};
  8363. big_int_from_u64(&one, 1);
  8364. for (Ast *e : cl->elems) {
  8365. GB_ASSERT(e->kind != Ast_FieldValue);
  8366. TypeAndValue tav = e->tav;
  8367. if (tav.mode != Addressing_Constant) {
  8368. continue;
  8369. }
  8370. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8371. i64 v = big_int_to_i64(&tav.value.value_integer);
  8372. i64 lower = bt->BitSet.lower;
  8373. u64 index = cast(u64)(v-lower);
  8374. BigInt bit = {};
  8375. big_int_from_u64(&bit, index);
  8376. big_int_shl(&bit, &one, &bit);
  8377. big_int_or(&bits, &bits, &bit);
  8378. }
  8379. o->value.kind = ExactValue_Integer;
  8380. o->value.value_integer = bits;
  8381. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8382. ExactValue value = exact_value_compound(node);
  8383. Type *bt = core_type(type);
  8384. if (bt->kind == Type_Basic) {
  8385. if (bt->Basic.flags & BasicFlag_Boolean) {
  8386. value = exact_value_bool(false);
  8387. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8388. value = exact_value_i64(0);
  8389. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8390. value = exact_value_i64(0);
  8391. } else if (bt->Basic.flags & BasicFlag_Float) {
  8392. value = exact_value_float(0);
  8393. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8394. value = exact_value_complex(0, 0);
  8395. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8396. value = exact_value_quaternion(0, 0, 0, 0);
  8397. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8398. value = exact_value_pointer(0);
  8399. } else if (bt->Basic.flags & BasicFlag_String) {
  8400. String empty_string = {};
  8401. value = exact_value_string(empty_string);
  8402. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8403. value = exact_value_i64(0);
  8404. }
  8405. }
  8406. o->value = value;
  8407. } else {
  8408. o->value = exact_value_compound(node);
  8409. }
  8410. } else {
  8411. o->mode = Addressing_Value;
  8412. }
  8413. o->type = type;
  8414. return kind;
  8415. }
  8416. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8417. ExprKind kind = Expr_Expr;
  8418. ast_node(ta, TypeAssertion, node);
  8419. check_expr(c, o, ta->expr);
  8420. node->viral_state_flags |= ta->expr->viral_state_flags;
  8421. if (o->mode == Addressing_Invalid) {
  8422. o->expr = node;
  8423. return kind;
  8424. }
  8425. if (o->mode == Addressing_Constant) {
  8426. gbString expr_str = expr_to_string(o->expr);
  8427. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8428. gb_string_free(expr_str);
  8429. o->mode = Addressing_Invalid;
  8430. o->expr = node;
  8431. return kind;
  8432. }
  8433. if (is_type_untyped(o->type)) {
  8434. gbString expr_str = expr_to_string(o->expr);
  8435. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8436. gb_string_free(expr_str);
  8437. o->mode = Addressing_Invalid;
  8438. o->expr = node;
  8439. return kind;
  8440. }
  8441. Type *src = type_deref(o->type);
  8442. Type *bsrc = base_type(src);
  8443. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8444. if (!is_type_union(src)) {
  8445. gbString str = type_to_string(o->type);
  8446. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8447. gb_string_free(str);
  8448. o->mode = Addressing_Invalid;
  8449. o->expr = node;
  8450. return kind;
  8451. }
  8452. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8453. bool allowed = false;
  8454. for (Type *vt : bsrc->Union.variants) {
  8455. if (are_types_identical(vt, type_hint)) {
  8456. allowed = true;
  8457. add_type_info_type(c, vt);
  8458. break;
  8459. }
  8460. }
  8461. if (allowed) {
  8462. add_type_info_type(c, o->type);
  8463. o->type = type_hint;
  8464. o->mode = Addressing_OptionalOk;
  8465. return kind;
  8466. }
  8467. }
  8468. if (bsrc->Union.variants.count != 1) {
  8469. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8470. o->mode = Addressing_Invalid;
  8471. o->expr = node;
  8472. return kind;
  8473. }
  8474. add_type_info_type(c, o->type);
  8475. add_type_info_type(c, bsrc->Union.variants[0]);
  8476. o->type = bsrc->Union.variants[0];
  8477. o->mode = Addressing_OptionalOk;
  8478. } else {
  8479. Type *t = check_type(c, ta->type);
  8480. Type *dst = t;
  8481. if (is_type_union(src)) {
  8482. bool ok = false;
  8483. for (Type *vt : bsrc->Union.variants) {
  8484. if (are_types_identical(vt, dst)) {
  8485. ok = true;
  8486. break;
  8487. }
  8488. }
  8489. if (!ok) {
  8490. gbString expr_str = expr_to_string(o->expr);
  8491. gbString dst_type_str = type_to_string(t);
  8492. defer (gb_string_free(expr_str));
  8493. defer (gb_string_free(dst_type_str));
  8494. if (bsrc->Union.variants.count == 0) {
  8495. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8496. } else {
  8497. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8498. }
  8499. o->mode = Addressing_Invalid;
  8500. o->expr = node;
  8501. return kind;
  8502. }
  8503. add_type_info_type(c, o->type);
  8504. add_type_info_type(c, t);
  8505. o->type = t;
  8506. o->mode = Addressing_OptionalOk;
  8507. } else if (is_type_any(src)) {
  8508. o->type = t;
  8509. o->mode = Addressing_OptionalOk;
  8510. add_type_info_type(c, o->type);
  8511. add_type_info_type(c, t);
  8512. } else {
  8513. gbString str = type_to_string(o->type);
  8514. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8515. gb_string_free(str);
  8516. o->mode = Addressing_Invalid;
  8517. o->expr = node;
  8518. return kind;
  8519. }
  8520. }
  8521. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8522. add_package_dependency(c, "runtime", "type_assertion_check");
  8523. add_package_dependency(c, "runtime", "type_assertion_check2");
  8524. }
  8525. return kind;
  8526. }
  8527. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8528. ast_node(se, SelectorCallExpr, node);
  8529. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8530. // COM APIs is a great example of where this kind of thing is extremely useful
  8531. // General idea:
  8532. //
  8533. // x->y(123) == x.y(x, 123)
  8534. //
  8535. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8536. // Just regenerating a new AST aids things
  8537. //
  8538. // TODO(bill): Is this a good hack or not?
  8539. //
  8540. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8541. if (se->modified_call) {
  8542. // Prevent double evaluation
  8543. o->expr = node;
  8544. o->type = node->tav.type;
  8545. o->value = node->tav.value;
  8546. o->mode = node->tav.mode;
  8547. return Expr_Expr;
  8548. }
  8549. bool allow_arrow_right_selector_expr;
  8550. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8551. c->allow_arrow_right_selector_expr = true;
  8552. Operand x = {};
  8553. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8554. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8555. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8556. o->mode = Addressing_Invalid;
  8557. o->type = t_invalid;
  8558. o->expr = node;
  8559. return kind;
  8560. }
  8561. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8562. gbString type_str = type_to_string(x.type);
  8563. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8564. gb_string_free(type_str);
  8565. o->mode = Addressing_Invalid;
  8566. o->type = t_invalid;
  8567. o->expr = node;
  8568. return Expr_Stmt;
  8569. }
  8570. ast_node(ce, CallExpr, se->call);
  8571. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8572. Ast *first_arg = x.expr->SelectorExpr.expr;
  8573. GB_ASSERT(first_arg != nullptr);
  8574. Entity *e = entity_of_node(se->expr);
  8575. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8576. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8577. }
  8578. if (e->kind != Entity_ProcGroup) {
  8579. Type *pt = base_type(x.type);
  8580. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8581. Type *first_type = nullptr;
  8582. String first_arg_name = {};
  8583. if (pt->Proc.param_count > 0) {
  8584. Entity *f = pt->Proc.params->Tuple.variables[0];
  8585. first_type = f->type;
  8586. first_arg_name = f->token.string;
  8587. }
  8588. if (first_arg_name.len == 0) {
  8589. first_arg_name = str_lit("_");
  8590. }
  8591. if (first_type == nullptr) {
  8592. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8593. o->mode = Addressing_Invalid;
  8594. o->type = t_invalid;
  8595. o->expr = node;
  8596. return Expr_Stmt;
  8597. }
  8598. Operand y = {};
  8599. y.mode = first_arg->tav.mode;
  8600. y.type = first_arg->tav.type;
  8601. y.value = first_arg->tav.value;
  8602. if (check_is_assignable_to(c, &y, first_type)) {
  8603. // Do nothing, it's valid
  8604. } else {
  8605. Operand z = y;
  8606. z.type = type_deref(y.type);
  8607. if (check_is_assignable_to(c, &z, first_type)) {
  8608. // NOTE(bill): AST GENERATION HACK!
  8609. Token op = {Token_Pointer};
  8610. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8611. } else if (y.mode == Addressing_Variable) {
  8612. Operand w = y;
  8613. w.type = alloc_type_pointer(y.type);
  8614. if (check_is_assignable_to(c, &w, first_type)) {
  8615. // NOTE(bill): AST GENERATION HACK!
  8616. Token op = {Token_And};
  8617. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8618. }
  8619. }
  8620. }
  8621. if (ce->args.count > 0) {
  8622. bool fail = false;
  8623. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8624. for (Ast *arg : ce->args) {
  8625. bool mix = false;
  8626. if (first_is_field_value) {
  8627. mix = arg->kind != Ast_FieldValue;
  8628. } else {
  8629. mix = arg->kind == Ast_FieldValue;
  8630. }
  8631. if (mix) {
  8632. fail = true;
  8633. break;
  8634. }
  8635. }
  8636. if (!fail && first_is_field_value) {
  8637. Token op = {Token_Eq};
  8638. AstFile *f = first_arg->file();
  8639. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8640. }
  8641. }
  8642. }
  8643. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8644. modified_args[0] = first_arg;
  8645. slice_copy(&modified_args, ce->args, 1);
  8646. ce->args = modified_args;
  8647. se->modified_call = true;
  8648. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8649. c->allow_arrow_right_selector_expr = true;
  8650. check_expr_base(c, o, se->call, type_hint);
  8651. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8652. o->expr = node;
  8653. return Expr_Expr;
  8654. }
  8655. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8656. ExprKind kind = Expr_Expr;
  8657. ast_node(ie, IndexExpr, node);
  8658. check_expr(c, o, ie->expr);
  8659. node->viral_state_flags |= ie->expr->viral_state_flags;
  8660. if (o->mode == Addressing_Invalid) {
  8661. o->expr = node;
  8662. return kind;
  8663. }
  8664. Type *t = base_type(type_deref(o->type));
  8665. bool is_ptr = is_type_pointer(o->type);
  8666. bool is_const = o->mode == Addressing_Constant;
  8667. if (is_type_map(t)) {
  8668. Operand key = {};
  8669. if (is_type_typeid(t->Map.key)) {
  8670. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8671. } else {
  8672. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8673. }
  8674. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8675. if (key.mode == Addressing_Invalid) {
  8676. o->mode = Addressing_Invalid;
  8677. o->expr = node;
  8678. return kind;
  8679. }
  8680. o->mode = Addressing_MapIndex;
  8681. o->type = t->Map.value;
  8682. o->expr = node;
  8683. add_map_get_dependencies(c);
  8684. add_map_set_dependencies(c);
  8685. return Expr_Expr;
  8686. }
  8687. i64 max_count = -1;
  8688. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8689. if (is_const) {
  8690. if (is_type_array(t)) {
  8691. // Okay
  8692. } else if (is_type_slice(t)) {
  8693. // Okay
  8694. } else if (is_type_enumerated_array(t)) {
  8695. // Okay
  8696. } else if (is_type_string(t)) {
  8697. // Okay
  8698. } else if (is_type_relative_multi_pointer(t)) {
  8699. // Okay
  8700. } else if (is_type_matrix(t)) {
  8701. // Okay
  8702. } else {
  8703. valid = false;
  8704. }
  8705. }
  8706. if (!valid) {
  8707. gbString str = expr_to_string(o->expr);
  8708. gbString type_str = type_to_string(o->type);
  8709. defer (gb_string_free(str));
  8710. defer (gb_string_free(type_str));
  8711. if (is_const) {
  8712. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8713. } else {
  8714. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8715. }
  8716. o->mode = Addressing_Invalid;
  8717. o->expr = node;
  8718. return kind;
  8719. }
  8720. if (ie->index == nullptr) {
  8721. gbString str = expr_to_string(o->expr);
  8722. error(o->expr, "Missing index for '%s'", str);
  8723. gb_string_free(str);
  8724. o->mode = Addressing_Invalid;
  8725. o->expr = node;
  8726. return kind;
  8727. }
  8728. Type *index_type_hint = nullptr;
  8729. if (is_type_enumerated_array(t)) {
  8730. Type *bt = base_type(t);
  8731. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8732. index_type_hint = bt->EnumeratedArray.index;
  8733. }
  8734. i64 index = 0;
  8735. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8736. if (is_const) {
  8737. if (index < 0) {
  8738. gbString str = expr_to_string(o->expr);
  8739. error(o->expr, "Cannot index a constant '%s'", str);
  8740. if (!build_context.terse_errors) {
  8741. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8742. }
  8743. gb_string_free(str);
  8744. o->mode = Addressing_Invalid;
  8745. o->expr = node;
  8746. return kind;
  8747. } else if (ok) {
  8748. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8749. o->mode = Addressing_Constant;
  8750. bool success = false;
  8751. bool finish = false;
  8752. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8753. if (!success) {
  8754. gbString str = expr_to_string(o->expr);
  8755. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8756. if (!build_context.terse_errors) {
  8757. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8758. }
  8759. gb_string_free(str);
  8760. o->mode = Addressing_Invalid;
  8761. o->expr = node;
  8762. return kind;
  8763. }
  8764. }
  8765. }
  8766. if (type_hint != nullptr && is_type_matrix(t)) {
  8767. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8768. // if a type hint exists
  8769. }
  8770. return kind;
  8771. }
  8772. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8773. ExprKind kind = Expr_Stmt;
  8774. ast_node(se, SliceExpr, node);
  8775. check_expr(c, o, se->expr);
  8776. node->viral_state_flags |= se->expr->viral_state_flags;
  8777. if (o->mode == Addressing_Invalid) {
  8778. o->mode = Addressing_Invalid;
  8779. o->expr = node;
  8780. return kind;
  8781. }
  8782. bool valid = false;
  8783. i64 max_count = -1;
  8784. Type *t = base_type(type_deref(o->type));
  8785. switch (t->kind) {
  8786. case Type_Basic:
  8787. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8788. valid = true;
  8789. if (o->mode == Addressing_Constant) {
  8790. max_count = o->value.value_string.len;
  8791. }
  8792. o->type = type_deref(o->type);
  8793. }
  8794. break;
  8795. case Type_Array:
  8796. valid = true;
  8797. max_count = t->Array.count;
  8798. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8799. gbString str = expr_to_string(node);
  8800. error(node, "Cannot slice array '%s', value is not addressable", str);
  8801. gb_string_free(str);
  8802. o->mode = Addressing_Invalid;
  8803. o->expr = node;
  8804. return kind;
  8805. }
  8806. o->type = alloc_type_slice(t->Array.elem);
  8807. break;
  8808. case Type_MultiPointer:
  8809. valid = true;
  8810. o->type = type_deref(o->type);
  8811. break;
  8812. case Type_Slice:
  8813. valid = true;
  8814. o->type = type_deref(o->type);
  8815. break;
  8816. case Type_DynamicArray:
  8817. valid = true;
  8818. o->type = alloc_type_slice(t->DynamicArray.elem);
  8819. break;
  8820. case Type_Struct:
  8821. if (is_type_soa_struct(t)) {
  8822. valid = true;
  8823. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8824. }
  8825. break;
  8826. case Type_RelativeMultiPointer:
  8827. valid = true;
  8828. o->type = type_deref(o->type);
  8829. break;
  8830. case Type_EnumeratedArray:
  8831. {
  8832. gbString str = expr_to_string(o->expr);
  8833. gbString type_str = type_to_string(o->type);
  8834. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8835. gb_string_free(type_str);
  8836. gb_string_free(str);
  8837. o->mode = Addressing_Invalid;
  8838. o->expr = node;
  8839. return kind;
  8840. }
  8841. break;
  8842. }
  8843. if (!valid) {
  8844. gbString str = expr_to_string(o->expr);
  8845. gbString type_str = type_to_string(o->type);
  8846. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8847. gb_string_free(type_str);
  8848. gb_string_free(str);
  8849. o->mode = Addressing_Invalid;
  8850. o->expr = node;
  8851. return kind;
  8852. }
  8853. if (se->low == nullptr && se->high != nullptr) {
  8854. // It is okay to continue as it will assume the 1st index is zero
  8855. }
  8856. i64 indices[2] = {};
  8857. Ast *nodes[2] = {se->low, se->high};
  8858. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8859. i64 index = max_count;
  8860. if (nodes[i] != nullptr) {
  8861. i64 capacity = -1;
  8862. if (max_count >= 0) {
  8863. capacity = max_count;
  8864. }
  8865. i64 j = 0;
  8866. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8867. index = j;
  8868. }
  8869. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8870. } else if (i == 0) {
  8871. index = 0;
  8872. }
  8873. indices[i] = index;
  8874. }
  8875. for (isize i = 0; i < gb_count_of(indices); i++) {
  8876. i64 a = indices[i];
  8877. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8878. i64 b = indices[j];
  8879. if (a > b && b >= 0) {
  8880. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8881. }
  8882. }
  8883. }
  8884. if (max_count < 0) {
  8885. if (o->mode == Addressing_Constant) {
  8886. gbString s = expr_to_string(se->expr);
  8887. error(se->expr, "Cannot slice constant value '%s'", s);
  8888. gb_string_free(s);
  8889. }
  8890. }
  8891. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8892. /*
  8893. x[:] -> [^]T
  8894. x[i:] -> [^]T
  8895. x[:n] -> []T
  8896. x[i:n] -> []T
  8897. */
  8898. o->type = alloc_type_slice(t->MultiPointer.elem);
  8899. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  8900. /*
  8901. x[:] -> [^]T
  8902. x[i:] -> [^]T
  8903. x[:n] -> []T
  8904. x[i:n] -> []T
  8905. */
  8906. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  8907. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  8908. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  8909. }
  8910. o->mode = Addressing_Value;
  8911. if (is_type_string(t) && max_count >= 0) {
  8912. bool all_constant = true;
  8913. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8914. if (nodes[i] != nullptr) {
  8915. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8916. if (tav.mode != Addressing_Constant) {
  8917. all_constant = false;
  8918. break;
  8919. }
  8920. }
  8921. }
  8922. if (!all_constant) {
  8923. gbString str = expr_to_string(o->expr);
  8924. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8925. if (!build_context.terse_errors) {
  8926. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8927. }
  8928. gb_string_free(str);
  8929. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8930. o->expr = node;
  8931. return kind;
  8932. }
  8933. String s = {};
  8934. if (o->value.kind == ExactValue_String) {
  8935. s = o->value.value_string;
  8936. }
  8937. o->mode = Addressing_Constant;
  8938. o->type = t;
  8939. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8940. }
  8941. return kind;
  8942. }
  8943. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8944. u32 prev_state_flags = c->state_flags;
  8945. defer (c->state_flags = prev_state_flags);
  8946. if (node->state_flags != 0) {
  8947. u32 in = node->state_flags;
  8948. u32 out = c->state_flags;
  8949. if (in & StateFlag_no_bounds_check) {
  8950. out |= StateFlag_no_bounds_check;
  8951. out &= ~StateFlag_bounds_check;
  8952. } else if (in & StateFlag_bounds_check) {
  8953. out |= StateFlag_bounds_check;
  8954. out &= ~StateFlag_no_bounds_check;
  8955. }
  8956. if (in & StateFlag_no_type_assert) {
  8957. out |= StateFlag_no_type_assert;
  8958. out &= ~StateFlag_type_assert;
  8959. } else if (in & StateFlag_type_assert) {
  8960. out |= StateFlag_type_assert;
  8961. out &= ~StateFlag_no_type_assert;
  8962. }
  8963. c->state_flags = out;
  8964. }
  8965. ExprKind kind = Expr_Stmt;
  8966. o->mode = Addressing_Invalid;
  8967. o->type = t_invalid;
  8968. o->value = {ExactValue_Invalid};
  8969. switch (node->kind) {
  8970. default:
  8971. return kind;
  8972. case_ast_node(be, BadExpr, node)
  8973. return kind;
  8974. case_end;
  8975. case_ast_node(i, Implicit, node)
  8976. switch (i->kind) {
  8977. case Token_context:
  8978. {
  8979. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8980. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8981. return kind;
  8982. }
  8983. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8984. c->scope->flags |= ScopeFlag_ContextDefined;
  8985. }
  8986. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8987. error(node, "'context' has not been defined within this scope");
  8988. // Continue with value
  8989. }
  8990. init_core_context(c->checker);
  8991. o->mode = Addressing_Context;
  8992. o->type = t_context;
  8993. }
  8994. break;
  8995. default:
  8996. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8997. return kind;
  8998. }
  8999. case_end;
  9000. case_ast_node(i, Ident, node);
  9001. check_ident(c, o, node, nullptr, type_hint, false);
  9002. case_end;
  9003. case_ast_node(u, Uninit, node);
  9004. o->mode = Addressing_Value;
  9005. o->type = t_untyped_uninit;
  9006. error(node, "Use of --- outside of variable declaration");
  9007. case_end;
  9008. case_ast_node(bl, BasicLit, node);
  9009. Type *t = t_invalid;
  9010. switch (node->tav.value.kind) {
  9011. case ExactValue_String: t = t_untyped_string; break;
  9012. case ExactValue_Float: t = t_untyped_float; break;
  9013. case ExactValue_Complex: t = t_untyped_complex; break;
  9014. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9015. case ExactValue_Integer:
  9016. t = t_untyped_integer;
  9017. if (bl->token.kind == Token_Rune) {
  9018. t = t_untyped_rune;
  9019. }
  9020. break;
  9021. default:
  9022. GB_PANIC("Unhandled value type for basic literal");
  9023. break;
  9024. }
  9025. o->mode = Addressing_Constant;
  9026. o->type = t;
  9027. o->value = node->tav.value;
  9028. case_end;
  9029. case_ast_node(bd, BasicDirective, node);
  9030. kind = check_basic_directive_expr(c, o, node, type_hint);
  9031. case_end;
  9032. case_ast_node(pg, ProcGroup, node);
  9033. error(node, "Illegal use of a procedure group");
  9034. o->mode = Addressing_Invalid;
  9035. case_end;
  9036. case_ast_node(pl, ProcLit, node);
  9037. CheckerContext ctx = *c;
  9038. DeclInfo *decl = nullptr;
  9039. Type *type = alloc_type(Type_Proc);
  9040. check_open_scope(&ctx, pl->type);
  9041. {
  9042. decl = make_decl_info(ctx.scope, ctx.decl);
  9043. decl->proc_lit = node;
  9044. ctx.decl = decl;
  9045. defer (ctx.decl = ctx.decl->parent);
  9046. if (pl->tags != 0) {
  9047. error(node, "A procedure literal cannot have tags");
  9048. pl->tags = 0; // TODO(bill): Should I zero this?!
  9049. }
  9050. check_procedure_type(&ctx, type, pl->type);
  9051. if (!is_type_proc(type)) {
  9052. gbString str = expr_to_string(node);
  9053. error(node, "Invalid procedure literal '%s'", str);
  9054. gb_string_free(str);
  9055. check_close_scope(&ctx);
  9056. return kind;
  9057. }
  9058. if (pl->body == nullptr) {
  9059. error(node, "A procedure literal must have a body");
  9060. return kind;
  9061. }
  9062. pl->decl = decl;
  9063. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9064. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9065. array_add(&ctx.checker->nested_proc_lits, decl);
  9066. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9067. }
  9068. check_close_scope(&ctx);
  9069. o->mode = Addressing_Value;
  9070. o->type = type;
  9071. case_end;
  9072. case_ast_node(te, TernaryIfExpr, node);
  9073. kind = check_ternary_if_expr(c, o, node, type_hint);
  9074. case_end;
  9075. case_ast_node(te, TernaryWhenExpr, node);
  9076. kind = check_ternary_when_expr(c, o, node, type_hint);
  9077. case_end;
  9078. case_ast_node(oe, OrElseExpr, node);
  9079. return check_or_else_expr(c, o, node, type_hint);
  9080. case_end;
  9081. case_ast_node(re, OrReturnExpr, node);
  9082. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9083. return check_or_return_expr(c, o, node, type_hint);
  9084. case_end;
  9085. case_ast_node(re, OrBranchExpr, node);
  9086. return check_or_branch_expr(c, o, node, type_hint);
  9087. case_end;
  9088. case_ast_node(cl, CompoundLit, node);
  9089. kind = check_compound_literal(c, o, node, type_hint);
  9090. case_end;
  9091. case_ast_node(pe, ParenExpr, node);
  9092. kind = check_expr_base(c, o, pe->expr, type_hint);
  9093. node->viral_state_flags |= pe->expr->viral_state_flags;
  9094. o->expr = node;
  9095. case_end;
  9096. case_ast_node(te, TagExpr, node);
  9097. String name = te->name.string;
  9098. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9099. if (te->expr) {
  9100. kind = check_expr_base(c, o, te->expr, type_hint);
  9101. node->viral_state_flags |= te->expr->viral_state_flags;
  9102. }
  9103. o->expr = node;
  9104. case_end;
  9105. case_ast_node(ta, TypeAssertion, node);
  9106. kind = check_type_assertion(c, o, node, type_hint);
  9107. case_end;
  9108. case_ast_node(tc, TypeCast, node);
  9109. check_expr_or_type(c, o, tc->type);
  9110. if (o->mode != Addressing_Type) {
  9111. gbString str = expr_to_string(tc->type);
  9112. error(tc->type, "Expected a type, got %s", str);
  9113. gb_string_free(str);
  9114. o->mode = Addressing_Invalid;
  9115. }
  9116. if (o->mode == Addressing_Invalid) {
  9117. o->expr = node;
  9118. return kind;
  9119. }
  9120. Type *type = o->type;
  9121. check_expr_base(c, o, tc->expr, type);
  9122. node->viral_state_flags |= tc->expr->viral_state_flags;
  9123. if (o->mode != Addressing_Invalid) {
  9124. switch (tc->token.kind) {
  9125. case Token_transmute:
  9126. check_transmute(c, node, o, type);
  9127. break;
  9128. case Token_cast:
  9129. check_cast(c, o, type);
  9130. break;
  9131. default:
  9132. error(node, "Invalid AST: Invalid casting expression");
  9133. o->mode = Addressing_Invalid;
  9134. break;
  9135. }
  9136. }
  9137. return Expr_Expr;
  9138. case_end;
  9139. case_ast_node(ac, AutoCast, node);
  9140. check_expr_base(c, o, ac->expr, type_hint);
  9141. node->viral_state_flags |= ac->expr->viral_state_flags;
  9142. if (o->mode == Addressing_Invalid) {
  9143. o->expr = node;
  9144. return kind;
  9145. }
  9146. if (type_hint) {
  9147. check_cast(c, o, type_hint);
  9148. }
  9149. o->expr = node;
  9150. return Expr_Expr;
  9151. case_end;
  9152. case_ast_node(ue, UnaryExpr, node);
  9153. Type *th = type_hint;
  9154. if (ue->op.kind == Token_And) {
  9155. th = type_deref(th);
  9156. }
  9157. check_expr_base(c, o, ue->expr, th);
  9158. node->viral_state_flags |= ue->expr->viral_state_flags;
  9159. if (o->mode != Addressing_Invalid) {
  9160. check_unary_expr(c, o, ue->op, node);
  9161. }
  9162. o->expr = node;
  9163. return Expr_Expr;
  9164. case_end;
  9165. case_ast_node(be, BinaryExpr, node);
  9166. check_binary_expr(c, o, node, type_hint, true);
  9167. if (o->mode == Addressing_Invalid) {
  9168. o->expr = node;
  9169. return kind;
  9170. }
  9171. case_end;
  9172. case_ast_node(se, SelectorExpr, node);
  9173. check_selector(c, o, node, type_hint);
  9174. node->viral_state_flags |= se->expr->viral_state_flags;
  9175. case_end;
  9176. case_ast_node(se, SelectorCallExpr, node);
  9177. return check_selector_call_expr(c, o, node, type_hint);
  9178. case_end;
  9179. case_ast_node(ise, ImplicitSelectorExpr, node);
  9180. return check_implicit_selector_expr(c, o, node, type_hint);
  9181. case_end;
  9182. case_ast_node(ie, IndexExpr, node);
  9183. kind = check_index_expr(c, o, node, type_hint);
  9184. case_end;
  9185. case_ast_node(se, SliceExpr, node);
  9186. kind = check_slice_expr(c, o, node, type_hint);
  9187. case_end;
  9188. case_ast_node(mie, MatrixIndexExpr, node);
  9189. check_matrix_index_expr(c, o, node, type_hint);
  9190. o->expr = node;
  9191. return Expr_Expr;
  9192. case_end;
  9193. case_ast_node(ce, CallExpr, node);
  9194. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9195. case_end;
  9196. case_ast_node(de, DerefExpr, node);
  9197. check_expr_or_type(c, o, de->expr);
  9198. node->viral_state_flags |= de->expr->viral_state_flags;
  9199. if (o->mode == Addressing_Invalid) {
  9200. o->mode = Addressing_Invalid;
  9201. o->expr = node;
  9202. return kind;
  9203. } else {
  9204. Type *t = base_type(o->type);
  9205. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9206. o->mode = Addressing_Variable;
  9207. o->type = t->Pointer.elem;
  9208. } else if (t->kind == Type_SoaPointer) {
  9209. o->mode = Addressing_SoaVariable;
  9210. o->type = type_deref(t);
  9211. } else if (t->kind == Type_RelativePointer) {
  9212. if (o->mode != Addressing_Variable) {
  9213. gbString str = expr_to_string(o->expr);
  9214. gbString typ = type_to_string(o->type);
  9215. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9216. gb_string_free(typ);
  9217. gb_string_free(str);
  9218. }
  9219. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9220. add_type_info_type(c, o->type);
  9221. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9222. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9223. o->mode = Addressing_Variable;
  9224. o->type = ptr_type->Pointer.elem;
  9225. } else {
  9226. gbString str = expr_to_string(o->expr);
  9227. gbString typ = type_to_string(o->type);
  9228. ERROR_BLOCK();
  9229. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9230. if (o->type && is_type_multi_pointer(o->type)) {
  9231. if (!build_context.terse_errors) {
  9232. error_line("\tDid you mean '%s[0]'?\n", str);
  9233. }
  9234. }
  9235. gb_string_free(typ);
  9236. gb_string_free(str);
  9237. o->mode = Addressing_Invalid;
  9238. o->expr = node;
  9239. return kind;
  9240. }
  9241. }
  9242. case_end;
  9243. case_ast_node(ia, InlineAsmExpr, node);
  9244. if (c->curr_proc_decl == nullptr) {
  9245. error(node, "Inline asm expressions are only allowed within a procedure body");
  9246. }
  9247. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9248. Type *return_type = nullptr;
  9249. for_array(i, ia->param_types) {
  9250. param_types[i] = check_type(c, ia->param_types[i]);
  9251. }
  9252. if (ia->return_type != nullptr) {
  9253. return_type = check_type(c, ia->return_type);
  9254. }
  9255. Operand x = {};
  9256. check_expr(c, &x, ia->asm_string);
  9257. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9258. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9259. }
  9260. check_expr(c, &x, ia->constraints_string);
  9261. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9262. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9263. }
  9264. Scope *scope = create_scope(c->info, c->scope);
  9265. scope->flags |= ScopeFlag_Proc;
  9266. Type *params = alloc_type_tuple();
  9267. Type *results = alloc_type_tuple();
  9268. if (param_types.count != 0) {
  9269. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9270. for_array(i, param_types) {
  9271. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9272. }
  9273. }
  9274. if (return_type != nullptr) {
  9275. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9276. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9277. }
  9278. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9279. o->type = pt;
  9280. o->mode = Addressing_Value;
  9281. o->expr = node;
  9282. return Expr_Expr;
  9283. case_end;
  9284. case Ast_TypeidType:
  9285. case Ast_PolyType:
  9286. case Ast_ProcType:
  9287. case Ast_PointerType:
  9288. case Ast_MultiPointerType:
  9289. case Ast_ArrayType:
  9290. case Ast_DynamicArrayType:
  9291. case Ast_StructType:
  9292. case Ast_UnionType:
  9293. case Ast_EnumType:
  9294. case Ast_MapType:
  9295. case Ast_BitSetType:
  9296. case Ast_MatrixType:
  9297. case Ast_RelativeType:
  9298. o->mode = Addressing_Type;
  9299. o->type = check_type(c, node);
  9300. break;
  9301. }
  9302. kind = Expr_Expr;
  9303. o->expr = node;
  9304. return kind;
  9305. }
  9306. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9307. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9308. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9309. o->type = t_invalid;
  9310. gbString xs = expr_to_string(o->expr);
  9311. if (o->mode == Addressing_Type) {
  9312. error(o->expr, "Invalid type usage '%s'", xs);
  9313. } else {
  9314. error(o->expr, "Invalid expression '%s'", xs);
  9315. }
  9316. gb_string_free(xs);
  9317. }
  9318. if (o->type != nullptr && is_type_untyped(o->type)) {
  9319. add_untyped(c, node, o->mode, o->type, o->value);
  9320. }
  9321. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9322. add_type_and_value(c, node, o->mode, o->type, o->value);
  9323. return kind;
  9324. }
  9325. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9326. check_expr_base(c, o, e, nullptr);
  9327. switch (o->mode) {
  9328. default:
  9329. return; // NOTE(bill): Valid
  9330. case Addressing_NoValue:
  9331. error_operand_no_value(o);
  9332. break;
  9333. }
  9334. o->mode = Addressing_Invalid;
  9335. }
  9336. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9337. check_expr_base(c, o, e, nullptr);
  9338. switch (o->mode) {
  9339. default:
  9340. return; // NOTE(bill): Valid
  9341. case Addressing_NoValue:
  9342. error_operand_no_value(o);
  9343. break;
  9344. case Addressing_Type:
  9345. error_operand_not_expression(o);
  9346. break;
  9347. }
  9348. o->mode = Addressing_Invalid;
  9349. }
  9350. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9351. check_expr_base(c, o, e, type_hint);
  9352. switch (o->mode) {
  9353. default:
  9354. return; // NOTE(bill): Valid
  9355. case Addressing_NoValue:
  9356. error_operand_no_value(o);
  9357. break;
  9358. case Addressing_Type:
  9359. error_operand_not_expression(o);
  9360. break;
  9361. }
  9362. o->mode = Addressing_Invalid;
  9363. }
  9364. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9365. if (o->mode == Addressing_Value) {
  9366. // NOTE(bill): Tuples are not first class thus never named
  9367. if (o->type->kind == Type_Tuple) {
  9368. isize count = o->type->Tuple.variables.count;
  9369. error(o->expr,
  9370. "%td-valued expression found where single value expected", count);
  9371. o->mode = Addressing_Invalid;
  9372. GB_ASSERT(count != 1);
  9373. }
  9374. }
  9375. }
  9376. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9377. check_multi_expr(c, o, e);
  9378. check_not_tuple(c, o);
  9379. }
  9380. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9381. check_expr_base(c, o, e, type_hint);
  9382. check_not_tuple(c, o);
  9383. error_operand_no_value(o);
  9384. }
  9385. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9386. switch (v.kind) {
  9387. case ExactValue_Invalid:
  9388. return true;
  9389. case ExactValue_Bool:
  9390. return !v.value_bool;
  9391. case ExactValue_String:
  9392. return v.value_string.len == 0;
  9393. case ExactValue_Integer:
  9394. return big_int_is_zero(&v.value_integer);
  9395. case ExactValue_Float:
  9396. return v.value_float == 0.0;
  9397. case ExactValue_Complex:
  9398. if (v.value_complex) {
  9399. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9400. }
  9401. return true;
  9402. case ExactValue_Quaternion:
  9403. if (v.value_quaternion) {
  9404. return v.value_quaternion->real == 0.0 &&
  9405. v.value_quaternion->imag == 0.0 &&
  9406. v.value_quaternion->jmag == 0.0 &&
  9407. v.value_quaternion->kmag == 0.0;
  9408. }
  9409. return true;
  9410. case ExactValue_Pointer:
  9411. return v.value_pointer == 0;
  9412. case ExactValue_Compound:
  9413. if (v.value_compound == nullptr) {
  9414. return true;
  9415. } else {
  9416. ast_node(cl, CompoundLit, v.value_compound);
  9417. if (cl->elems.count == 0) {
  9418. return true;
  9419. } else {
  9420. for (Ast *elem : cl->elems) {
  9421. if (elem->tav.mode != Addressing_Constant) {
  9422. return false;
  9423. }
  9424. if (!is_exact_value_zero(elem->tav.value)) {
  9425. return false;
  9426. }
  9427. }
  9428. return true;
  9429. }
  9430. }
  9431. case ExactValue_Procedure:
  9432. return v.value_procedure == nullptr;
  9433. case ExactValue_Typeid:
  9434. return v.value_typeid == nullptr;
  9435. }
  9436. return true;
  9437. }
  9438. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9439. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9440. for_array(i, params) {
  9441. if (i > 0) {
  9442. str = gb_string_appendc(str, ", ");
  9443. }
  9444. str = write_expr_to_string(str, params[i], false);
  9445. }
  9446. return str;
  9447. }
  9448. gb_internal gbString string_append_string(gbString str, String string) {
  9449. if (string.len > 0) {
  9450. return gb_string_append_length(str, &string[0], string.len);
  9451. }
  9452. return str;
  9453. }
  9454. gb_internal gbString string_append_token(gbString str, Token token) {
  9455. str = string_append_string(str, token.string);
  9456. return str;
  9457. }
  9458. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9459. if (node == nullptr)
  9460. return str;
  9461. if (is_ast_stmt(node)) {
  9462. GB_ASSERT("stmt passed to write_expr_to_string");
  9463. }
  9464. switch (node->kind) {
  9465. default:
  9466. str = gb_string_appendc(str, "(BadExpr)");
  9467. break;
  9468. case_ast_node(i, Ident, node);
  9469. str = string_append_token(str, i->token);
  9470. case_end;
  9471. case_ast_node(i, Implicit, node);
  9472. str = string_append_token(str, *i);
  9473. case_end;
  9474. case_ast_node(bl, BasicLit, node);
  9475. str = string_append_token(str, bl->token);
  9476. case_end;
  9477. case_ast_node(bd, BasicDirective, node);
  9478. str = gb_string_append_rune(str, '#');
  9479. str = string_append_string(str, bd->name.string);
  9480. case_end;
  9481. case_ast_node(ud, Uninit, node);
  9482. str = gb_string_appendc(str, "---");
  9483. case_end;
  9484. case_ast_node(pg, ProcGroup, node);
  9485. str = gb_string_appendc(str, "proc{");
  9486. for_array(i, pg->args) {
  9487. if (i > 0) str = gb_string_appendc(str, ", ");
  9488. str = write_expr_to_string(str, pg->args[i], shorthand);
  9489. }
  9490. str = gb_string_append_rune(str, '}');
  9491. case_end;
  9492. case_ast_node(pl, ProcLit, node);
  9493. str = write_expr_to_string(str, pl->type, shorthand);
  9494. if (pl->body) {
  9495. str = gb_string_appendc(str, " {...}");
  9496. } else {
  9497. str = gb_string_appendc(str, " ---");
  9498. }
  9499. case_end;
  9500. case_ast_node(cl, CompoundLit, node);
  9501. str = write_expr_to_string(str, cl->type, shorthand);
  9502. str = gb_string_append_rune(str, '{');
  9503. if (shorthand) {
  9504. str = gb_string_appendc(str, "...");
  9505. } else {
  9506. for_array(i, cl->elems) {
  9507. if (i > 0) str = gb_string_appendc(str, ", ");
  9508. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9509. }
  9510. }
  9511. str = gb_string_append_rune(str, '}');
  9512. case_end;
  9513. case_ast_node(te, TagExpr, node);
  9514. str = gb_string_append_rune(str, '#');
  9515. str = string_append_token(str, te->name);
  9516. str = write_expr_to_string(str, te->expr, shorthand);
  9517. case_end;
  9518. case_ast_node(ue, UnaryExpr, node);
  9519. str = string_append_token(str, ue->op);
  9520. str = write_expr_to_string(str, ue->expr, shorthand);
  9521. case_end;
  9522. case_ast_node(de, DerefExpr, node);
  9523. str = write_expr_to_string(str, de->expr, shorthand);
  9524. str = gb_string_append_rune(str, '^');
  9525. case_end;
  9526. case_ast_node(be, BinaryExpr, node);
  9527. str = write_expr_to_string(str, be->left, shorthand);
  9528. str = gb_string_append_rune(str, ' ');
  9529. str = string_append_token(str, be->op);
  9530. str = gb_string_append_rune(str, ' ');
  9531. str = write_expr_to_string(str, be->right, shorthand);
  9532. case_end;
  9533. case_ast_node(te, TernaryIfExpr, node);
  9534. TokenPos x = ast_token(te->x).pos;
  9535. TokenPos cond = ast_token(te->cond).pos;
  9536. if (x < cond) {
  9537. str = write_expr_to_string(str, te->x, shorthand);
  9538. str = gb_string_appendc(str, " if ");
  9539. str = write_expr_to_string(str, te->cond, shorthand);
  9540. str = gb_string_appendc(str, " else ");
  9541. str = write_expr_to_string(str, te->y, shorthand);
  9542. } else {
  9543. str = write_expr_to_string(str, te->cond, shorthand);
  9544. str = gb_string_appendc(str, " ? ");
  9545. str = write_expr_to_string(str, te->x, shorthand);
  9546. str = gb_string_appendc(str, " : ");
  9547. str = write_expr_to_string(str, te->y, shorthand);
  9548. }
  9549. case_end;
  9550. case_ast_node(te, TernaryWhenExpr, node);
  9551. str = write_expr_to_string(str, te->x, shorthand);
  9552. str = gb_string_appendc(str, " when ");
  9553. str = write_expr_to_string(str, te->cond, shorthand);
  9554. str = gb_string_appendc(str, " else ");
  9555. str = write_expr_to_string(str, te->y, shorthand);
  9556. case_end;
  9557. case_ast_node(oe, OrElseExpr, node);
  9558. str = write_expr_to_string(str, oe->x, shorthand);
  9559. str = gb_string_appendc(str, " or_else ");
  9560. str = write_expr_to_string(str, oe->y, shorthand);
  9561. case_end;
  9562. case_ast_node(oe, OrReturnExpr, node);
  9563. str = write_expr_to_string(str, oe->expr, shorthand);
  9564. str = gb_string_appendc(str, " or_return");
  9565. case_end;
  9566. case_ast_node(oe, OrBranchExpr, node);
  9567. str = write_expr_to_string(str, oe->expr, shorthand);
  9568. str = gb_string_append_rune(str, ' ');
  9569. str = string_append_token(str, oe->token);
  9570. if (oe->label) {
  9571. str = gb_string_append_rune(str, ' ');
  9572. str = write_expr_to_string(str, oe->label, shorthand);
  9573. }
  9574. case_end;
  9575. case_ast_node(pe, ParenExpr, node);
  9576. str = gb_string_append_rune(str, '(');
  9577. str = write_expr_to_string(str, pe->expr, shorthand);
  9578. str = gb_string_append_rune(str, ')');
  9579. case_end;
  9580. case_ast_node(se, SelectorExpr, node);
  9581. str = write_expr_to_string(str, se->expr, shorthand);
  9582. str = string_append_token(str, se->token);
  9583. str = write_expr_to_string(str, se->selector, shorthand);
  9584. case_end;
  9585. case_ast_node(se, ImplicitSelectorExpr, node);
  9586. str = gb_string_append_rune(str, '.');
  9587. str = write_expr_to_string(str, se->selector, shorthand);
  9588. case_end;
  9589. case_ast_node(se, SelectorCallExpr, node);
  9590. str = write_expr_to_string(str, se->expr, shorthand);
  9591. str = gb_string_appendc(str, "(");
  9592. ast_node(ce, CallExpr, se->call);
  9593. isize start = se->modified_call ? 1 : 0;
  9594. for (isize i = start; i < ce->args.count; i++) {
  9595. Ast *arg = ce->args[i];
  9596. if (i > start) {
  9597. str = gb_string_appendc(str, ", ");
  9598. }
  9599. str = write_expr_to_string(str, arg, shorthand);
  9600. }
  9601. str = gb_string_appendc(str, ")");
  9602. case_end;
  9603. case_ast_node(ta, TypeAssertion, node);
  9604. str = write_expr_to_string(str, ta->expr, shorthand);
  9605. if (ta->type != nullptr &&
  9606. ta->type->kind == Ast_UnaryExpr &&
  9607. ta->type->UnaryExpr.op.kind == Token_Question) {
  9608. str = gb_string_appendc(str, ".?");
  9609. } else {
  9610. str = gb_string_appendc(str, ".(");
  9611. str = write_expr_to_string(str, ta->type, shorthand);
  9612. str = gb_string_append_rune(str, ')');
  9613. }
  9614. case_end;
  9615. case_ast_node(tc, TypeCast, node);
  9616. str = string_append_token(str, tc->token);
  9617. str = gb_string_append_rune(str, '(');
  9618. str = write_expr_to_string(str, tc->type, shorthand);
  9619. str = gb_string_append_rune(str, ')');
  9620. str = write_expr_to_string(str, tc->expr, shorthand);
  9621. case_end;
  9622. case_ast_node(ac, AutoCast, node);
  9623. str = string_append_token(str, ac->token);
  9624. str = gb_string_append_rune(str, ' ');
  9625. str = write_expr_to_string(str, ac->expr, shorthand);
  9626. case_end;
  9627. case_ast_node(ie, IndexExpr, node);
  9628. str = write_expr_to_string(str, ie->expr, shorthand);
  9629. str = gb_string_append_rune(str, '[');
  9630. str = write_expr_to_string(str, ie->index, shorthand);
  9631. str = gb_string_append_rune(str, ']');
  9632. case_end;
  9633. case_ast_node(se, SliceExpr, node);
  9634. str = write_expr_to_string(str, se->expr, shorthand);
  9635. str = gb_string_append_rune(str, '[');
  9636. str = write_expr_to_string(str, se->low, shorthand);
  9637. str = string_append_token(str, se->interval);
  9638. str = write_expr_to_string(str, se->high, shorthand);
  9639. str = gb_string_append_rune(str, ']');
  9640. case_end;
  9641. case_ast_node(mie, MatrixIndexExpr, node);
  9642. str = write_expr_to_string(str, mie->expr, shorthand);
  9643. str = gb_string_append_rune(str, '[');
  9644. str = write_expr_to_string(str, mie->row_index, shorthand);
  9645. str = gb_string_appendc(str, ", ");
  9646. str = write_expr_to_string(str, mie->column_index, shorthand);
  9647. str = gb_string_append_rune(str, ']');
  9648. case_end;
  9649. case_ast_node(e, Ellipsis, node);
  9650. str = gb_string_appendc(str, "..");
  9651. str = write_expr_to_string(str, e->expr, shorthand);
  9652. case_end;
  9653. case_ast_node(fv, FieldValue, node);
  9654. str = write_expr_to_string(str, fv->field, shorthand);
  9655. str = gb_string_appendc(str, " = ");
  9656. str = write_expr_to_string(str, fv->value, shorthand);
  9657. case_end;
  9658. case_ast_node(fv, EnumFieldValue, node);
  9659. str = write_expr_to_string(str, fv->name, shorthand);
  9660. if (fv->value) {
  9661. str = gb_string_appendc(str, " = ");
  9662. str = write_expr_to_string(str, fv->value, shorthand);
  9663. }
  9664. case_end;
  9665. case_ast_node(ht, HelperType, node);
  9666. str = gb_string_appendc(str, "#type ");
  9667. str = write_expr_to_string(str, ht->type, shorthand);
  9668. case_end;
  9669. case_ast_node(ht, DistinctType, node);
  9670. str = gb_string_appendc(str, "distinct ");
  9671. str = write_expr_to_string(str, ht->type, shorthand);
  9672. case_end;
  9673. case_ast_node(pt, PolyType, node);
  9674. str = gb_string_append_rune(str, '$');
  9675. str = write_expr_to_string(str, pt->type, shorthand);
  9676. if (pt->specialization != nullptr) {
  9677. str = gb_string_append_rune(str, '/');
  9678. str = write_expr_to_string(str, pt->specialization, shorthand);
  9679. }
  9680. case_end;
  9681. case_ast_node(pt, PointerType, node);
  9682. str = gb_string_append_rune(str, '^');
  9683. str = write_expr_to_string(str, pt->type, shorthand);
  9684. case_end;
  9685. case_ast_node(pt, MultiPointerType, node);
  9686. str = gb_string_appendc(str, "[^]");
  9687. str = write_expr_to_string(str, pt->type, shorthand);
  9688. case_end;
  9689. case_ast_node(at, ArrayType, node);
  9690. str = gb_string_append_rune(str, '[');
  9691. if (at->count != nullptr &&
  9692. at->count->kind == Ast_UnaryExpr &&
  9693. at->count->UnaryExpr.op.kind == Token_Question) {
  9694. str = gb_string_appendc(str, "?");
  9695. } else {
  9696. str = write_expr_to_string(str, at->count, shorthand);
  9697. }
  9698. str = gb_string_append_rune(str, ']');
  9699. str = write_expr_to_string(str, at->elem, shorthand);
  9700. case_end;
  9701. case_ast_node(at, DynamicArrayType, node);
  9702. str = gb_string_appendc(str, "[dynamic]");
  9703. str = write_expr_to_string(str, at->elem, shorthand);
  9704. case_end;
  9705. case_ast_node(bs, BitSetType, node);
  9706. str = gb_string_appendc(str, "bit_set[");
  9707. str = write_expr_to_string(str, bs->elem, shorthand);
  9708. str = gb_string_appendc(str, "]");
  9709. case_end;
  9710. case_ast_node(mt, MapType, node);
  9711. str = gb_string_appendc(str, "map[");
  9712. str = write_expr_to_string(str, mt->key, shorthand);
  9713. str = gb_string_append_rune(str, ']');
  9714. str = write_expr_to_string(str, mt->value, shorthand);
  9715. case_end;
  9716. case_ast_node(mt, MatrixType, node);
  9717. str = gb_string_appendc(str, "matrix[");
  9718. str = write_expr_to_string(str, mt->row_count, shorthand);
  9719. str = gb_string_appendc(str, ", ");
  9720. str = write_expr_to_string(str, mt->column_count, shorthand);
  9721. str = gb_string_append_rune(str, ']');
  9722. str = write_expr_to_string(str, mt->elem, shorthand);
  9723. case_end;
  9724. case_ast_node(f, Field, node);
  9725. if (f->flags&FieldFlag_using) {
  9726. str = gb_string_appendc(str, "using ");
  9727. }
  9728. if (f->flags&FieldFlag_no_alias) {
  9729. str = gb_string_appendc(str, "#no_alias ");
  9730. }
  9731. if (f->flags&FieldFlag_c_vararg) {
  9732. str = gb_string_appendc(str, "#c_vararg ");
  9733. }
  9734. if (f->flags&FieldFlag_any_int) {
  9735. str = gb_string_appendc(str, "#any_int ");
  9736. }
  9737. if (f->flags&FieldFlag_no_broadcast) {
  9738. str = gb_string_appendc(str, "#no_broadcast ");
  9739. }
  9740. if (f->flags&FieldFlag_const) {
  9741. str = gb_string_appendc(str, "#const ");
  9742. }
  9743. if (f->flags&FieldFlag_subtype) {
  9744. str = gb_string_appendc(str, "#subtype ");
  9745. }
  9746. for_array(i, f->names) {
  9747. Ast *name = f->names[i];
  9748. if (i > 0) str = gb_string_appendc(str, ", ");
  9749. str = write_expr_to_string(str, name, shorthand);
  9750. }
  9751. if (f->names.count > 0) {
  9752. if (f->type == nullptr && f->default_value != nullptr) {
  9753. str = gb_string_append_rune(str, ' ');
  9754. }
  9755. str = gb_string_appendc(str, ":");
  9756. }
  9757. if (f->type != nullptr) {
  9758. str = gb_string_append_rune(str, ' ');
  9759. str = write_expr_to_string(str, f->type, shorthand);
  9760. }
  9761. if (f->default_value != nullptr) {
  9762. if (f->type != nullptr) {
  9763. str = gb_string_append_rune(str, ' ');
  9764. }
  9765. str = gb_string_appendc(str, "= ");
  9766. str = write_expr_to_string(str, f->default_value, shorthand);
  9767. }
  9768. case_end;
  9769. case_ast_node(f, FieldList, node);
  9770. bool has_name = false;
  9771. for_array(i, f->list) {
  9772. ast_node(field, Field, f->list[i]);
  9773. if (field->names.count > 1) {
  9774. has_name = true;
  9775. break;
  9776. }
  9777. if (field->names.count == 0) {
  9778. continue;
  9779. }
  9780. if (!is_blank_ident(field->names[0])) {
  9781. has_name = true;
  9782. break;
  9783. }
  9784. }
  9785. for_array(i, f->list) {
  9786. if (i > 0) str = gb_string_appendc(str, ", ");
  9787. if (has_name) {
  9788. str = write_expr_to_string(str, f->list[i], shorthand);
  9789. } else {
  9790. ast_node(field, Field, f->list[i]);
  9791. if (field->flags&FieldFlag_using) {
  9792. str = gb_string_appendc(str, "using ");
  9793. }
  9794. if (field->flags&FieldFlag_no_alias) {
  9795. str = gb_string_appendc(str, "#no_alias ");
  9796. }
  9797. if (field->flags&FieldFlag_c_vararg) {
  9798. str = gb_string_appendc(str, "#c_vararg ");
  9799. }
  9800. if (field->flags&FieldFlag_any_int) {
  9801. str = gb_string_appendc(str, "#any_int ");
  9802. }
  9803. if (field->flags&FieldFlag_no_broadcast) {
  9804. str = gb_string_appendc(str, "#no_broadcast ");
  9805. }
  9806. if (field->flags&FieldFlag_const) {
  9807. str = gb_string_appendc(str, "#const ");
  9808. }
  9809. if (field->flags&FieldFlag_subtype) {
  9810. str = gb_string_appendc(str, "#subtype ");
  9811. }
  9812. str = write_expr_to_string(str, field->type, shorthand);
  9813. }
  9814. }
  9815. case_end;
  9816. case_ast_node(ce, CallExpr, node);
  9817. switch (ce->inlining) {
  9818. case ProcInlining_inline:
  9819. str = gb_string_appendc(str, "#force_inline ");
  9820. break;
  9821. case ProcInlining_no_inline:
  9822. str = gb_string_appendc(str, "#force_no_inline ");
  9823. break;
  9824. }
  9825. str = write_expr_to_string(str, ce->proc, shorthand);
  9826. str = gb_string_appendc(str, "(");
  9827. isize idx0 = cast(isize)ce->was_selector;
  9828. for (isize i = idx0; i < ce->args.count; i++) {
  9829. Ast *arg = ce->args[i];
  9830. if (i > idx0) {
  9831. str = gb_string_appendc(str, ", ");
  9832. }
  9833. str = write_expr_to_string(str, arg, shorthand);
  9834. }
  9835. str = gb_string_appendc(str, ")");
  9836. case_end;
  9837. case_ast_node(tt, TypeidType, node);
  9838. str = gb_string_appendc(str, "typeid");
  9839. if (tt->specialization) {
  9840. str = gb_string_appendc(str, "/");
  9841. str = write_expr_to_string(str, tt->specialization, shorthand);
  9842. }
  9843. case_end;
  9844. case_ast_node(pt, ProcType, node);
  9845. str = gb_string_appendc(str, "proc(");
  9846. str = write_expr_to_string(str, pt->params, shorthand);
  9847. str = gb_string_appendc(str, ")");
  9848. if (pt->results != nullptr) {
  9849. str = gb_string_appendc(str, " -> ");
  9850. bool parens_needed = false;
  9851. if (pt->results && pt->results->kind == Ast_FieldList) {
  9852. for (Ast *field : pt->results->FieldList.list) {
  9853. ast_node(f, Field, field);
  9854. if (f->names.count != 0) {
  9855. parens_needed = true;
  9856. break;
  9857. }
  9858. }
  9859. }
  9860. if (parens_needed) {
  9861. str = gb_string_append_rune(str, '(');
  9862. }
  9863. str = write_expr_to_string(str, pt->results, shorthand);
  9864. if (parens_needed) {
  9865. str = gb_string_append_rune(str, ')');
  9866. }
  9867. }
  9868. case_end;
  9869. case_ast_node(st, StructType, node);
  9870. str = gb_string_appendc(str, "struct ");
  9871. if (st->polymorphic_params) {
  9872. str = gb_string_append_rune(str, '(');
  9873. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9874. str = gb_string_appendc(str, ") ");
  9875. }
  9876. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9877. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9878. if (st->align) {
  9879. str = gb_string_appendc(str, "#align ");
  9880. str = write_expr_to_string(str, st->align, shorthand);
  9881. str = gb_string_append_rune(str, ' ');
  9882. }
  9883. str = gb_string_append_rune(str, '{');
  9884. if (shorthand) {
  9885. str = gb_string_appendc(str, "...");
  9886. } else {
  9887. str = write_struct_fields_to_string(str, st->fields);
  9888. }
  9889. str = gb_string_append_rune(str, '}');
  9890. case_end;
  9891. case_ast_node(st, UnionType, node);
  9892. str = gb_string_appendc(str, "union ");
  9893. if (st->polymorphic_params) {
  9894. str = gb_string_append_rune(str, '(');
  9895. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9896. str = gb_string_appendc(str, ") ");
  9897. }
  9898. switch (st->kind) {
  9899. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9900. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9901. }
  9902. if (st->align) {
  9903. str = gb_string_appendc(str, "#align ");
  9904. str = write_expr_to_string(str, st->align, shorthand);
  9905. str = gb_string_append_rune(str, ' ');
  9906. }
  9907. str = gb_string_append_rune(str, '{');
  9908. if (shorthand) {
  9909. str = gb_string_appendc(str, "...");
  9910. } else {
  9911. str = write_struct_fields_to_string(str, st->variants);
  9912. }
  9913. str = gb_string_append_rune(str, '}');
  9914. case_end;
  9915. case_ast_node(et, EnumType, node);
  9916. str = gb_string_appendc(str, "enum ");
  9917. if (et->base_type != nullptr) {
  9918. str = write_expr_to_string(str, et->base_type, shorthand);
  9919. str = gb_string_append_rune(str, ' ');
  9920. }
  9921. str = gb_string_append_rune(str, '{');
  9922. if (shorthand) {
  9923. str = gb_string_appendc(str, "...");
  9924. } else {
  9925. for_array(i, et->fields) {
  9926. if (i > 0) {
  9927. str = gb_string_appendc(str, ", ");
  9928. }
  9929. str = write_expr_to_string(str, et->fields[i], shorthand);
  9930. }
  9931. }
  9932. str = gb_string_append_rune(str, '}');
  9933. case_end;
  9934. case_ast_node(rt, RelativeType, node);
  9935. str = write_expr_to_string(str, rt->tag, shorthand);
  9936. str = gb_string_appendc(str, "" );
  9937. str = write_expr_to_string(str, rt->type, shorthand);
  9938. case_end;
  9939. case_ast_node(f, BitFieldField, node);
  9940. str = write_expr_to_string(str, f->name, shorthand);
  9941. str = gb_string_appendc(str, ": ");
  9942. str = write_expr_to_string(str, f->type, shorthand);
  9943. str = gb_string_appendc(str, " | ");
  9944. str = write_expr_to_string(str, f->bit_size, shorthand);
  9945. case_end;
  9946. case_ast_node(bf, BitFieldType, node);
  9947. str = gb_string_appendc(str, "bit_field ");
  9948. if (!shorthand) {
  9949. str = write_expr_to_string(str, bf->backing_type, shorthand);
  9950. }
  9951. str = gb_string_appendc(str, " {");
  9952. if (shorthand) {
  9953. str = gb_string_appendc(str, "...");
  9954. } else {
  9955. for_array(i, bf->fields) {
  9956. if (i > 0) {
  9957. str = gb_string_appendc(str, ", ");
  9958. }
  9959. str = write_expr_to_string(str, bf->fields[i], false);
  9960. }
  9961. }
  9962. str = gb_string_appendc(str, "}");
  9963. case_end;
  9964. case_ast_node(ia, InlineAsmExpr, node);
  9965. str = gb_string_appendc(str, "asm(");
  9966. for_array(i, ia->param_types) {
  9967. if (i > 0) {
  9968. str = gb_string_appendc(str, ", ");
  9969. }
  9970. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9971. }
  9972. str = gb_string_appendc(str, ")");
  9973. if (ia->return_type != nullptr) {
  9974. str = gb_string_appendc(str, " -> ");
  9975. str = write_expr_to_string(str, ia->return_type, shorthand);
  9976. }
  9977. if (ia->has_side_effects) {
  9978. str = gb_string_appendc(str, " #side_effects");
  9979. }
  9980. if (ia->is_align_stack) {
  9981. str = gb_string_appendc(str, " #stack_align");
  9982. }
  9983. if (ia->dialect) {
  9984. str = gb_string_appendc(str, " #");
  9985. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9986. }
  9987. str = gb_string_appendc(str, " {");
  9988. if (shorthand) {
  9989. str = gb_string_appendc(str, "...");
  9990. } else {
  9991. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9992. str = gb_string_appendc(str, ", ");
  9993. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9994. }
  9995. str = gb_string_appendc(str, "}");
  9996. case_end;
  9997. }
  9998. return str;
  9999. }
  10000. gb_internal gbString expr_to_string(Ast *expression) {
  10001. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10002. }
  10003. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10004. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10005. }
  10006. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10007. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10008. }