check_expr.cpp 305 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653
  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_MAX,
  18. };
  19. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  20. "None",
  21. "NoneProcedureType",
  22. "WrongTypes",
  23. "NonVariadicExpand",
  24. "VariadicTuple",
  25. "MultipleVariadicExpand",
  26. "AmbiguousPolymorphicVariadic",
  27. "ArgumentCount",
  28. "TooFewArguments",
  29. "TooManyArguments",
  30. "InvalidFieldValue",
  31. "ParameterNotFound",
  32. "ParameterMissing",
  33. "DuplicateParameter",
  34. "NoneConstantParameter",
  35. };
  36. enum CallArgumentErrorMode {
  37. CallArgumentMode_NoErrors,
  38. CallArgumentMode_ShowErrors,
  39. };
  40. struct CallArgumentData {
  41. Entity *gen_entity;
  42. i64 score;
  43. Type * result_type;
  44. };
  45. struct PolyProcData {
  46. Entity * gen_entity;
  47. ProcInfo *proc_info;
  48. };
  49. struct ValidIndexAndScore {
  50. isize index;
  51. i64 score;
  52. };
  53. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  54. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  55. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  56. return sj < si ? -1 : sj > si;
  57. }
  58. #define CALL_ARGUMENT_CHECKER(name) CallArgumentError name(CheckerContext *c, Ast *call, Type *proc_type, Entity *entity, Array<Operand> operands, CallArgumentErrorMode show_error_mode, CallArgumentData *data)
  59. typedef CALL_ARGUMENT_CHECKER(CallArgumentCheckerType);
  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> *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 CallArgumentData check_call_arguments (CheckerContext *c, Operand *operand, Type *proc_type, Ast *call);
  90. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  91. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type);
  92. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  93. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  95. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  96. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_);
  97. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  98. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  99. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  100. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  101. gb_internal bool is_diverging_expr(Ast *expr);
  102. enum LoadDirectiveResult {
  103. LoadDirective_Success = 0,
  104. LoadDirective_Error = 1,
  105. LoadDirective_NotFound = 2,
  106. };
  107. gb_internal bool is_load_directive_call(Ast *call) {
  108. call = unparen_expr(call);
  109. if (call->kind != Ast_CallExpr) {
  110. return false;
  111. }
  112. ast_node(ce, CallExpr, call);
  113. if (ce->proc->kind != Ast_BasicDirective) {
  114. return false;
  115. }
  116. ast_node(bd, BasicDirective, ce->proc);
  117. String name = bd->name.string;
  118. return name == "load";
  119. }
  120. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  121. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  122. auto results = did_you_mean_results(d);
  123. if (results.count != 0) {
  124. error_line("\tSuggestion: Did you mean?\n");
  125. for (auto const &result : results) {
  126. String const &target = result.target;
  127. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  128. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  129. }
  130. }
  131. }
  132. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  133. if (e->kind != Entity_TypeName) {
  134. return;
  135. }
  136. if (e->TypeName.objc_metadata == nullptr) {
  137. return;
  138. }
  139. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  140. Type *t = base_type(e->type);
  141. GB_ASSERT(t->kind == Type_Struct);
  142. if (is_type) {
  143. for (auto const &entry : objc_metadata->type_entries) {
  144. string_set_add(set, entry.name);
  145. }
  146. } else {
  147. for (auto const &entry : objc_metadata->value_entries) {
  148. string_set_add(set, entry.name);
  149. }
  150. }
  151. for (Entity *f : t->Struct.fields) {
  152. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  153. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  154. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  155. }
  156. }
  157. }
  158. }
  159. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  160. ERROR_BLOCK();
  161. GB_ASSERT(e->kind == Entity_TypeName);
  162. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  163. auto *objc_metadata = e->TypeName.objc_metadata;
  164. MUTEX_GUARD(objc_metadata->mutex);
  165. StringSet set = {};
  166. defer (string_set_destroy(&set));
  167. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  168. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  169. defer (did_you_mean_destroy(&d));
  170. for (String const &target : set) {
  171. did_you_mean_append(&d, target);
  172. }
  173. check_did_you_mean_print(&d, prefix);
  174. }
  175. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  176. ERROR_BLOCK();
  177. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  178. defer (did_you_mean_destroy(&d));
  179. for (Entity *e : fields) {
  180. did_you_mean_append(&d, e->token.string);
  181. }
  182. check_did_you_mean_print(&d, prefix);
  183. }
  184. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  185. ERROR_BLOCK();
  186. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  187. defer (did_you_mean_destroy(&d));
  188. for (Entity *e : fields) {
  189. did_you_mean_append(&d, e->token.string);
  190. }
  191. check_did_you_mean_print(&d, prefix);
  192. }
  193. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  194. ERROR_BLOCK();
  195. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  196. defer (did_you_mean_destroy(&d));
  197. rw_mutex_shared_lock(&scope->mutex);
  198. for (auto const &entry : scope->elements) {
  199. Entity *e = entry.value;
  200. did_you_mean_append(&d, e->token.string);
  201. }
  202. rw_mutex_shared_unlock(&scope->mutex);
  203. check_did_you_mean_print(&d, prefix);
  204. }
  205. gb_internal Entity *entity_from_expr(Ast *expr) {
  206. expr = unparen_expr(expr);
  207. switch (expr->kind) {
  208. case Ast_Ident:
  209. return expr->Ident.entity;
  210. case Ast_SelectorExpr:
  211. return entity_from_expr(expr->SelectorExpr.selector);
  212. }
  213. return nullptr;
  214. }
  215. gb_internal void error_operand_not_expression(Operand *o) {
  216. if (o->mode == Addressing_Type) {
  217. gbString err = expr_to_string(o->expr);
  218. error(o->expr, "'%s' is not an expression but a type", err);
  219. gb_string_free(err);
  220. o->mode = Addressing_Invalid;
  221. }
  222. }
  223. gb_internal void error_operand_no_value(Operand *o) {
  224. if (o->mode == Addressing_NoValue) {
  225. gbString err = expr_to_string(o->expr);
  226. Ast *x = unparen_expr(o->expr);
  227. if (x->kind == Ast_CallExpr) {
  228. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  229. } else {
  230. error(o->expr, "'%s' used as a value", err);
  231. }
  232. gb_string_free(err);
  233. o->mode = Addressing_Invalid;
  234. }
  235. }
  236. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  237. if (build_context.dynamic_map_calls) {
  238. add_package_dependency(c, "runtime", "__dynamic_map_get");
  239. } else {
  240. add_package_dependency(c, "runtime", "map_desired_position");
  241. add_package_dependency(c, "runtime", "map_probe_distance");
  242. }
  243. }
  244. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  245. init_core_source_code_location(c->checker);
  246. if (t_map_set_proc == nullptr) {
  247. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  248. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  249. }
  250. if (build_context.dynamic_map_calls) {
  251. add_package_dependency(c, "runtime", "__dynamic_map_set");
  252. } else {
  253. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  254. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  255. }
  256. }
  257. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  258. init_core_source_code_location(c->checker);
  259. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  260. }
  261. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  262. Scope *s = c->scope;
  263. check_collect_entities(c, nodes);
  264. for (auto const &entry : s->elements) {
  265. Entity *e = entry.value;
  266. switch (e->kind) {
  267. case Entity_Constant:
  268. case Entity_TypeName:
  269. case Entity_Procedure:
  270. break;
  271. default:
  272. continue;
  273. }
  274. DeclInfo *d = decl_info_of_entity(e);
  275. if (d != nullptr) {
  276. check_entity_decl(c, e, d, nullptr);
  277. }
  278. }
  279. }
  280. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  281. Array<Operand> *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  282. ///////////////////////////////////////////////////////////////////////////////
  283. // //
  284. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  285. // //
  286. ///////////////////////////////////////////////////////////////////////////////
  287. CheckerInfo *info = old_c->info;
  288. if (base_entity == nullptr) {
  289. return false;
  290. }
  291. if (!is_type_proc(base_entity->type)) {
  292. return false;
  293. }
  294. String name = base_entity->token.string;
  295. Type *src = base_type(base_entity->type);
  296. Type *dst = nullptr;
  297. if (type != nullptr) {
  298. dst = base_type(type);
  299. }
  300. if (param_operands == nullptr) {
  301. GB_ASSERT(dst != nullptr);
  302. }
  303. if (param_operands != nullptr) {
  304. GB_ASSERT(dst == nullptr);
  305. }
  306. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  307. return false;
  308. }
  309. if (dst != nullptr) {
  310. if (dst->Proc.is_polymorphic) {
  311. return false;
  312. }
  313. if (dst->Proc.param_count != src->Proc.param_count ||
  314. dst->Proc.result_count != src->Proc.result_count) {
  315. return false;
  316. }
  317. }
  318. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  319. if (old_decl == nullptr) {
  320. return false;
  321. }
  322. gbAllocator a = heap_allocator();
  323. Array<Operand> operands = {};
  324. if (param_operands) {
  325. operands = *param_operands;
  326. } else {
  327. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  328. for (isize i = 0; i < dst->Proc.param_count; i++) {
  329. Entity *param = dst->Proc.params->Tuple.variables[i];
  330. Operand o = {Addressing_Value};
  331. o.type = param->type;
  332. array_add(&operands, o);
  333. }
  334. }
  335. defer (if (param_operands == nullptr) {
  336. array_free(&operands);
  337. });
  338. CheckerContext nctx = *old_c;
  339. Scope *scope = create_scope(info, base_entity->scope);
  340. scope->flags |= ScopeFlag_Proc;
  341. nctx.scope = scope;
  342. nctx.allow_polymorphic_types = true;
  343. if (nctx.polymorphic_scope == nullptr) {
  344. nctx.polymorphic_scope = scope;
  345. }
  346. auto *pt = &src->Proc;
  347. // NOTE(bill): This is slightly memory leaking if the type already exists
  348. // Maybe it's better to check with the previous types first?
  349. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  350. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  351. if (!success) {
  352. return false;
  353. }
  354. GenProcsData *gen_procs = nullptr;
  355. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  356. GB_ASSERT(base_entity->kind == Entity_Procedure);
  357. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  358. gen_procs = base_entity->Procedure.gen_procs;
  359. if (gen_procs) {
  360. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  361. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  362. for (Entity *other : gen_procs->procs) {
  363. Type *pt = base_type(other->type);
  364. if (are_types_identical(pt, final_proc_type)) {
  365. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  366. if (poly_proc_data) {
  367. poly_proc_data->gen_entity = other;
  368. }
  369. return true;
  370. }
  371. }
  372. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  373. } else {
  374. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  375. gen_procs->procs.allocator = heap_allocator();
  376. base_entity->Procedure.gen_procs = gen_procs;
  377. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  378. }
  379. {
  380. // LEAK TODO(bill): This is technically a memory leak as it has to generate the type twice
  381. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  382. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  383. nctx.no_polymorphic_errors = false;
  384. // NOTE(bill): Reset scope from the failed procedure type
  385. scope_reset(scope);
  386. // LEAK TODO(bill): Cloning this AST may be leaky
  387. Ast *cloned_proc_type_node = clone_ast(pt->node);
  388. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  389. if (!success) {
  390. return false;
  391. }
  392. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  393. for (Entity *other : gen_procs->procs) {
  394. Type *pt = base_type(other->type);
  395. if (are_types_identical(pt, final_proc_type)) {
  396. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  397. if (poly_proc_data) {
  398. poly_proc_data->gen_entity = other;
  399. }
  400. DeclInfo *decl = other->decl_info;
  401. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  402. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  403. proc_info->file = other->file;
  404. proc_info->token = other->token;
  405. proc_info->decl = decl;
  406. proc_info->type = other->type;
  407. proc_info->body = decl->proc_lit->ProcLit.body;
  408. proc_info->tags = other->Procedure.tags;;
  409. proc_info->generated_from_polymorphic = true;
  410. proc_info->poly_def_node = poly_def_node;
  411. check_procedure_later(nctx.checker, proc_info);
  412. }
  413. return true;
  414. }
  415. }
  416. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  417. }
  418. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  419. ast_node(pl, ProcLit, proc_lit);
  420. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  421. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  422. final_proc_type->Proc.is_poly_specialized = true;
  423. final_proc_type->Proc.is_polymorphic = true;
  424. final_proc_type->Proc.variadic = src->Proc.variadic;
  425. final_proc_type->Proc.require_results = src->Proc.require_results;
  426. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  427. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  428. final_proc_type->Proc.diverging = src->Proc.diverging;
  429. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  430. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  431. for (isize i = 0; i < operands.count; i++) {
  432. Operand o = operands[i];
  433. if (final_proc_type == o.type ||
  434. base_entity->type == o.type) {
  435. // NOTE(bill): Cycle
  436. final_proc_type->Proc.is_poly_specialized = false;
  437. break;
  438. }
  439. }
  440. u64 tags = base_entity->Procedure.tags;
  441. Ast *ident = clone_ast(base_entity->identifier);
  442. Token token = ident->Ident.token;
  443. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  444. d->gen_proc_type = final_proc_type;
  445. d->type_expr = pl->type;
  446. d->proc_lit = proc_lit;
  447. d->proc_checked_state = ProcCheckedState_Unchecked;
  448. d->defer_use_checked = false;
  449. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  450. entity->identifier = ident;
  451. add_entity_and_decl_info(&nctx, ident, entity, d);
  452. // NOTE(bill): Set the scope afterwards as this is not real overloading
  453. entity->scope = scope->parent;
  454. entity->file = base_entity->file;
  455. entity->pkg = base_entity->pkg;
  456. entity->flags = 0;
  457. d->entity = entity;
  458. AstFile *file = nullptr;
  459. {
  460. Scope *s = entity->scope;
  461. while (s != nullptr && s->file == nullptr) {
  462. file = s->file;
  463. s = s->parent;
  464. }
  465. }
  466. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  467. array_add(&gen_procs->procs, entity);
  468. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  469. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  470. proc_info->file = file;
  471. proc_info->token = token;
  472. proc_info->decl = d;
  473. proc_info->type = final_proc_type;
  474. proc_info->body = pl->body;
  475. proc_info->tags = tags;
  476. proc_info->generated_from_polymorphic = true;
  477. proc_info->poly_def_node = poly_def_node;
  478. if (poly_proc_data) {
  479. poly_proc_data->gen_entity = entity;
  480. poly_proc_data->proc_info = proc_info;
  481. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  482. }
  483. // NOTE(bill): Check the newly generated procedure body
  484. check_procedure_later(nctx.checker, proc_info);
  485. return true;
  486. }
  487. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  488. if (operand->expr == nullptr) return false;
  489. Entity *base_entity = entity_of_node(operand->expr);
  490. if (base_entity == nullptr) return false;
  491. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  492. }
  493. gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  494. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  495. }
  496. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  497. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  498. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  499. #define MAXIMUM_TYPE_DISTANCE 10
  500. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  501. if (c == nullptr) {
  502. GB_ASSERT(operand->mode == Addressing_Value);
  503. GB_ASSERT(is_type_typed(operand->type));
  504. }
  505. if (operand->mode == Addressing_Invalid ||
  506. type == t_invalid) {
  507. return -1;
  508. }
  509. if (operand->mode == Addressing_Builtin) {
  510. return -1;
  511. }
  512. if (operand->mode == Addressing_Type) {
  513. if (is_type_typeid(type)) {
  514. add_type_info_type(c, operand->type);
  515. return 4;
  516. }
  517. return -1;
  518. }
  519. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  520. return -1;
  521. }
  522. Type *s = operand->type;
  523. if (are_types_identical(s, type)) {
  524. return 0;
  525. }
  526. Type *src = base_type(s);
  527. Type *dst = base_type(type);
  528. if (is_type_untyped_undef(src)) {
  529. if (type_has_undef(dst)) {
  530. return 1;
  531. }
  532. return -1;
  533. }
  534. if (is_type_untyped_nil(src)) {
  535. if (type_has_nil(dst)) {
  536. return 1;
  537. }
  538. return -1;
  539. }
  540. if (is_type_untyped(src)) {
  541. if (is_type_any(dst)) {
  542. // NOTE(bill): Anything can cast to 'Any'
  543. add_type_info_type(c, s);
  544. return MAXIMUM_TYPE_DISTANCE;
  545. }
  546. if (dst->kind == Type_Basic) {
  547. if (operand->mode == Addressing_Constant) {
  548. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  549. if (is_type_typed(dst) && src->kind == Type_Basic) {
  550. switch (src->Basic.kind) {
  551. case Basic_UntypedRune:
  552. if (is_type_integer(dst) || is_type_rune(dst)) {
  553. return 1;
  554. }
  555. break;
  556. case Basic_UntypedInteger:
  557. if (is_type_integer(dst) || is_type_rune(dst)) {
  558. return 1;
  559. }
  560. break;
  561. case Basic_UntypedFloat:
  562. if (is_type_float(dst)) {
  563. return 1;
  564. }
  565. break;
  566. case Basic_UntypedComplex:
  567. if (is_type_complex(dst)) {
  568. return 1;
  569. }
  570. if (is_type_quaternion(dst)) {
  571. return 2;
  572. }
  573. break;
  574. case Basic_UntypedQuaternion:
  575. if (is_type_quaternion(dst)) {
  576. return 1;
  577. }
  578. break;
  579. }
  580. }
  581. return 2;
  582. }
  583. return -1;
  584. }
  585. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedRune) {
  586. if (is_type_integer(dst) || is_type_rune(dst)) {
  587. if (is_type_typed(type)) {
  588. return 2;
  589. }
  590. return 1;
  591. }
  592. return -1;
  593. }
  594. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedBool) {
  595. if (is_type_boolean(dst)) {
  596. if (is_type_typed(type)) {
  597. return 2;
  598. }
  599. return 1;
  600. }
  601. return -1;
  602. }
  603. }
  604. }
  605. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  606. if (c->in_enum_type) {
  607. return 3;
  608. }
  609. }
  610. {
  611. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  612. if (subtype_level > 0) {
  613. return 4 + subtype_level;
  614. }
  615. }
  616. // ^T <- rawptr
  617. #if 0
  618. // TODO(bill): Should C-style (not C++) pointer cast be allowed?
  619. if (is_type_pointer(dst) && is_type_rawptr(src)) {
  620. return true;
  621. }
  622. #endif
  623. #if 1
  624. // rawptr <- ^T
  625. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  626. return 5;
  627. }
  628. // rawptr <- [^]T
  629. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  630. return 5;
  631. }
  632. // ^T <- [^]T
  633. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  634. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  635. return 4;
  636. }
  637. }
  638. // [^]T <- ^T
  639. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  640. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  641. return 4;
  642. }
  643. }
  644. #endif
  645. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  646. bool modify_type = !c->no_polymorphic_errors;
  647. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  648. return 2;
  649. }
  650. }
  651. if (is_type_union(dst)) {
  652. for (Type *vt : dst->Union.variants) {
  653. if (are_types_identical(vt, s)) {
  654. return 1;
  655. }
  656. }
  657. // TODO(bill): Determine which rule is a better on in practice
  658. if (dst->Union.variants.count == 1) {
  659. Type *vt = dst->Union.variants[0];
  660. i64 score = check_distance_between_types(c, operand, vt);
  661. if (score >= 0) {
  662. return score+2;
  663. }
  664. } else if (is_type_untyped(src)) {
  665. i64 prev_lowest_score = -1;
  666. i64 lowest_score = -1;
  667. for (Type *vt : dst->Union.variants) {
  668. i64 score = check_distance_between_types(c, operand, vt);
  669. if (score >= 0) {
  670. if (lowest_score < 0) {
  671. lowest_score = score;
  672. } else {
  673. if (prev_lowest_score < 0) {
  674. prev_lowest_score = lowest_score;
  675. } else {
  676. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  677. }
  678. lowest_score = gb_min(lowest_score, score);
  679. }
  680. }
  681. }
  682. if (lowest_score >= 0) {
  683. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  684. return lowest_score+2;
  685. }
  686. }
  687. }
  688. }
  689. if (is_type_relative_pointer(dst)) {
  690. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  691. if (score >= 0) {
  692. return score+2;
  693. }
  694. }
  695. if (is_type_relative_slice(dst)) {
  696. i64 score = check_distance_between_types(c, operand, dst->RelativeSlice.slice_type);
  697. if (score >= 0) {
  698. return score+2;
  699. }
  700. }
  701. if (is_type_proc(dst)) {
  702. if (are_types_identical(src, dst)) {
  703. return 3;
  704. }
  705. PolyProcData poly_proc_data = {};
  706. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  707. Entity *e = poly_proc_data.gen_entity;
  708. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  709. add_entity_use(c, operand->expr, e);
  710. return 4;
  711. }
  712. }
  713. if (is_type_complex_or_quaternion(dst)) {
  714. Type *elem = base_complex_elem_type(dst);
  715. if (are_types_identical(elem, base_type(src))) {
  716. return 5;
  717. }
  718. }
  719. if (is_type_array(dst)) {
  720. Type *elem = base_array_type(dst);
  721. i64 distance = check_distance_between_types(c, operand, elem);
  722. if (distance >= 0) {
  723. return distance + 6;
  724. }
  725. }
  726. if (is_type_simd_vector(dst)) {
  727. Type *dst_elem = base_array_type(dst);
  728. i64 distance = check_distance_between_types(c, operand, dst_elem);
  729. if (distance >= 0) {
  730. return distance + 6;
  731. }
  732. }
  733. if (is_type_matrix(dst)) {
  734. if (are_types_identical(src, dst)) {
  735. return 5;
  736. }
  737. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  738. Type *dst_elem = base_array_type(dst);
  739. i64 distance = check_distance_between_types(c, operand, dst_elem);
  740. if (distance >= 0) {
  741. return distance + 7;
  742. }
  743. }
  744. }
  745. if (is_type_any(dst)) {
  746. if (!is_type_polymorphic(src)) {
  747. if (operand->mode == Addressing_Context && operand->type == t_context) {
  748. return -1;
  749. } else {
  750. // NOTE(bill): Anything can cast to 'Any'
  751. add_type_info_type(c, s);
  752. return MAXIMUM_TYPE_DISTANCE;
  753. }
  754. }
  755. }
  756. Ast *expr = unparen_expr(operand->expr);
  757. if (expr != nullptr) {
  758. if (expr->kind == Ast_AutoCast) {
  759. Operand x = *operand;
  760. x.expr = expr->AutoCast.expr;
  761. if (check_cast_internal(c, &x, type)) {
  762. return MAXIMUM_TYPE_DISTANCE;
  763. }
  764. }
  765. }
  766. return -1;
  767. }
  768. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  769. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  770. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  771. // TODO(bill): A decent score function
  772. i64 d = distance*distance; // x^2
  773. if (is_variadic && d >= 0) {
  774. d += distance + 1; // x^2 + x + 1
  775. }
  776. return gb_max(c - d, 0);
  777. }
  778. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  779. i64 score = 0;
  780. i64 distance = check_distance_between_types(c, operand, type);
  781. bool ok = distance >= 0;
  782. if (ok) {
  783. score = assign_score_function(distance, is_variadic);
  784. }
  785. if (score_) *score_ = score;
  786. return ok;
  787. }
  788. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  789. i64 score = 0;
  790. return check_is_assignable_to_with_score(c, operand, type, &score);
  791. }
  792. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  793. Operand x = {};
  794. x.type = src;
  795. x.mode = Addressing_Value;
  796. return check_is_assignable_to(nullptr, &x, dst);
  797. }
  798. gb_internal AstPackage *get_package_of_type(Type *type) {
  799. for (;;) {
  800. if (type == nullptr) {
  801. return nullptr;
  802. }
  803. switch (type->kind) {
  804. case Type_Basic:
  805. return builtin_pkg;
  806. case Type_Named:
  807. if (type->Named.type_name != nullptr) {
  808. return type->Named.type_name->pkg;
  809. }
  810. return nullptr;
  811. case Type_Pointer:
  812. type = type->Pointer.elem;
  813. continue;
  814. case Type_Array:
  815. type = type->Array.elem;
  816. continue;
  817. case Type_Slice:
  818. type = type->Slice.elem;
  819. continue;
  820. case Type_DynamicArray:
  821. type = type->DynamicArray.elem;
  822. continue;
  823. case Type_RelativePointer:
  824. type = type->RelativePointer.pointer_type;
  825. continue;
  826. case Type_RelativeSlice:
  827. type = type->RelativeSlice.slice_type;
  828. continue;
  829. }
  830. return nullptr;
  831. }
  832. }
  833. // NOTE(bill): 'content_name' is for debugging and error messages
  834. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  835. check_not_tuple(c, operand);
  836. if (operand->mode == Addressing_Invalid) {
  837. return;
  838. }
  839. if (is_type_untyped(operand->type)) {
  840. Type *target_type = type;
  841. if (type == nullptr || is_type_any(type)) {
  842. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  843. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  844. operand->mode = Addressing_Invalid;
  845. return;
  846. }
  847. if (type == nullptr && is_type_untyped_undef(operand->type)) {
  848. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  849. operand->mode = Addressing_Invalid;
  850. return;
  851. }
  852. target_type = default_type(operand->type);
  853. if (type != nullptr && !is_type_any(type)) {
  854. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  855. }
  856. add_type_info_type(c, type);
  857. add_type_info_type(c, target_type);
  858. }
  859. convert_to_typed(c, operand, target_type);
  860. if (operand->mode == Addressing_Invalid) {
  861. return;
  862. }
  863. }
  864. if (type == nullptr) {
  865. return;
  866. }
  867. if (operand->mode == Addressing_ProcGroup) {
  868. bool good = false;
  869. if (type != nullptr && is_type_proc(type)) {
  870. Array<Entity *> procs = proc_group_entities(c, *operand);
  871. // NOTE(bill): These should be done
  872. for (Entity *e : procs) {
  873. Type *t = base_type(e->type);
  874. if (t == t_invalid) {
  875. continue;
  876. }
  877. Operand x = {};
  878. x.mode = Addressing_Value;
  879. x.type = t;
  880. if (check_is_assignable_to(c, &x, type)) {
  881. add_entity_use(c, operand->expr, e);
  882. good = true;
  883. break;
  884. }
  885. }
  886. }
  887. if (!good) {
  888. gbString expr_str = expr_to_string(operand->expr);
  889. gbString op_type_str = type_to_string(operand->type);
  890. gbString type_str = type_to_string(type);
  891. defer (gb_string_free(type_str));
  892. defer (gb_string_free(op_type_str));
  893. defer (gb_string_free(expr_str));
  894. // TODO(bill): is this a good enough error message?
  895. error(operand->expr,
  896. "Cannot assign overloaded procedure '%s' to '%s' in %.*s",
  897. expr_str,
  898. op_type_str,
  899. LIT(context_name));
  900. operand->mode = Addressing_Invalid;
  901. }
  902. convert_to_typed(c, operand, type);
  903. return;
  904. }
  905. if (check_is_assignable_to(c, operand, type)) {
  906. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  907. add_type_info_type(c, operand->type);
  908. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  909. }
  910. } else {
  911. gbString expr_str = expr_to_string(operand->expr);
  912. gbString op_type_str = type_to_string(operand->type);
  913. gbString type_str = type_to_string(type);
  914. defer (gb_string_free(type_str));
  915. defer (gb_string_free(op_type_str));
  916. defer (gb_string_free(expr_str));
  917. switch (operand->mode) {
  918. case Addressing_Builtin:
  919. // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use
  920. error(operand->expr,
  921. "Cannot assign built-in procedure '%s' in %.*s",
  922. expr_str,
  923. LIT(context_name));
  924. break;
  925. case Addressing_Type:
  926. error(operand->expr,
  927. "Cannot assign '%s' which is a type in %.*s",
  928. op_type_str,
  929. LIT(context_name));
  930. break;
  931. default:
  932. // TODO(bill): is this a good enough error message?
  933. {
  934. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  935. gbString type_extra = gb_string_make(heap_allocator(), "");
  936. defer (gb_string_free(op_type_extra));
  937. defer (gb_string_free(type_extra));
  938. isize on = gb_string_length(op_type_str);
  939. isize tn = gb_string_length(type_str);
  940. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  941. AstPackage *op_pkg = get_package_of_type(operand->type);
  942. AstPackage *type_pkg = get_package_of_type(type);
  943. if (op_pkg != nullptr) {
  944. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  945. }
  946. if (type_pkg != nullptr) {
  947. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  948. }
  949. }
  950. ERROR_BLOCK();
  951. error(operand->expr,
  952. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  953. expr_str,
  954. op_type_str, op_type_extra,
  955. type_str, type_extra,
  956. LIT(context_name));
  957. check_assignment_error_suggestion(c, operand, type);
  958. }
  959. break;
  960. }
  961. operand->mode = Addressing_Invalid;
  962. return;
  963. }
  964. }
  965. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  966. Type *gt = *gt_;
  967. GB_ASSERT(gt->kind == Type_Generic);
  968. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  969. GB_ASSERT(e != nullptr);
  970. if (e->kind == Entity_TypeName) {
  971. *gt_ = nullptr;
  972. *dst_count = source_count;
  973. e->kind = Entity_Constant;
  974. e->Constant.value = exact_value_i64(source_count);
  975. e->type = t_untyped_integer;
  976. return true;
  977. } else if (e->kind == Entity_Constant) {
  978. *gt_ = nullptr;
  979. if (e->Constant.value.kind != ExactValue_Integer) {
  980. return false;
  981. }
  982. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  983. if (count != source_count) {
  984. return false;
  985. }
  986. *dst_count = source_count;
  987. return true;
  988. }
  989. return false;
  990. }
  991. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  992. Operand o = {Addressing_Value};
  993. o.type = source;
  994. switch (poly->kind) {
  995. case Type_Basic:
  996. if (compound) return are_types_identical(poly, source);
  997. return check_is_assignable_to(c, &o, poly);
  998. case Type_Named: {
  999. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1000. return true;
  1001. }
  1002. if (compound || !is_type_generic(poly)) {
  1003. return are_types_identical(poly, source);
  1004. }
  1005. return check_is_assignable_to(c, &o, poly);
  1006. }
  1007. case Type_Generic: {
  1008. if (poly->Generic.specialized != nullptr) {
  1009. Type *s = poly->Generic.specialized;
  1010. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1011. return false;
  1012. }
  1013. }
  1014. if (modify_type) {
  1015. Type *ds = default_type(source);
  1016. gb_memmove(poly, ds, gb_size_of(Type));
  1017. }
  1018. return true;
  1019. }
  1020. case Type_Pointer:
  1021. if (source->kind == Type_Pointer) {
  1022. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem);
  1023. if (level > 0) {
  1024. return true;
  1025. }
  1026. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1027. } else if (source->kind == Type_MultiPointer) {
  1028. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1029. if (level > 0) {
  1030. return true;
  1031. }
  1032. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1033. }
  1034. return false;
  1035. case Type_MultiPointer:
  1036. if (source->kind == Type_MultiPointer) {
  1037. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1038. if (level > 0) {
  1039. return true;
  1040. }
  1041. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1042. } else if (source->kind == Type_Pointer) {
  1043. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1044. if (level > 0) {
  1045. return true;
  1046. }
  1047. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1048. }
  1049. return false;
  1050. case Type_Array:
  1051. if (source->kind == Type_Array) {
  1052. if (poly->Array.generic_count != nullptr) {
  1053. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1054. return false;
  1055. }
  1056. }
  1057. if (poly->Array.count == source->Array.count) {
  1058. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1059. }
  1060. } else if (source->kind == Type_EnumeratedArray) {
  1061. if (poly->Array.generic_count != nullptr) {
  1062. Type *gt = poly->Array.generic_count;
  1063. GB_ASSERT(gt->kind == Type_Generic);
  1064. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1065. GB_ASSERT(e != nullptr);
  1066. if (e->kind == Entity_TypeName) {
  1067. Type *index = source->EnumeratedArray.index;
  1068. Type *it = base_type(index);
  1069. if (it->kind != Type_Enum) {
  1070. return false;
  1071. }
  1072. poly->kind = Type_EnumeratedArray;
  1073. poly->cached_size = -1;
  1074. poly->cached_align = -1;
  1075. poly->flags.exchange(source->flags);
  1076. poly->failure = false;
  1077. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1078. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1079. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1080. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1081. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1082. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1083. e->kind = Entity_TypeName;
  1084. e->TypeName.is_type_alias = true;
  1085. e->type = index;
  1086. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1087. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1088. }
  1089. }
  1090. }
  1091. }
  1092. return false;
  1093. case Type_EnumeratedArray:
  1094. if (source->kind == Type_EnumeratedArray) {
  1095. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1096. return false;
  1097. }
  1098. if (poly->EnumeratedArray.op) {
  1099. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1100. return false;
  1101. }
  1102. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1103. return false;
  1104. }
  1105. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1106. return false;
  1107. }
  1108. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1109. }
  1110. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1111. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1112. return index || elem;
  1113. }
  1114. return false;
  1115. case Type_DynamicArray:
  1116. if (source->kind == Type_DynamicArray) {
  1117. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1118. }
  1119. return false;
  1120. case Type_Slice:
  1121. if (source->kind == Type_Slice) {
  1122. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1123. }
  1124. return false;
  1125. case Type_Enum:
  1126. return false;
  1127. case Type_BitSet:
  1128. if (source->kind == Type_BitSet) {
  1129. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1130. return false;
  1131. }
  1132. if (poly->BitSet.underlying == nullptr) {
  1133. if (modify_type) {
  1134. poly->BitSet.underlying = source->BitSet.underlying;
  1135. }
  1136. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1137. return false;
  1138. }
  1139. return true;
  1140. }
  1141. return false;
  1142. case Type_Union:
  1143. if (source->kind == Type_Union) {
  1144. TypeUnion *x = &poly->Union;
  1145. TypeUnion *y = &source->Union;
  1146. if (x->variants.count != y->variants.count) {
  1147. return false;
  1148. }
  1149. for_array(i, x->variants) {
  1150. Type *a = x->variants[i];
  1151. Type *b = y->variants[i];
  1152. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1153. if (!ok) return false;
  1154. }
  1155. return true;
  1156. }
  1157. return false;
  1158. case Type_Struct:
  1159. if (source->kind == Type_Struct) {
  1160. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1161. poly->Struct.soa_kind != StructSoa_None) {
  1162. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1163. if (ok) switch (source->Struct.soa_kind) {
  1164. case StructSoa_Fixed:
  1165. default:
  1166. GB_PANIC("Unhandled SOA Kind");
  1167. break;
  1168. case StructSoa_Slice:
  1169. if (modify_type) {
  1170. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1171. gb_memmove(poly, type, gb_size_of(*type));
  1172. }
  1173. break;
  1174. case StructSoa_Dynamic:
  1175. if (modify_type) {
  1176. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1177. gb_memmove(poly, type, gb_size_of(*type));
  1178. }
  1179. break;
  1180. }
  1181. return ok;
  1182. }
  1183. // return check_is_assignable_to(c, &o, poly);
  1184. }
  1185. return false;
  1186. case Type_Tuple:
  1187. GB_PANIC("This should never happen");
  1188. return false;
  1189. case Type_Proc:
  1190. if (source->kind == Type_Proc) {
  1191. // return check_is_assignable_to(c, &o, poly);
  1192. // TODO(bill): Polymorphic type assignment
  1193. #if 1
  1194. TypeProc *x = &poly->Proc;
  1195. TypeProc *y = &source->Proc;
  1196. if (x->calling_convention != y->calling_convention) {
  1197. return false;
  1198. }
  1199. if (x->c_vararg != y->c_vararg) {
  1200. return false;
  1201. }
  1202. if (x->variadic != y->variadic) {
  1203. return false;
  1204. }
  1205. if (x->param_count != y->param_count) {
  1206. return false;
  1207. }
  1208. if (x->result_count != y->result_count) {
  1209. return false;
  1210. }
  1211. for (isize i = 0; i < x->param_count; i++) {
  1212. Entity *a = x->params->Tuple.variables[i];
  1213. Entity *b = y->params->Tuple.variables[i];
  1214. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1215. if (!ok) return false;
  1216. }
  1217. for (isize i = 0; i < x->result_count; i++) {
  1218. Entity *a = x->results->Tuple.variables[i];
  1219. Entity *b = y->results->Tuple.variables[i];
  1220. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1221. if (!ok) return false;
  1222. }
  1223. return true;
  1224. #endif
  1225. }
  1226. return false;
  1227. case Type_Map:
  1228. if (source->kind == Type_Map) {
  1229. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1230. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1231. if (key || value) {
  1232. poly->Map.lookup_result_type = nullptr;
  1233. init_map_internal_types(poly);
  1234. return true;
  1235. }
  1236. }
  1237. return false;
  1238. case Type_Matrix:
  1239. if (source->kind == Type_Matrix) {
  1240. if (poly->Matrix.generic_row_count != nullptr) {
  1241. poly->Matrix.stride_in_bytes = 0;
  1242. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1243. return false;
  1244. }
  1245. }
  1246. if (poly->Matrix.generic_column_count != nullptr) {
  1247. poly->Matrix.stride_in_bytes = 0;
  1248. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1249. return false;
  1250. }
  1251. }
  1252. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1253. poly->Matrix.column_count == source->Matrix.column_count) {
  1254. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1255. }
  1256. }
  1257. return false;
  1258. case Type_SimdVector:
  1259. if (source->kind == Type_SimdVector) {
  1260. if (poly->SimdVector.generic_count != nullptr) {
  1261. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1262. return false;
  1263. }
  1264. }
  1265. if (poly->SimdVector.count == source->SimdVector.count) {
  1266. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1267. }
  1268. }
  1269. return false;
  1270. }
  1271. return false;
  1272. }
  1273. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1274. if (curr->state != EntityState_InProgress) {
  1275. return false;
  1276. }
  1277. for_array(i, *c->type_path) {
  1278. Entity *prev = c->type_path->data[i];
  1279. if (prev == curr) {
  1280. if (report) {
  1281. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1282. for (isize j = i; j < c->type_path->count; j++) {
  1283. Entity *curr = (*c->type_path)[j];
  1284. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1285. }
  1286. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1287. curr->type = t_invalid;
  1288. }
  1289. return true;
  1290. }
  1291. }
  1292. return false;
  1293. }
  1294. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1295. GB_ASSERT(n->kind == Ast_Ident);
  1296. o->mode = Addressing_Invalid;
  1297. o->expr = n;
  1298. String name = n->Ident.token.string;
  1299. Entity *e = scope_lookup(c->scope, name);
  1300. if (e == nullptr) {
  1301. if (is_blank_ident(name)) {
  1302. error(n, "'_' cannot be used as a value");
  1303. } else {
  1304. error(n, "Undeclared name: %.*s", LIT(name));
  1305. }
  1306. o->type = t_invalid;
  1307. o->mode = Addressing_Invalid;
  1308. if (named_type != nullptr) {
  1309. set_base_type(named_type, t_invalid);
  1310. }
  1311. return nullptr;
  1312. }
  1313. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1314. if (e->parent_proc_decl != nullptr &&
  1315. e->parent_proc_decl != c->curr_proc_decl) {
  1316. if (e->kind == Entity_Variable) {
  1317. if ((e->flags & EntityFlag_Static) == 0) {
  1318. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1319. return nullptr;
  1320. }
  1321. } else if (e->kind == Entity_Label) {
  1322. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1323. return nullptr;
  1324. }
  1325. }
  1326. if (e->kind == Entity_ProcGroup) {
  1327. auto *pge = &e->ProcGroup;
  1328. DeclInfo *d = decl_info_of_entity(e);
  1329. check_entity_decl(c, e, d, nullptr);
  1330. Array<Entity *> procs = pge->entities;
  1331. bool skip = false;
  1332. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1333. // NOTE(bill): These should be done
  1334. for (Entity *proc : procs) {
  1335. Type *t = base_type(proc->type);
  1336. if (t == t_invalid) {
  1337. continue;
  1338. }
  1339. Operand x = {};
  1340. x.mode = Addressing_Value;
  1341. x.type = t;
  1342. if (check_is_assignable_to(c, &x, type_hint)) {
  1343. e = proc;
  1344. add_entity_use(c, n, e);
  1345. skip = true;
  1346. break;
  1347. }
  1348. }
  1349. }
  1350. if (!skip) {
  1351. o->mode = Addressing_ProcGroup;
  1352. o->type = t_invalid;
  1353. o->proc_group = e;
  1354. return nullptr;
  1355. }
  1356. }
  1357. add_entity_use(c, n, e);
  1358. if (e->state == EntityState_Unresolved) {
  1359. check_entity_decl(c, e, nullptr, named_type);
  1360. }
  1361. if (e->type == nullptr) {
  1362. // TODO(bill): Which is correct? return or compiler_error?
  1363. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1364. return nullptr;
  1365. }
  1366. e->flags |= EntityFlag_Used;
  1367. Type *type = e->type;
  1368. o->type = type;
  1369. switch (e->kind) {
  1370. case Entity_Constant:
  1371. if (type == t_invalid) {
  1372. o->type = t_invalid;
  1373. return e;
  1374. }
  1375. o->value = e->Constant.value;
  1376. if (o->value.kind == ExactValue_Invalid) {
  1377. return e;
  1378. }
  1379. if (o->value.kind == ExactValue_Procedure) {
  1380. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1381. if (proc != nullptr) {
  1382. o->mode = Addressing_Value;
  1383. o->type = proc->type;
  1384. return proc;
  1385. }
  1386. }
  1387. o->mode = Addressing_Constant;
  1388. break;
  1389. case Entity_Variable:
  1390. e->flags |= EntityFlag_Used;
  1391. if (type == t_invalid) {
  1392. o->type = t_invalid;
  1393. return e;
  1394. }
  1395. o->mode = Addressing_Variable;
  1396. if (e->flags & EntityFlag_Value) {
  1397. o->mode = Addressing_Value;
  1398. }
  1399. break;
  1400. case Entity_Procedure:
  1401. o->mode = Addressing_Value;
  1402. o->value = exact_value_procedure(n);
  1403. break;
  1404. case Entity_Builtin:
  1405. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1406. o->mode = Addressing_Builtin;
  1407. break;
  1408. case Entity_TypeName:
  1409. o->mode = Addressing_Type;
  1410. if (check_cycle(c, e, true)) {
  1411. o->type = t_invalid;
  1412. }
  1413. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1414. o->type = base_type(o->type);
  1415. }
  1416. break;
  1417. case Entity_ImportName:
  1418. if (!allow_import_name) {
  1419. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1420. }
  1421. return e;
  1422. case Entity_LibraryName:
  1423. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1424. return e;
  1425. case Entity_Label:
  1426. o->mode = Addressing_NoValue;
  1427. break;
  1428. case Entity_Nil:
  1429. o->mode = Addressing_Value;
  1430. break;
  1431. default:
  1432. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1433. break;
  1434. }
  1435. return e;
  1436. }
  1437. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1438. if (o->type == nullptr) {
  1439. gbString str = expr_to_string(o->expr);
  1440. error(o->expr, "Expression has no value '%s'", str);
  1441. gb_string_free(str);
  1442. return false;
  1443. }
  1444. // TODO(bill): Handle errors correctly
  1445. Type *type = base_type(core_array_type(o->type));
  1446. gbString str = nullptr;
  1447. switch (op.kind) {
  1448. case Token_Add:
  1449. case Token_Sub:
  1450. if (!is_type_numeric(type)) {
  1451. str = expr_to_string(o->expr);
  1452. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1453. gb_string_free(str);
  1454. }
  1455. break;
  1456. case Token_Xor:
  1457. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1458. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1459. }
  1460. break;
  1461. case Token_Not:
  1462. if (!is_type_boolean(type)) {
  1463. ERROR_BLOCK();
  1464. str = expr_to_string(o->expr);
  1465. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1466. gb_string_free(str);
  1467. if (is_type_integer(type)) {
  1468. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1469. }
  1470. }
  1471. break;
  1472. default:
  1473. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1474. return false;
  1475. }
  1476. return true;
  1477. }
  1478. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1479. Type *main_type = o->type;
  1480. // TODO(bill): Handle errors correctly
  1481. Type *type = base_type(core_array_type(main_type));
  1482. Type *ct = core_type(type);
  1483. switch (op.kind) {
  1484. case Token_Sub:
  1485. case Token_SubEq:
  1486. if (is_type_bit_set(type)) {
  1487. return true;
  1488. } else if (!is_type_numeric(type)) {
  1489. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1490. return false;
  1491. }
  1492. break;
  1493. case Token_Quo:
  1494. case Token_QuoEq:
  1495. if (is_type_matrix(main_type)) {
  1496. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1497. return false;
  1498. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1499. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1500. return false;
  1501. }
  1502. /*fallthrough*/
  1503. case Token_Mul:
  1504. case Token_MulEq:
  1505. case Token_AddEq:
  1506. if (is_type_bit_set(type)) {
  1507. return true;
  1508. } else if (!is_type_numeric(type)) {
  1509. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1510. return false;
  1511. }
  1512. break;
  1513. case Token_Add:
  1514. if (is_type_string(type)) {
  1515. if (o->mode == Addressing_Constant) {
  1516. return true;
  1517. }
  1518. error(op, "String concatenation is only allowed with constant strings");
  1519. return false;
  1520. } else if (is_type_bit_set(type)) {
  1521. return true;
  1522. } else if (!is_type_numeric(type)) {
  1523. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1524. return false;
  1525. }
  1526. break;
  1527. case Token_And:
  1528. case Token_Or:
  1529. case Token_AndEq:
  1530. case Token_OrEq:
  1531. case Token_Xor:
  1532. case Token_XorEq:
  1533. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1534. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1535. return false;
  1536. }
  1537. break;
  1538. case Token_Mod:
  1539. case Token_ModMod:
  1540. case Token_ModEq:
  1541. case Token_ModModEq:
  1542. if (is_type_matrix(main_type)) {
  1543. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1544. return false;
  1545. }
  1546. if (!is_type_integer(type)) {
  1547. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1548. return false;
  1549. } else if (is_type_simd_vector(main_type)) {
  1550. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1551. return false;
  1552. }
  1553. break;
  1554. case Token_AndNot:
  1555. case Token_AndNotEq:
  1556. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1557. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1558. return false;
  1559. }
  1560. break;
  1561. case Token_CmpAnd:
  1562. case Token_CmpOr:
  1563. case Token_CmpAndEq:
  1564. case Token_CmpOrEq:
  1565. if (!is_type_boolean(type)) {
  1566. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1567. return false;
  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_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1577. if (in_value.kind == ExactValue_Invalid) {
  1578. // NOTE(bill): There's already been an error
  1579. return true;
  1580. }
  1581. type = core_type(type);
  1582. if (type == t_invalid) {
  1583. return false;
  1584. } else if (is_type_boolean(type)) {
  1585. return in_value.kind == ExactValue_Bool;
  1586. } else if (is_type_string(type)) {
  1587. return in_value.kind == ExactValue_String;
  1588. } else if (is_type_integer(type) || is_type_rune(type)) {
  1589. if (in_value.kind == ExactValue_Bool) {
  1590. return false;
  1591. }
  1592. ExactValue v = exact_value_to_integer(in_value);
  1593. if (v.kind != ExactValue_Integer) {
  1594. return false;
  1595. }
  1596. if (out_value) *out_value = v;
  1597. if (is_type_untyped(type)) {
  1598. return true;
  1599. }
  1600. BigInt i = v.value_integer;
  1601. i64 bit_size = type_size_of(type);
  1602. BigInt umax = {};
  1603. BigInt imin = {};
  1604. BigInt imax = {};
  1605. if (bit_size < 16) {
  1606. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1607. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1608. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1609. } else {
  1610. big_int_from_u64(&umax, 1);
  1611. big_int_from_i64(&imin, 1);
  1612. big_int_from_i64(&imax, 1);
  1613. BigInt bi128 = {};
  1614. BigInt bi127 = {};
  1615. big_int_from_i64(&bi128, 128);
  1616. big_int_from_i64(&bi127, 127);
  1617. big_int_shl_eq(&umax, &bi128);
  1618. mp_decr(&umax);
  1619. big_int_shl_eq(&imin, &bi127);
  1620. big_int_neg(&imin, &imin);
  1621. big_int_shl_eq(&imax, &bi127);
  1622. mp_decr(&imax);
  1623. }
  1624. switch (type->Basic.kind) {
  1625. case Basic_rune:
  1626. case Basic_i8:
  1627. case Basic_i16:
  1628. case Basic_i32:
  1629. case Basic_i64:
  1630. case Basic_i128:
  1631. case Basic_int:
  1632. case Basic_i16le:
  1633. case Basic_i32le:
  1634. case Basic_i64le:
  1635. case Basic_i128le:
  1636. case Basic_i16be:
  1637. case Basic_i32be:
  1638. case Basic_i64be:
  1639. case Basic_i128be:
  1640. {
  1641. // return imin <= i && i <= imax;
  1642. int a = big_int_cmp(&imin, &i);
  1643. int b = big_int_cmp(&i, &imax);
  1644. return (a <= 0) && (b <= 0);
  1645. }
  1646. case Basic_u8:
  1647. case Basic_u16:
  1648. case Basic_u32:
  1649. case Basic_u64:
  1650. case Basic_u128:
  1651. case Basic_uint:
  1652. case Basic_uintptr:
  1653. case Basic_u16le:
  1654. case Basic_u32le:
  1655. case Basic_u64le:
  1656. case Basic_u128le:
  1657. case Basic_u16be:
  1658. case Basic_u32be:
  1659. case Basic_u64be:
  1660. case Basic_u128be:
  1661. {
  1662. // return 0ull <= i && i <= umax;
  1663. int b = big_int_cmp(&i, &umax);
  1664. return !i.sign && (b <= 0);
  1665. }
  1666. case Basic_UntypedInteger:
  1667. return true;
  1668. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1669. }
  1670. } else if (is_type_float(type)) {
  1671. ExactValue v = exact_value_to_float(in_value);
  1672. if (v.kind != ExactValue_Float) {
  1673. return false;
  1674. }
  1675. if (out_value) *out_value = v;
  1676. switch (type->Basic.kind) {
  1677. case Basic_f16:
  1678. case Basic_f32:
  1679. case Basic_f64:
  1680. return true;
  1681. case Basic_f16le:
  1682. case Basic_f16be:
  1683. case Basic_f32le:
  1684. case Basic_f32be:
  1685. case Basic_f64le:
  1686. case Basic_f64be:
  1687. return true;
  1688. case Basic_UntypedFloat:
  1689. return true;
  1690. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1691. }
  1692. } else if (is_type_complex(type)) {
  1693. ExactValue v = exact_value_to_complex(in_value);
  1694. if (v.kind != ExactValue_Complex) {
  1695. return false;
  1696. }
  1697. switch (type->Basic.kind) {
  1698. case Basic_complex32:
  1699. case Basic_complex64:
  1700. case Basic_complex128: {
  1701. ExactValue real = exact_value_real(v);
  1702. ExactValue imag = exact_value_imag(v);
  1703. if (real.kind != ExactValue_Invalid &&
  1704. imag.kind != ExactValue_Invalid) {
  1705. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1706. return true;
  1707. }
  1708. break;
  1709. }
  1710. case Basic_UntypedComplex:
  1711. return true;
  1712. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1713. }
  1714. return false;
  1715. } else if (is_type_quaternion(type)) {
  1716. ExactValue v = exact_value_to_quaternion(in_value);
  1717. if (v.kind != ExactValue_Quaternion) {
  1718. return false;
  1719. }
  1720. switch (type->Basic.kind) {
  1721. case Basic_quaternion64:
  1722. case Basic_quaternion128:
  1723. case Basic_quaternion256: {
  1724. ExactValue real = exact_value_real(v);
  1725. ExactValue imag = exact_value_imag(v);
  1726. ExactValue jmag = exact_value_jmag(v);
  1727. ExactValue kmag = exact_value_kmag(v);
  1728. if (real.kind != ExactValue_Invalid &&
  1729. imag.kind != ExactValue_Invalid) {
  1730. 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));
  1731. return true;
  1732. }
  1733. break;
  1734. }
  1735. case Basic_UntypedComplex:
  1736. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1737. return true;
  1738. case Basic_UntypedQuaternion:
  1739. return true;
  1740. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1741. }
  1742. return false;
  1743. } else if (is_type_pointer(type)) {
  1744. if (in_value.kind == ExactValue_Pointer) {
  1745. return true;
  1746. }
  1747. if (in_value.kind == ExactValue_Integer) {
  1748. return false;
  1749. // return true;
  1750. }
  1751. if (in_value.kind == ExactValue_String) {
  1752. return false;
  1753. }
  1754. if (out_value) *out_value = in_value;
  1755. } else if (is_type_bit_set(type)) {
  1756. if (in_value.kind == ExactValue_Integer) {
  1757. return true;
  1758. }
  1759. }
  1760. return false;
  1761. }
  1762. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1763. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1764. gbString b = type_to_string(type);
  1765. i64 sz = type_size_of(type);
  1766. BigInt *bi = &o->value.value_integer;
  1767. if (is_type_unsigned(type)) {
  1768. if (big_int_is_neg(bi)) {
  1769. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1770. } else {
  1771. BigInt one = big_int_make_u64(1);
  1772. BigInt max_size = big_int_make_u64(1);
  1773. BigInt bits = big_int_make_i64(8*sz);
  1774. big_int_shl_eq(&max_size, &bits);
  1775. big_int_sub_eq(&max_size, &one);
  1776. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1777. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1778. }
  1779. } else {
  1780. BigInt zero = big_int_make_u64(0);
  1781. BigInt one = big_int_make_u64(1);
  1782. BigInt max_size = big_int_make_u64(1);
  1783. BigInt bits = big_int_make_i64(8*sz - 1);
  1784. big_int_shl_eq(&max_size, &bits);
  1785. if (big_int_is_neg(bi)) {
  1786. big_int_neg(&max_size, &max_size);
  1787. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1788. error_line("\tThe minimum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1789. } else {
  1790. big_int_sub_eq(&max_size, &one);
  1791. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1792. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1793. }
  1794. }
  1795. gb_string_free(b);
  1796. return true;
  1797. }
  1798. return false;
  1799. }
  1800. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1801. gbString a = expr_to_string(o->expr);
  1802. gbString b = type_to_string(type);
  1803. defer(
  1804. gb_string_free(b);
  1805. gb_string_free(a);
  1806. );
  1807. Type *src = base_type(o->type);
  1808. Type *dst = base_type(type);
  1809. if (is_type_array(src) && is_type_slice(dst)) {
  1810. Type *s = src->Array.elem;
  1811. Type *d = dst->Slice.elem;
  1812. if (are_types_identical(s, d)) {
  1813. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1814. }
  1815. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1816. Type *s = src->DynamicArray.elem;
  1817. Type *d = dst->Slice.elem;
  1818. if (are_types_identical(s, d)) {
  1819. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1820. }
  1821. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1822. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1823. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1824. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1825. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1826. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1827. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1828. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1829. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1830. return;
  1831. }
  1832. }
  1833. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1834. gbString a = expr_to_string(o->expr);
  1835. gbString b = type_to_string(type);
  1836. defer(
  1837. gb_string_free(b);
  1838. gb_string_free(a);
  1839. );
  1840. Type *src = base_type(o->type);
  1841. Type *dst = base_type(type);
  1842. if (is_type_array(src) && is_type_slice(dst)) {
  1843. Type *s = src->Array.elem;
  1844. Type *d = dst->Slice.elem;
  1845. if (are_types_identical(s, d)) {
  1846. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1847. }
  1848. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1849. if (is_type_uintptr(type)) {
  1850. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1851. } else {
  1852. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1853. i64 x = type_size_of(o->type);
  1854. i64 y = type_size_of(type);
  1855. if (x != y) {
  1856. 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);
  1857. }
  1858. }
  1859. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  1860. if (is_type_uintptr(o->type)) {
  1861. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  1862. } else {
  1863. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  1864. }
  1865. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1866. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1867. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1868. return;
  1869. }
  1870. }
  1871. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  1872. GB_ASSERT(o->mode == Addressing_Constant);
  1873. ExactValue out_value = o->value;
  1874. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  1875. o->value = out_value;
  1876. return true;
  1877. } else {
  1878. o->value = out_value;
  1879. gbString a = expr_to_string(o->expr);
  1880. gbString b = type_to_string(type);
  1881. gbString c = type_to_string(o->type);
  1882. gbString s = exact_value_to_string(o->value);
  1883. defer(
  1884. gb_string_free(s);
  1885. gb_string_free(c);
  1886. gb_string_free(b);
  1887. gb_string_free(a);
  1888. o->mode = Addressing_Invalid;
  1889. );
  1890. ERROR_BLOCK();
  1891. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1892. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1893. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  1894. } else {
  1895. if (are_types_identical(o->type, type)) {
  1896. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  1897. } else {
  1898. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  1899. }
  1900. check_assignment_error_suggestion(ctx, o, type);
  1901. }
  1902. } else {
  1903. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  1904. check_assignment_error_suggestion(ctx, o, type);
  1905. }
  1906. return false;
  1907. }
  1908. }
  1909. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1910. if (o->mode == Addressing_OptionalOk) {
  1911. Ast *expr = unselector_expr(o->expr);
  1912. if (expr->kind != Ast_TypeAssertion) {
  1913. return true;
  1914. }
  1915. ast_node(ta, TypeAssertion, expr);
  1916. TypeAndValue tv = ta->expr->tav;
  1917. if (is_type_pointer(tv.type)) {
  1918. return false;
  1919. }
  1920. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1921. return false;
  1922. }
  1923. if (is_type_any(tv.type)) {
  1924. return false;
  1925. }
  1926. return true;
  1927. }
  1928. if (o->mode == Addressing_MapIndex) {
  1929. return false;
  1930. }
  1931. Ast *expr = unparen_expr(o->expr);
  1932. if (expr->kind == Ast_CompoundLit) {
  1933. return false;
  1934. }
  1935. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  1936. }
  1937. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  1938. switch (op.kind) {
  1939. case Token_And: { // Pointer address
  1940. if (check_is_not_addressable(c, o)) {
  1941. if (ast_node_expect(node, Ast_UnaryExpr)) {
  1942. ast_node(ue, UnaryExpr, node);
  1943. gbString str = expr_to_string(ue->expr);
  1944. defer (gb_string_free(str));
  1945. Entity *e = entity_of_node(o->expr);
  1946. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  1947. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  1948. } else {
  1949. switch (o->mode) {
  1950. case Addressing_Constant:
  1951. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  1952. break;
  1953. case Addressing_SwizzleValue:
  1954. case Addressing_SwizzleVariable:
  1955. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  1956. break;
  1957. default:
  1958. {
  1959. begin_error_block();
  1960. defer (end_error_block());
  1961. error(op, "Cannot take the pointer address of '%s'", str);
  1962. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  1963. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  1964. }
  1965. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  1966. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  1967. }
  1968. }
  1969. break;
  1970. }
  1971. }
  1972. }
  1973. o->mode = Addressing_Invalid;
  1974. return;
  1975. }
  1976. if (o->mode == Addressing_SoaVariable) {
  1977. ast_node(ue, UnaryExpr, node);
  1978. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  1979. ast_node(ie, IndexExpr, ue->expr);
  1980. Type *soa_type = type_of_expr(ie->expr);
  1981. GB_ASSERT(is_type_soa_struct(soa_type));
  1982. o->type = alloc_type_soa_pointer(soa_type);
  1983. } else {
  1984. o->type = alloc_type_pointer(o->type);
  1985. }
  1986. } else {
  1987. o->type = alloc_type_pointer(o->type);
  1988. }
  1989. switch (o->mode) {
  1990. case Addressing_OptionalOk:
  1991. case Addressing_MapIndex:
  1992. o->mode = Addressing_OptionalOkPtr;
  1993. break;
  1994. default:
  1995. o->mode = Addressing_Value;
  1996. break;
  1997. }
  1998. return;
  1999. }
  2000. }
  2001. if (!check_unary_op(c, o, op)) {
  2002. o->mode = Addressing_Invalid;
  2003. return;
  2004. }
  2005. if (o->mode == Addressing_Constant) {
  2006. Type *type = base_type(o->type);
  2007. if (!is_type_constant_type(o->type)) {
  2008. gbString xt = type_to_string(o->type);
  2009. gbString err_str = expr_to_string(node);
  2010. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2011. gb_string_free(err_str);
  2012. gb_string_free(xt);
  2013. o->mode = Addressing_Invalid;
  2014. return;
  2015. }
  2016. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2017. gbString err_str = expr_to_string(node);
  2018. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2019. gb_string_free(err_str);
  2020. o->mode = Addressing_Invalid;
  2021. return;
  2022. }
  2023. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2024. gbString err_str = expr_to_string(node);
  2025. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2026. gb_string_free(err_str);
  2027. o->mode = Addressing_Invalid;
  2028. return;
  2029. }
  2030. i32 precision = 0;
  2031. if (is_type_typed(type)) {
  2032. precision = cast(i32)(8 * type_size_of(type));
  2033. }
  2034. bool is_unsigned = is_type_unsigned(type);
  2035. if (is_type_rune(type)) {
  2036. GB_ASSERT(!is_unsigned);
  2037. }
  2038. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2039. if (is_type_typed(type)) {
  2040. if (node != nullptr) {
  2041. o->expr = node;
  2042. }
  2043. check_is_expressible(c, o, type);
  2044. }
  2045. return;
  2046. }
  2047. o->mode = Addressing_Value;
  2048. }
  2049. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2050. if (t == nullptr) {
  2051. return;
  2052. }
  2053. t = base_type(t);
  2054. if (!is_type_comparable(t)) {
  2055. return;
  2056. }
  2057. switch (t->kind) {
  2058. case Type_Basic:
  2059. switch (t->Basic.kind) {
  2060. case Basic_complex32:
  2061. add_package_dependency(c, "runtime", "complex32_eq");
  2062. add_package_dependency(c, "runtime", "complex32_ne");
  2063. break;
  2064. case Basic_complex64:
  2065. add_package_dependency(c, "runtime", "complex64_eq");
  2066. add_package_dependency(c, "runtime", "complex64_ne");
  2067. break;
  2068. case Basic_complex128:
  2069. add_package_dependency(c, "runtime", "complex128_eq");
  2070. add_package_dependency(c, "runtime", "complex128_ne");
  2071. break;
  2072. case Basic_quaternion64:
  2073. add_package_dependency(c, "runtime", "quaternion64_eq");
  2074. add_package_dependency(c, "runtime", "quaternion64_ne");
  2075. break;
  2076. case Basic_quaternion128:
  2077. add_package_dependency(c, "runtime", "quaternion128_eq");
  2078. add_package_dependency(c, "runtime", "quaternion128_ne");
  2079. break;
  2080. case Basic_quaternion256:
  2081. add_package_dependency(c, "runtime", "quaternion256_eq");
  2082. add_package_dependency(c, "runtime", "quaternion256_ne");
  2083. break;
  2084. case Basic_cstring:
  2085. add_package_dependency(c, "runtime", "cstring_to_string");
  2086. /*fallthrough*/
  2087. case Basic_string:
  2088. add_package_dependency(c, "runtime", "string_eq");
  2089. add_package_dependency(c, "runtime", "string_ne");
  2090. break;
  2091. }
  2092. break;
  2093. case Type_Struct:
  2094. for (Entity *field : t->Struct.fields) {
  2095. add_comparison_procedures_for_fields(c, field->type);
  2096. }
  2097. break;
  2098. }
  2099. }
  2100. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2101. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2102. bool comp = are_types_identical(x->type, y->type);
  2103. switch (op) {
  2104. case Token_CmpEq: /* comp = comp; */ break;
  2105. case Token_NotEq: comp = !comp; break;
  2106. }
  2107. x->mode = Addressing_Constant;
  2108. x->type = t_untyped_bool;
  2109. x->value = exact_value_bool(comp);
  2110. return;
  2111. }
  2112. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2113. add_type_info_type(c, x->type);
  2114. add_type_info_type(c, y->type);
  2115. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2116. x->mode = Addressing_Value;
  2117. x->type = t_untyped_bool;
  2118. return;
  2119. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2120. add_type_info_type(c, x->type);
  2121. add_type_info_type(c, y->type);
  2122. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2123. x->mode = Addressing_Value;
  2124. x->type = t_untyped_bool;
  2125. return;
  2126. }
  2127. TEMPORARY_ALLOCATOR_GUARD();
  2128. gbString err_str = nullptr;
  2129. if (check_is_assignable_to(c, x, y->type) ||
  2130. check_is_assignable_to(c, y, x->type)) {
  2131. Type *err_type = x->type;
  2132. bool defined = false;
  2133. switch (op) {
  2134. case Token_CmpEq:
  2135. case Token_NotEq:
  2136. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2137. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2138. (is_operand_nil(*y) && type_has_nil(x->type));
  2139. break;
  2140. case Token_Lt:
  2141. case Token_Gt:
  2142. case Token_LtEq:
  2143. case Token_GtEq:
  2144. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2145. defined = true;
  2146. } else {
  2147. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2148. }
  2149. break;
  2150. }
  2151. if (!defined) {
  2152. gbString xs = type_to_string(x->type, temporary_allocator());
  2153. gbString ys = type_to_string(y->type, temporary_allocator());
  2154. err_str = gb_string_make(temporary_allocator(),
  2155. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2156. );
  2157. } else {
  2158. Type *comparison_type = x->type;
  2159. if (x->type == err_type && is_operand_nil(*x)) {
  2160. comparison_type = y->type;
  2161. }
  2162. add_comparison_procedures_for_fields(c, comparison_type);
  2163. }
  2164. } else {
  2165. gbString xt, yt;
  2166. if (x->mode == Addressing_ProcGroup) {
  2167. xt = gb_string_make(temporary_allocator(), "procedure group");
  2168. } else {
  2169. xt = type_to_string(x->type);
  2170. }
  2171. if (y->mode == Addressing_ProcGroup) {
  2172. yt = gb_string_make(temporary_allocator(), "procedure group");
  2173. } else {
  2174. yt = type_to_string(y->type);
  2175. }
  2176. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2177. }
  2178. if (err_str != nullptr) {
  2179. error(node, "Cannot compare expression, %s", err_str);
  2180. x->type = t_untyped_bool;
  2181. } else {
  2182. if (x->mode == Addressing_Constant &&
  2183. y->mode == Addressing_Constant) {
  2184. if (is_type_constant_type(x->type)) {
  2185. if (is_type_bit_set(x->type)) {
  2186. switch (op) {
  2187. case Token_CmpEq:
  2188. case Token_NotEq:
  2189. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2190. break;
  2191. case Token_Lt:
  2192. case Token_LtEq:
  2193. {
  2194. ExactValue lhs = x->value;
  2195. ExactValue rhs = y->value;
  2196. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2197. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2198. if (op == Token_Lt) {
  2199. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2200. }
  2201. x->value = res;
  2202. break;
  2203. }
  2204. case Token_Gt:
  2205. case Token_GtEq:
  2206. {
  2207. ExactValue lhs = x->value;
  2208. ExactValue rhs = y->value;
  2209. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2210. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2211. if (op == Token_Gt) {
  2212. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2213. }
  2214. x->value = res;
  2215. break;
  2216. }
  2217. }
  2218. } else {
  2219. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2220. }
  2221. } else {
  2222. x->mode = Addressing_Value;
  2223. }
  2224. } else {
  2225. x->mode = Addressing_Value;
  2226. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2227. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2228. i64 size = 0;
  2229. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2230. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2231. if (is_type_string(x->type) || is_type_string(y->type)) {
  2232. switch (op) {
  2233. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2234. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2235. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2236. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2237. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2238. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2239. }
  2240. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2241. switch (op) {
  2242. case Token_CmpEq:
  2243. switch (8*size) {
  2244. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2245. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2246. }
  2247. break;
  2248. case Token_NotEq:
  2249. switch (8*size) {
  2250. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2251. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2252. }
  2253. break;
  2254. }
  2255. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2256. switch (op) {
  2257. case Token_CmpEq:
  2258. switch (8*size) {
  2259. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2260. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2261. }
  2262. break;
  2263. case Token_NotEq:
  2264. switch (8*size) {
  2265. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2266. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2267. }
  2268. break;
  2269. }
  2270. }
  2271. }
  2272. x->type = t_untyped_bool;
  2273. }
  2274. }
  2275. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2276. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2277. ast_node(be, BinaryExpr, node);
  2278. ExactValue x_val = {};
  2279. if (x->mode == Addressing_Constant) {
  2280. x_val = exact_value_to_integer(x->value);
  2281. }
  2282. bool x_is_untyped = is_type_untyped(x->type);
  2283. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2284. gbString err_str = expr_to_string(x->expr);
  2285. error(node, "Shifted operand '%s' must be an integer", err_str);
  2286. gb_string_free(err_str);
  2287. x->mode = Addressing_Invalid;
  2288. return;
  2289. }
  2290. if (is_type_unsigned(y->type)) {
  2291. } else if (is_type_untyped(y->type)) {
  2292. convert_to_typed(c, y, t_untyped_integer);
  2293. if (y->mode == Addressing_Invalid) {
  2294. x->mode = Addressing_Invalid;
  2295. return;
  2296. }
  2297. } else {
  2298. gbString err_str = expr_to_string(y->expr);
  2299. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2300. gb_string_free(err_str);
  2301. x->mode = Addressing_Invalid;
  2302. return;
  2303. }
  2304. if (x->mode == Addressing_Constant) {
  2305. if (y->mode == Addressing_Constant) {
  2306. ExactValue y_val = exact_value_to_integer(y->value);
  2307. if (y_val.kind != ExactValue_Integer) {
  2308. gbString err_str = expr_to_string(y->expr);
  2309. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2310. gb_string_free(err_str);
  2311. x->mode = Addressing_Invalid;
  2312. return;
  2313. }
  2314. BigInt max_shift = {};
  2315. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2316. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2317. gbString err_str = expr_to_string(y->expr);
  2318. error(node, "Shift amount too large: '%s'", err_str);
  2319. gb_string_free(err_str);
  2320. x->mode = Addressing_Invalid;
  2321. return;
  2322. }
  2323. if (!is_type_integer(x->type)) {
  2324. // NOTE(bill): It could be an untyped float but still representable
  2325. // as an integer
  2326. x->type = t_untyped_integer;
  2327. }
  2328. x->expr = node;
  2329. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2330. if (is_type_typed(x->type)) {
  2331. check_is_expressible(c, x, x->type);
  2332. }
  2333. return;
  2334. }
  2335. TokenPos pos = ast_token(x->expr).pos;
  2336. if (x_is_untyped) {
  2337. if (x->expr != nullptr) {
  2338. x->expr->tav.is_lhs = true;
  2339. }
  2340. x->mode = Addressing_Value;
  2341. if (type_hint) {
  2342. if (is_type_integer(type_hint)) {
  2343. x->type = type_hint;
  2344. } else {
  2345. gbString x_str = expr_to_string(x->expr);
  2346. gbString to_type = type_to_string(type_hint);
  2347. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2348. gb_string_free(x_str);
  2349. gb_string_free(to_type);
  2350. x->mode = Addressing_Invalid;
  2351. }
  2352. }
  2353. // x->value = x_val;
  2354. return;
  2355. }
  2356. }
  2357. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2358. gbString err_str = expr_to_string(y->expr);
  2359. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2360. gb_string_free(err_str);
  2361. }
  2362. // TODO(bill): Should we support shifts for fixed arrays and #simd vectors?
  2363. if (!is_type_integer(x->type)) {
  2364. gbString err_str = expr_to_string(x->expr);
  2365. error(node, "Shift operand '%s' must be an integer", err_str);
  2366. gb_string_free(err_str);
  2367. x->mode = Addressing_Invalid;
  2368. return;
  2369. }
  2370. if (is_type_untyped(y->type)) {
  2371. convert_to_typed(c, y, t_uint);
  2372. }
  2373. x->mode = Addressing_Value;
  2374. }
  2375. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2376. if (check_is_assignable_to(c, operand, y)) {
  2377. return true;
  2378. }
  2379. bool is_constant = operand->mode == Addressing_Constant;
  2380. Type *x = operand->type;
  2381. Type *src = core_type(x);
  2382. Type *dst = core_type(y);
  2383. if (are_types_identical(src, dst)) {
  2384. return true;
  2385. }
  2386. // if (is_type_tuple(src)) {
  2387. // Ast *expr = unparen_expr(operand->expr);
  2388. // if (expr && expr->kind == Ast_CallExpr) {
  2389. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2390. // ast_node(ce, CallExpr, expr);
  2391. // Type *pt = base_type(type_of_expr(ce->proc));
  2392. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2393. // if (pt->Proc.result_count > 0) {
  2394. // Operand op = *operand;
  2395. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2396. // bool ok = check_is_castable_to(c, &op, y);
  2397. // if (ok) {
  2398. // ce->optional_ok_one = true;
  2399. // }
  2400. // return ok;
  2401. // }
  2402. // }
  2403. // }
  2404. // }
  2405. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2406. if (is_type_u8_array(dst)) {
  2407. String s = operand->value.value_string;
  2408. return s.len == dst->Array.count;
  2409. }
  2410. if (is_type_rune_array(dst)) {
  2411. String s = operand->value.value_string;
  2412. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2413. }
  2414. }
  2415. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2416. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2417. return dst->Array.count == src->Array.count;
  2418. }
  2419. }
  2420. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2421. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2422. }
  2423. // Cast between booleans and integers
  2424. if (is_type_boolean(src) || is_type_integer(src)) {
  2425. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2426. return true;
  2427. }
  2428. }
  2429. // Cast between numbers
  2430. if (is_type_integer(src) || is_type_float(src)) {
  2431. if (is_type_integer(dst) || is_type_float(dst)) {
  2432. return true;
  2433. }
  2434. }
  2435. if (is_type_integer(src) && is_type_rune(dst)) {
  2436. return true;
  2437. }
  2438. if (is_type_rune(src) && is_type_integer(dst)) {
  2439. return true;
  2440. }
  2441. if (is_type_complex(src) && is_type_complex(dst)) {
  2442. return true;
  2443. }
  2444. if (is_type_float(src) && is_type_complex(dst)) {
  2445. return true;
  2446. }
  2447. if (is_type_float(src) && is_type_quaternion(dst)) {
  2448. return true;
  2449. }
  2450. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2451. return true;
  2452. }
  2453. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2454. return true;
  2455. }
  2456. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2457. GB_ASSERT(src->kind == Type_Matrix);
  2458. GB_ASSERT(dst->kind == Type_Matrix);
  2459. Operand op = *operand;
  2460. op.type = src->Matrix.elem;
  2461. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2462. return false;
  2463. }
  2464. if (src->Matrix.row_count != src->Matrix.column_count) {
  2465. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2466. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2467. return src_count == dst_count;
  2468. }
  2469. return is_matrix_square(dst) && is_matrix_square(src);
  2470. }
  2471. // Cast between pointers
  2472. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2473. return true;
  2474. }
  2475. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2476. return true;
  2477. }
  2478. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2479. return true;
  2480. }
  2481. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2482. return true;
  2483. }
  2484. // uintptr <-> pointer
  2485. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2486. return true;
  2487. }
  2488. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2489. return true;
  2490. }
  2491. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2492. return true;
  2493. }
  2494. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2495. return true;
  2496. }
  2497. // []byte/[]u8 <-> string (not cstring)
  2498. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2499. return true;
  2500. }
  2501. // cstring -> string
  2502. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2503. if (operand->mode != Addressing_Constant) {
  2504. add_package_dependency(c, "runtime", "cstring_to_string");
  2505. }
  2506. return true;
  2507. }
  2508. // cstring -> ^u8
  2509. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2510. return !is_constant;
  2511. }
  2512. // cstring -> [^]u8
  2513. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2514. return !is_constant;
  2515. }
  2516. // cstring -> rawptr
  2517. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2518. return !is_constant;
  2519. }
  2520. // ^u8 -> cstring
  2521. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2522. return !is_constant;
  2523. }
  2524. // [^]u8 -> cstring
  2525. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2526. return !is_constant;
  2527. }
  2528. // rawptr -> cstring
  2529. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2530. return !is_constant;
  2531. }
  2532. // proc <-> proc
  2533. if (is_type_proc(src) && is_type_proc(dst)) {
  2534. return true;
  2535. }
  2536. // proc -> rawptr
  2537. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2538. return true;
  2539. }
  2540. // rawptr -> proc
  2541. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2542. return true;
  2543. }
  2544. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2545. if (src->SimdVector.count != dst->SimdVector.count) {
  2546. return false;
  2547. }
  2548. Type *elem_src = base_array_type(src);
  2549. Type *elem_dst = base_array_type(dst);
  2550. Operand x = {};
  2551. x.type = elem_src;
  2552. x.mode = Addressing_Value;
  2553. return check_is_castable_to(c, &x, elem_dst);
  2554. }
  2555. if (is_type_simd_vector(dst)) {
  2556. Type *elem = base_array_type(dst);
  2557. if (check_is_castable_to(c, operand, elem)) {
  2558. return true;
  2559. }
  2560. }
  2561. return false;
  2562. }
  2563. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2564. bool is_const_expr = x->mode == Addressing_Constant;
  2565. Type *bt = base_type(type);
  2566. if (is_const_expr && is_type_constant_type(bt)) {
  2567. if (core_type(bt)->kind == Type_Basic) {
  2568. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2569. return true;
  2570. } else if (check_is_castable_to(c, x, type)) {
  2571. if (is_type_pointer(type)) {
  2572. return true;
  2573. }
  2574. }
  2575. } else if (check_is_castable_to(c, x, type)) {
  2576. x->value = {};
  2577. x->mode = Addressing_Value;
  2578. return true;
  2579. }
  2580. } else if (check_is_castable_to(c, x, type)) {
  2581. if (x->mode != Addressing_Constant) {
  2582. x->mode = Addressing_Value;
  2583. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2584. x->mode = Addressing_Value;
  2585. } else if (is_type_union(type)) {
  2586. x->mode = Addressing_Value;
  2587. }
  2588. if (x->mode == Addressing_Value) {
  2589. x->value = {};
  2590. }
  2591. return true;
  2592. }
  2593. return false;
  2594. }
  2595. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2596. if (!is_operand_value(*x)) {
  2597. error(x->expr, "Only values can be casted");
  2598. x->mode = Addressing_Invalid;
  2599. return;
  2600. }
  2601. bool is_const_expr = x->mode == Addressing_Constant;
  2602. bool can_convert = check_cast_internal(c, x, type);
  2603. if (!can_convert) {
  2604. TEMPORARY_ALLOCATOR_GUARD();
  2605. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2606. gbString to_type = type_to_string(type, temporary_allocator());
  2607. gbString from_type = type_to_string(x->type, temporary_allocator());
  2608. x->mode = Addressing_Invalid;
  2609. begin_error_block();
  2610. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2611. if (is_const_expr) {
  2612. gbString val_str = exact_value_to_string(x->value);
  2613. if (is_type_float(x->type) && is_type_integer(type)) {
  2614. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2615. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2616. x->mode = Addressing_Constant;
  2617. x->type = type;
  2618. } else {
  2619. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2620. if (is_type_numeric(type)) {
  2621. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2622. x->mode = Addressing_Constant;
  2623. x->type = type;
  2624. }
  2625. }
  2626. gb_string_free(val_str);
  2627. }
  2628. check_cast_error_suggestion(c, x, type);
  2629. end_error_block();
  2630. return;
  2631. }
  2632. if (is_type_untyped(x->type)) {
  2633. Type *final_type = type;
  2634. if (is_const_expr && !is_type_constant_type(type)) {
  2635. final_type = default_type(x->type);
  2636. }
  2637. update_untyped_expr_type(c, x->expr, final_type, true);
  2638. }
  2639. if (build_context.vet_extra) {
  2640. if (are_types_identical(x->type, type)) {
  2641. gbString str = type_to_string(type);
  2642. warning(x->expr, "Unneeded cast to the same type '%s'", str);
  2643. gb_string_free(str);
  2644. }
  2645. }
  2646. x->type = type;
  2647. }
  2648. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2649. if (!is_operand_value(*o)) {
  2650. error(o->expr, "'transmute' can only be applied to values");
  2651. o->mode = Addressing_Invalid;
  2652. return false;
  2653. }
  2654. // if (o->mode == Addressing_Constant) {
  2655. // gbString expr_str = expr_to_string(o->expr);
  2656. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2657. // gb_string_free(expr_str);
  2658. // o->mode = Addressing_Invalid;
  2659. // o->expr = node;
  2660. // return false;
  2661. // }
  2662. Type *src_t = o->type;
  2663. Type *dst_t = t;
  2664. Type *src_bt = base_type(src_t);
  2665. Type *dst_bt = base_type(dst_t);
  2666. if (is_type_untyped(src_t)) {
  2667. gbString expr_str = expr_to_string(o->expr);
  2668. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2669. gb_string_free(expr_str);
  2670. o->mode = Addressing_Invalid;
  2671. o->expr = node;
  2672. return false;
  2673. }
  2674. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2675. GB_ASSERT(global_error_collector.count != 0);
  2676. o->mode = Addressing_Invalid;
  2677. o->expr = node;
  2678. return false;
  2679. }
  2680. if (src_bt == nullptr || src_bt == t_invalid) {
  2681. // NOTE(bill): this should be an error
  2682. GB_ASSERT(global_error_collector.count != 0);
  2683. o->mode = Addressing_Value;
  2684. o->expr = node;
  2685. o->type = dst_t;
  2686. return true;
  2687. }
  2688. i64 srcz = type_size_of(src_t);
  2689. i64 dstz = type_size_of(dst_t);
  2690. if (srcz != dstz) {
  2691. gbString expr_str = expr_to_string(o->expr);
  2692. gbString type_str = type_to_string(dst_t);
  2693. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2694. gb_string_free(type_str);
  2695. gb_string_free(expr_str);
  2696. o->mode = Addressing_Invalid;
  2697. o->expr = node;
  2698. return false;
  2699. }
  2700. if (build_context.vet_extra) {
  2701. if (are_types_identical(o->type, dst_t)) {
  2702. gbString str = type_to_string(dst_t);
  2703. warning(o->expr, "Unneeded transmute to the same type '%s'", str);
  2704. gb_string_free(str);
  2705. }
  2706. }
  2707. o->expr = node;
  2708. o->type = dst_t;
  2709. if (o->mode == Addressing_Constant) {
  2710. if (are_types_identical(src_bt, dst_bt)) {
  2711. return true;
  2712. }
  2713. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2714. if (types_have_same_internal_endian(src_t, dst_t)) {
  2715. ExactValue src_v = exact_value_to_integer(o->value);
  2716. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2717. BigInt v = src_v.value_integer;
  2718. BigInt smax = {};
  2719. BigInt umax = {};
  2720. big_int_from_u64(&smax, 0);
  2721. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2722. big_int_from_u64(&umax, 1);
  2723. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2724. big_int_shl_eq(&umax, &sz_in_bits);
  2725. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2726. if (big_int_cmp(&v, &smax) >= 0) {
  2727. big_int_sub_eq(&v, &umax);
  2728. }
  2729. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2730. if (big_int_is_neg(&v)) {
  2731. big_int_add_eq(&v, &umax);
  2732. }
  2733. }
  2734. o->value.kind = ExactValue_Integer;
  2735. o->value.value_integer = v;
  2736. return true;
  2737. }
  2738. }
  2739. }
  2740. o->mode = Addressing_Value;
  2741. o->value = {};
  2742. return true;
  2743. }
  2744. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2745. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2746. if (check_is_assignable_to(c, y, x->type)) {
  2747. if (check_binary_op(c, x, op)) {
  2748. return true;
  2749. }
  2750. }
  2751. }
  2752. return false;
  2753. }
  2754. gb_internal bool is_ise_expr(Ast *node) {
  2755. node = unparen_expr(node);
  2756. return node->kind == Ast_ImplicitSelectorExpr;
  2757. }
  2758. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2759. if (use_lhs_as_type_hint) { // RHS in this case
  2760. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2761. }
  2762. return false;
  2763. }
  2764. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2765. Type *xt = base_type(matrix);
  2766. if (type_hint != nullptr) {
  2767. Type *th = base_type(type_hint);
  2768. if (are_types_identical(th, xt)) {
  2769. return type_hint;
  2770. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2771. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2772. // ignore
  2773. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2774. return type_hint;
  2775. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2776. return type_hint;
  2777. }
  2778. }
  2779. }
  2780. return matrix;
  2781. }
  2782. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2783. if (!check_binary_op(c, x, op)) {
  2784. x->mode = Addressing_Invalid;
  2785. return;
  2786. }
  2787. Type *xt = base_type(x->type);
  2788. Type *yt = base_type(y->type);
  2789. if (is_type_matrix(x->type)) {
  2790. GB_ASSERT(xt->kind == Type_Matrix);
  2791. if (op.kind == Token_Mul) {
  2792. if (yt->kind == Type_Matrix) {
  2793. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2794. goto matrix_error;
  2795. }
  2796. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2797. goto matrix_error;
  2798. }
  2799. x->mode = Addressing_Value;
  2800. if (are_types_identical(xt, yt)) {
  2801. if (!is_type_named(x->type) && is_type_named(y->type)) {
  2802. // prefer the named type
  2803. x->type = y->type;
  2804. }
  2805. } else {
  2806. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2807. }
  2808. goto matrix_success;
  2809. } else if (yt->kind == Type_Array) {
  2810. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2811. goto matrix_error;
  2812. }
  2813. if (xt->Matrix.column_count != yt->Array.count) {
  2814. goto matrix_error;
  2815. }
  2816. // Treat arrays as column vectors
  2817. x->mode = Addressing_Value;
  2818. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2819. x->type = y->type;
  2820. } else {
  2821. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2822. }
  2823. goto matrix_success;
  2824. }
  2825. }
  2826. if (!are_types_identical(xt, yt)) {
  2827. goto matrix_error;
  2828. }
  2829. x->mode = Addressing_Value;
  2830. x->type = xt;
  2831. goto matrix_success;
  2832. } else {
  2833. GB_ASSERT(!is_type_matrix(xt));
  2834. GB_ASSERT(is_type_matrix(yt));
  2835. if (op.kind == Token_Mul) {
  2836. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2837. if (xt->kind == Type_Array) {
  2838. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2839. goto matrix_error;
  2840. }
  2841. if (xt->Array.count != yt->Matrix.row_count) {
  2842. goto matrix_error;
  2843. }
  2844. // Treat arrays as row vectors
  2845. x->mode = Addressing_Value;
  2846. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2847. x->type = x->type;
  2848. } else {
  2849. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2850. }
  2851. goto matrix_success;
  2852. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  2853. x->type = check_matrix_type_hint(y->type, type_hint);
  2854. return;
  2855. }
  2856. }
  2857. if (!are_types_identical(xt, yt)) {
  2858. goto matrix_error;
  2859. }
  2860. x->mode = Addressing_Value;
  2861. x->type = xt;
  2862. goto matrix_success;
  2863. }
  2864. matrix_success:
  2865. x->type = check_matrix_type_hint(x->type, type_hint);
  2866. return;
  2867. matrix_error:
  2868. gbString xts = type_to_string(x->type);
  2869. gbString yts = type_to_string(y->type);
  2870. gbString expr_str = expr_to_string(x->expr);
  2871. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2872. gb_string_free(expr_str);
  2873. gb_string_free(yts);
  2874. gb_string_free(xts);
  2875. x->type = t_invalid;
  2876. x->mode = Addressing_Invalid;
  2877. return;
  2878. }
  2879. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2880. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2881. Operand y_ = {}, *y = &y_;
  2882. ast_node(be, BinaryExpr, node);
  2883. defer({
  2884. node->viral_state_flags |= be->left->viral_state_flags;
  2885. node->viral_state_flags |= be->right->viral_state_flags;
  2886. });
  2887. Token op = be->op;
  2888. switch (op.kind) {
  2889. case Token_CmpEq:
  2890. case Token_NotEq: {
  2891. // NOTE(bill): Allow comparisons between types
  2892. if (is_ise_expr(be->left)) {
  2893. // Evalute the right before the left for an '.X' expression
  2894. check_expr_or_type(c, y, be->right, type_hint);
  2895. check_expr_or_type(c, x, be->left, y->type);
  2896. } else {
  2897. check_expr_or_type(c, x, be->left, type_hint);
  2898. check_expr_or_type(c, y, be->right, x->type);
  2899. }
  2900. bool xt = x->mode == Addressing_Type;
  2901. bool yt = y->mode == Addressing_Type;
  2902. // If only one is a type, this is an error
  2903. if (xt ^ yt) {
  2904. GB_ASSERT(xt != yt);
  2905. if (xt) {
  2906. if (!is_type_typeid(y->type)) {
  2907. error_operand_not_expression(x);
  2908. }
  2909. }
  2910. if (yt) {
  2911. if (!is_type_typeid(x->type)) {
  2912. error_operand_not_expression(y);
  2913. }
  2914. }
  2915. }
  2916. break;
  2917. }
  2918. case Token_in:
  2919. case Token_not_in:
  2920. {
  2921. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  2922. check_expr(c, y, be->right);
  2923. Type *rhs_type = type_deref(y->type);
  2924. if (is_type_bit_set(rhs_type)) {
  2925. Type *elem = base_type(rhs_type)->BitSet.elem;
  2926. check_expr_with_type_hint(c, x, be->left, elem);
  2927. } else if (is_type_map(rhs_type)) {
  2928. Type *key = base_type(rhs_type)->Map.key;
  2929. check_expr_with_type_hint(c, x, be->left, key);
  2930. } else {
  2931. check_expr(c, x, be->left);
  2932. }
  2933. if (x->mode == Addressing_Invalid) {
  2934. return;
  2935. }
  2936. if (y->mode == Addressing_Invalid) {
  2937. x->mode = Addressing_Invalid;
  2938. x->expr = y->expr;
  2939. return;
  2940. }
  2941. if (is_type_map(rhs_type)) {
  2942. Type *yt = base_type(rhs_type);
  2943. if (op.kind == Token_in) {
  2944. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  2945. } else {
  2946. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  2947. }
  2948. add_map_get_dependencies(c);
  2949. } else if (is_type_bit_set(rhs_type)) {
  2950. Type *yt = base_type(rhs_type);
  2951. if (op.kind == Token_in) {
  2952. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  2953. } else {
  2954. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  2955. }
  2956. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  2957. ExactValue k = exact_value_to_integer(x->value);
  2958. ExactValue v = exact_value_to_integer(y->value);
  2959. GB_ASSERT(k.kind == ExactValue_Integer);
  2960. GB_ASSERT(v.kind == ExactValue_Integer);
  2961. i64 key = big_int_to_i64(&k.value_integer);
  2962. i64 lower = yt->BitSet.lower;
  2963. i64 upper = yt->BitSet.upper;
  2964. if (lower <= key && key <= upper) {
  2965. i64 bit = 1ll<<key;
  2966. i64 bits = big_int_to_i64(&v.value_integer);
  2967. x->mode = Addressing_Constant;
  2968. x->type = t_untyped_bool;
  2969. if (op.kind == Token_in) {
  2970. x->value = exact_value_bool((bit & bits) != 0);
  2971. } else {
  2972. x->value = exact_value_bool((bit & bits) == 0);
  2973. }
  2974. x->expr = node;
  2975. return;
  2976. } else {
  2977. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  2978. x->mode = Addressing_Invalid;
  2979. }
  2980. }
  2981. } else {
  2982. gbString t = type_to_string(y->type);
  2983. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  2984. gb_string_free(t);
  2985. x->expr = node;
  2986. x->mode = Addressing_Invalid;
  2987. return;
  2988. }
  2989. if (x->mode != Addressing_Invalid) {
  2990. x->mode = Addressing_Value;
  2991. x->type = t_untyped_bool;
  2992. }
  2993. x->expr = node;
  2994. return;
  2995. }
  2996. default:
  2997. if (is_ise_expr(be->left)) {
  2998. // Evalute the right before the left for an '.X' expression
  2999. check_expr_or_type(c, y, be->right, type_hint);
  3000. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3001. check_expr_or_type(c, x, be->left, y->type);
  3002. } else {
  3003. check_expr_with_type_hint(c, x, be->left, type_hint);
  3004. }
  3005. } else {
  3006. check_expr_with_type_hint(c, x, be->left, type_hint);
  3007. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3008. check_expr_with_type_hint(c, y, be->right, x->type);
  3009. } else {
  3010. check_expr_with_type_hint(c, y, be->right, type_hint);
  3011. }
  3012. }
  3013. break;
  3014. }
  3015. if (x->mode == Addressing_Invalid) {
  3016. return;
  3017. }
  3018. if (y->mode == Addressing_Invalid) {
  3019. x->mode = Addressing_Invalid;
  3020. x->expr = y->expr;
  3021. return;
  3022. }
  3023. if (x->mode == Addressing_Builtin) {
  3024. x->mode = Addressing_Invalid;
  3025. error(x->expr, "built-in expression in binary expression");
  3026. return;
  3027. }
  3028. if (y->mode == Addressing_Builtin) {
  3029. x->mode = Addressing_Invalid;
  3030. error(y->expr, "built-in expression in binary expression");
  3031. return;
  3032. }
  3033. if (x->mode == Addressing_ProcGroup) {
  3034. x->mode = Addressing_Invalid;
  3035. if (x->proc_group != nullptr) {
  3036. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3037. } else {
  3038. error(x->expr, "procedure group used in binary expression");
  3039. }
  3040. return;
  3041. }
  3042. if (y->mode == Addressing_ProcGroup) {
  3043. x->mode = Addressing_Invalid;
  3044. if (x->proc_group != nullptr) {
  3045. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3046. } else {
  3047. error(y->expr, "procedure group used in binary expression");
  3048. }
  3049. return;
  3050. }
  3051. if (token_is_shift(op.kind)) {
  3052. check_shift(c, x, y, node, type_hint);
  3053. return;
  3054. }
  3055. convert_to_typed(c, x, y->type);
  3056. if (x->mode == Addressing_Invalid) {
  3057. return;
  3058. }
  3059. convert_to_typed(c, y, x->type);
  3060. if (y->mode == Addressing_Invalid) {
  3061. x->mode = Addressing_Invalid;
  3062. return;
  3063. }
  3064. if (token_is_comparison(op.kind)) {
  3065. check_comparison(c, node, x, y, op.kind);
  3066. return;
  3067. }
  3068. if (check_binary_array_expr(c, op, x, y)) {
  3069. x->mode = Addressing_Value;
  3070. x->type = x->type;
  3071. return;
  3072. }
  3073. if (check_binary_array_expr(c, op, y, x)) {
  3074. x->mode = Addressing_Value;
  3075. x->type = y->type;
  3076. return;
  3077. }
  3078. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3079. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3080. x->expr = node;
  3081. return;
  3082. }
  3083. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3084. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3085. // NOTE(bill, 2022-06-26)
  3086. // Allow any boolean types within `&&` and `||`
  3087. // This is an exception to all other binary expressions since the result
  3088. // of a comparison will always be an untyped boolean, and allowing
  3089. // any boolean between these two simplifies a lot of expressions
  3090. } else if (!are_types_identical(x->type, y->type)) {
  3091. if (x->type != t_invalid &&
  3092. y->type != t_invalid) {
  3093. gbString xt = type_to_string(x->type);
  3094. gbString yt = type_to_string(y->type);
  3095. gbString expr_str = expr_to_string(node);
  3096. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3097. gb_string_free(expr_str);
  3098. gb_string_free(yt);
  3099. gb_string_free(xt);
  3100. }
  3101. x->mode = Addressing_Invalid;
  3102. return;
  3103. }
  3104. if (!check_binary_op(c, x, op)) {
  3105. x->mode = Addressing_Invalid;
  3106. return;
  3107. }
  3108. switch (op.kind) {
  3109. case Token_Quo:
  3110. case Token_Mod:
  3111. case Token_ModMod:
  3112. case Token_QuoEq:
  3113. case Token_ModEq:
  3114. case Token_ModModEq:
  3115. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3116. y->mode == Addressing_Constant) {
  3117. bool fail = false;
  3118. switch (y->value.kind) {
  3119. case ExactValue_Integer:
  3120. if (big_int_is_zero(&y->value.value_integer)) {
  3121. fail = true;
  3122. }
  3123. break;
  3124. case ExactValue_Float:
  3125. if (y->value.value_float == 0.0) {
  3126. fail = true;
  3127. }
  3128. break;
  3129. }
  3130. if (fail) {
  3131. error(y->expr, "Division by zero not allowed");
  3132. x->mode = Addressing_Invalid;
  3133. return;
  3134. }
  3135. }
  3136. break;
  3137. case Token_CmpAnd:
  3138. case Token_CmpOr:
  3139. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3140. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3141. }
  3142. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3143. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3144. }
  3145. break;
  3146. }
  3147. if (x->mode == Addressing_Constant &&
  3148. y->mode == Addressing_Constant) {
  3149. ExactValue a = x->value;
  3150. ExactValue b = y->value;
  3151. if (!is_type_constant_type(x->type)) {
  3152. #if 0
  3153. gbString xt = type_to_string(x->type);
  3154. gbString err_str = expr_to_string(node);
  3155. error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
  3156. gb_string_free(err_str);
  3157. gb_string_free(xt);
  3158. x->mode = Addressing_Invalid;
  3159. #else
  3160. // NOTE(bill, 2021-04-21): The above is literally a useless error message.
  3161. // Why did I add it in the first place?!
  3162. x->mode = Addressing_Value;
  3163. #endif
  3164. return;
  3165. }
  3166. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3167. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3168. }
  3169. if (is_type_bit_set(x->type)) {
  3170. switch (op.kind) {
  3171. case Token_Add: op.kind = Token_Or; break;
  3172. case Token_Sub: op.kind = Token_AndNot; break;
  3173. }
  3174. }
  3175. x->value = exact_binary_operator_value(op.kind, a, b);
  3176. if (is_type_typed(x->type)) {
  3177. if (node != nullptr) {
  3178. x->expr = node;
  3179. }
  3180. check_is_expressible(c, x, x->type);
  3181. }
  3182. return;
  3183. } else if (is_type_string(x->type)) {
  3184. error(node, "String concatenation is only allowed with constant strings");
  3185. x->mode = Addressing_Invalid;
  3186. return;
  3187. }
  3188. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3189. Type *bt = base_type(x->type);
  3190. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3191. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3192. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3193. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3194. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3195. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3196. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3197. }
  3198. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3199. Type *bt = base_type(x->type);
  3200. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3201. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3202. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3203. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3204. }
  3205. }
  3206. x->mode = Addressing_Value;
  3207. }
  3208. gb_internal Operand make_operand_from_node(Ast *node) {
  3209. GB_ASSERT(node != nullptr);
  3210. Operand x = {};
  3211. x.expr = node;
  3212. x.mode = node->tav.mode;
  3213. x.type = node->tav.type;
  3214. x.value = node->tav.value;
  3215. return x;
  3216. }
  3217. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3218. GB_ASSERT(e != nullptr);
  3219. ExprInfo *old = check_get_expr_info(c, e);
  3220. if (old == nullptr) {
  3221. if (type != nullptr && type != t_invalid) {
  3222. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3223. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3224. if (e->kind == Ast_TernaryIfExpr) {
  3225. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3226. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3227. }
  3228. }
  3229. }
  3230. return;
  3231. }
  3232. switch (e->kind) {
  3233. case_ast_node(ue, UnaryExpr, e);
  3234. if (old->value.kind != ExactValue_Invalid) {
  3235. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3236. // They don't need to be updated as they will be updated later and
  3237. // checked at the end of general checking stage.
  3238. break;
  3239. }
  3240. update_untyped_expr_type(c, ue->expr, type, final);
  3241. case_end;
  3242. case_ast_node(be, BinaryExpr, e);
  3243. if (old->value.kind != ExactValue_Invalid) {
  3244. // See above note in UnaryExpr case
  3245. break;
  3246. }
  3247. if (token_is_comparison(be->op.kind)) {
  3248. // NOTE(bill): Do nothing as the types are fine
  3249. } else if (token_is_shift(be->op.kind)) {
  3250. update_untyped_expr_type(c, be->left, type, final);
  3251. } else {
  3252. update_untyped_expr_type(c, be->left, type, final);
  3253. update_untyped_expr_type(c, be->right, type, final);
  3254. }
  3255. case_end;
  3256. case_ast_node(te, TernaryIfExpr, e);
  3257. if (old->value.kind != ExactValue_Invalid) {
  3258. // See above note in UnaryExpr case
  3259. break;
  3260. }
  3261. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3262. // having an untyped value
  3263. Operand x = make_operand_from_node(te->x);
  3264. Operand y = make_operand_from_node(te->y);
  3265. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3266. update_untyped_expr_type(c, te->x, type, final);
  3267. }
  3268. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3269. update_untyped_expr_type(c, te->y, type, final);
  3270. }
  3271. case_end;
  3272. case_ast_node(te, TernaryWhenExpr, e);
  3273. if (old->value.kind != ExactValue_Invalid) {
  3274. // See above note in UnaryExpr case
  3275. break;
  3276. }
  3277. update_untyped_expr_type(c, te->x, type, final);
  3278. update_untyped_expr_type(c, te->y, type, final);
  3279. case_end;
  3280. case_ast_node(ore, OrReturnExpr, e);
  3281. if (old->value.kind != ExactValue_Invalid) {
  3282. // See above note in UnaryExpr case
  3283. break;
  3284. }
  3285. update_untyped_expr_type(c, ore->expr, type, final);
  3286. case_end;
  3287. case_ast_node(oee, OrElseExpr, e);
  3288. if (old->value.kind != ExactValue_Invalid) {
  3289. // See above note in UnaryExpr case
  3290. break;
  3291. }
  3292. update_untyped_expr_type(c, oee->x, type, final);
  3293. update_untyped_expr_type(c, oee->y, type, final);
  3294. case_end;
  3295. case_ast_node(pe, ParenExpr, e);
  3296. update_untyped_expr_type(c, pe->expr, type, final);
  3297. case_end;
  3298. }
  3299. if (!final && is_type_untyped(type)) {
  3300. old->type = base_type(type);
  3301. return;
  3302. }
  3303. // We need to remove it and then give it a new one
  3304. check_remove_expr_info(c, e);
  3305. if (old->is_lhs && !is_type_integer(type)) {
  3306. gbString expr_str = expr_to_string(e);
  3307. gbString type_str = type_to_string(type);
  3308. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3309. gb_string_free(type_str);
  3310. gb_string_free(expr_str);
  3311. return;
  3312. }
  3313. add_type_and_value(c, e, old->mode, type, old->value);
  3314. }
  3315. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3316. GB_ASSERT(e != nullptr);
  3317. ExprInfo *found = check_get_expr_info(c, e);
  3318. if (found) {
  3319. found->value = value;
  3320. }
  3321. }
  3322. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3323. gbString expr_str = expr_to_string(operand->expr);
  3324. gbString type_str = type_to_string(target_type);
  3325. gbString from_type_str = type_to_string(operand->type);
  3326. char const *extra_text = "";
  3327. if (operand->mode == Addressing_Constant) {
  3328. if (big_int_is_zero(&operand->value.value_integer)) {
  3329. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3330. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3331. extra_text = " - Did you want 'nil'?";
  3332. }
  3333. }
  3334. }
  3335. ERROR_BLOCK();
  3336. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3337. if (operand->value.kind == ExactValue_String) {
  3338. String key = operand->value.value_string;
  3339. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3340. Type *et = base_type(target_type);
  3341. check_did_you_mean_type(key, et->Enum.fields, ".");
  3342. }
  3343. }
  3344. gb_string_free(from_type_str);
  3345. gb_string_free(type_str);
  3346. gb_string_free(expr_str);
  3347. operand->mode = Addressing_Invalid;
  3348. }
  3349. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3350. Type *t = core_type(type);
  3351. if (is_type_boolean(t)) {
  3352. // v = exact_value_to_boolean(v);
  3353. } else if (is_type_float(t)) {
  3354. v = exact_value_to_float(v);
  3355. } else if (is_type_integer(t)) {
  3356. v = exact_value_to_integer(v);
  3357. } else if (is_type_pointer(t)) {
  3358. v = exact_value_to_integer(v);
  3359. } else if (is_type_complex(t)) {
  3360. v = exact_value_to_complex(v);
  3361. } else if (is_type_quaternion(t)) {
  3362. v = exact_value_to_quaternion(v);
  3363. }
  3364. return v;
  3365. }
  3366. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3367. GB_ASSERT_NOT_NULL(target_type);
  3368. if (operand->mode == Addressing_Invalid ||
  3369. operand->mode == Addressing_Type ||
  3370. is_type_typed(operand->type) ||
  3371. target_type == t_invalid) {
  3372. return;
  3373. }
  3374. if (is_type_untyped(target_type)) {
  3375. GB_ASSERT(operand->type->kind == Type_Basic);
  3376. GB_ASSERT(target_type->kind == Type_Basic);
  3377. BasicKind x_kind = operand->type->Basic.kind;
  3378. BasicKind y_kind = target_type->Basic.kind;
  3379. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3380. if (x_kind < y_kind) {
  3381. operand->type = target_type;
  3382. update_untyped_expr_type(c, operand->expr, target_type, false);
  3383. }
  3384. } else if (x_kind != y_kind) {
  3385. operand->mode = Addressing_Invalid;
  3386. convert_untyped_error(c, operand, target_type);
  3387. return;
  3388. }
  3389. return;
  3390. }
  3391. Type *t = base_type(target_type);
  3392. if (c->in_enum_type) {
  3393. t = core_type(target_type);
  3394. }
  3395. switch (t->kind) {
  3396. case Type_Basic:
  3397. if (operand->mode == Addressing_Constant) {
  3398. check_is_expressible(c, operand, t);
  3399. if (operand->mode == Addressing_Invalid) {
  3400. return;
  3401. }
  3402. update_untyped_expr_value(c, operand->expr, operand->value);
  3403. } else {
  3404. switch (operand->type->Basic.kind) {
  3405. case Basic_UntypedBool:
  3406. if (!is_type_boolean(target_type)) {
  3407. operand->mode = Addressing_Invalid;
  3408. convert_untyped_error(c, operand, target_type);
  3409. return;
  3410. }
  3411. break;
  3412. case Basic_UntypedInteger:
  3413. case Basic_UntypedFloat:
  3414. case Basic_UntypedComplex:
  3415. case Basic_UntypedQuaternion:
  3416. case Basic_UntypedRune:
  3417. if (!is_type_numeric(target_type)) {
  3418. operand->mode = Addressing_Invalid;
  3419. convert_untyped_error(c, operand, target_type);
  3420. return;
  3421. }
  3422. break;
  3423. case Basic_UntypedNil:
  3424. if (is_type_any(target_type)) {
  3425. // target_type = t_untyped_nil;
  3426. } else if (is_type_cstring(target_type)) {
  3427. // target_type = t_untyped_nil;
  3428. } else if (!type_has_nil(target_type)) {
  3429. operand->mode = Addressing_Invalid;
  3430. convert_untyped_error(c, operand, target_type);
  3431. return;
  3432. }
  3433. break;
  3434. }
  3435. }
  3436. break;
  3437. case Type_Array: {
  3438. Type *elem = base_array_type(t);
  3439. if (check_is_assignable_to(c, operand, elem)) {
  3440. operand->mode = Addressing_Value;
  3441. } else {
  3442. if (operand->value.kind == ExactValue_String) {
  3443. String s = operand->value.value_string;
  3444. if (is_type_u8_array(t)) {
  3445. if (s.len == t->Array.count) {
  3446. break;
  3447. }
  3448. } else if (is_type_rune_array(t)) {
  3449. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3450. if (rune_count == t->Array.count) {
  3451. break;
  3452. }
  3453. }
  3454. }
  3455. operand->mode = Addressing_Invalid;
  3456. convert_untyped_error(c, operand, target_type);
  3457. return;
  3458. }
  3459. break;
  3460. }
  3461. case Type_Matrix: {
  3462. Type *elem = base_array_type(t);
  3463. if (check_is_assignable_to(c, operand, elem)) {
  3464. if (t->Matrix.row_count != t->Matrix.column_count) {
  3465. operand->mode = Addressing_Invalid;
  3466. begin_error_block();
  3467. defer (end_error_block());
  3468. convert_untyped_error(c, operand, target_type);
  3469. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3470. return;
  3471. } else {
  3472. operand->mode = Addressing_Value;
  3473. }
  3474. } else {
  3475. operand->mode = Addressing_Invalid;
  3476. convert_untyped_error(c, operand, target_type);
  3477. return;
  3478. }
  3479. break;
  3480. }
  3481. case Type_Union:
  3482. if (!is_operand_nil(*operand) && !is_operand_undef(*operand)) {
  3483. TEMPORARY_ALLOCATOR_GUARD();
  3484. isize count = t->Union.variants.count;
  3485. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3486. isize valid_count = 0;
  3487. isize first_success_index = -1;
  3488. for_array(i, t->Union.variants) {
  3489. Type *vt = t->Union.variants[i];
  3490. i64 score = 0;
  3491. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3492. valids[valid_count].index = i;
  3493. valids[valid_count].score = score;
  3494. valid_count += 1;
  3495. if (first_success_index < 0) {
  3496. first_success_index = i;
  3497. }
  3498. }
  3499. }
  3500. if (valid_count > 1) {
  3501. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3502. i64 best_score = valids[0].score;
  3503. for (isize i = 1; i < valid_count; i++) {
  3504. auto v = valids[i];
  3505. if (best_score > v.score) {
  3506. valid_count = i;
  3507. break;
  3508. }
  3509. best_score = v.score;
  3510. }
  3511. first_success_index = valids[0].index;
  3512. }
  3513. gbString type_str = type_to_string(target_type);
  3514. defer (gb_string_free(type_str));
  3515. if (valid_count == 1) {
  3516. operand->mode = Addressing_Value;
  3517. operand->type = t->Union.variants[first_success_index];
  3518. target_type = t->Union.variants[first_success_index];
  3519. break;
  3520. } else if (valid_count > 1) {
  3521. begin_error_block();
  3522. defer (end_error_block());
  3523. GB_ASSERT(first_success_index >= 0);
  3524. operand->mode = Addressing_Invalid;
  3525. convert_untyped_error(c, operand, target_type);
  3526. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3527. i32 j = 0;
  3528. for (i32 i = 0; i < valid_count; i++) {
  3529. ValidIndexAndScore valid = valids[i];
  3530. if (j > 0 && valid_count > 2) error_line(", ");
  3531. if (j == valid_count-1) {
  3532. if (valid_count == 2) error_line(" ");
  3533. error_line("or ");
  3534. }
  3535. gbString str = type_to_string(t->Union.variants[valid.index]);
  3536. error_line("'%s'", str);
  3537. gb_string_free(str);
  3538. j++;
  3539. }
  3540. error_line("\n\n");
  3541. return;
  3542. } else if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  3543. target_type = t_untyped_undef;
  3544. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3545. begin_error_block();
  3546. defer (end_error_block());
  3547. operand->mode = Addressing_Invalid;
  3548. convert_untyped_error(c, operand, target_type);
  3549. if (count > 0) {
  3550. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3551. error_line("\t");
  3552. for (i32 i = 0; i < count; i++) {
  3553. Type *v = t->Union.variants[i];
  3554. if (i > 0 && count > 2) error_line(", ");
  3555. if (i == count-1) {
  3556. if (count == 2) error_line(" ");
  3557. if (count > 1) {
  3558. error_line("or ");
  3559. }
  3560. }
  3561. gbString str = type_to_string(v);
  3562. error_line("'%s'", str);
  3563. gb_string_free(str);
  3564. }
  3565. error_line("\n\n");
  3566. }
  3567. return;
  3568. }
  3569. }
  3570. /* fallthrough */
  3571. default:
  3572. if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  3573. target_type = t_untyped_undef;
  3574. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3575. target_type = t_untyped_nil;
  3576. } else {
  3577. operand->mode = Addressing_Invalid;
  3578. convert_untyped_error(c, operand, target_type);
  3579. return;
  3580. }
  3581. break;
  3582. }
  3583. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3584. if (is_type_untyped_nil(operand->type) && is_type_untyped_undef(operand->type)) {
  3585. } else {
  3586. target_type = default_type(operand->type);
  3587. }
  3588. }
  3589. update_untyped_expr_type(c, operand->expr, target_type, true);
  3590. operand->type = target_type;
  3591. }
  3592. 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) {
  3593. Operand operand = {Addressing_Invalid};
  3594. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3595. if (operand.mode == Addressing_Invalid) {
  3596. if (value) *value = 0;
  3597. return false;
  3598. }
  3599. Type *index_type = t_int;
  3600. if (type_hint != nullptr) {
  3601. index_type = type_hint;
  3602. }
  3603. convert_to_typed(c, &operand, index_type);
  3604. if (operand.mode == Addressing_Invalid) {
  3605. if (value) *value = 0;
  3606. return false;
  3607. }
  3608. if (type_hint != nullptr) {
  3609. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3610. gbString expr_str = expr_to_string(operand.expr);
  3611. gbString index_type_str = type_to_string(type_hint);
  3612. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3613. gb_string_free(index_type_str);
  3614. gb_string_free(expr_str);
  3615. if (value) *value = 0;
  3616. return false;
  3617. }
  3618. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3619. gbString expr_str = expr_to_string(operand.expr);
  3620. gbString type_str = type_to_string(operand.type);
  3621. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3622. gb_string_free(type_str);
  3623. gb_string_free(expr_str);
  3624. if (value) *value = 0;
  3625. return false;
  3626. }
  3627. if (operand.mode == Addressing_Constant &&
  3628. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3629. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3630. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3631. TEMPORARY_ALLOCATOR_GUARD();
  3632. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3633. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3634. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3635. if (value) *value = 0;
  3636. return false;
  3637. }
  3638. if (max_count >= 0) {
  3639. if (is_type_enum(index_type)) {
  3640. Type *bt = base_type(index_type);
  3641. GB_ASSERT(bt->kind == Type_Enum);
  3642. ExactValue const &lo = *bt->Enum.min_value;
  3643. ExactValue const &hi = *bt->Enum.max_value;
  3644. String lo_str = {};
  3645. String hi_str = {};
  3646. if (bt->Enum.fields.count > 0) {
  3647. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3648. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3649. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3650. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3651. }
  3652. bool out_of_bounds = false;
  3653. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3654. out_of_bounds = true;
  3655. }
  3656. if (out_of_bounds) {
  3657. gbString expr_str = expr_to_string(operand.expr);
  3658. if (lo_str.len > 0) {
  3659. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3660. } else {
  3661. gbString index_type_str = type_to_string(index_type);
  3662. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3663. gb_string_free(index_type_str);
  3664. }
  3665. gb_string_free(expr_str);
  3666. return false;
  3667. }
  3668. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3669. return true;
  3670. } else { // NOTE(bill): Do array bound checking
  3671. i64 v = -1;
  3672. if (i.used <= 1) {
  3673. v = big_int_to_i64(&i);
  3674. }
  3675. if (value) *value = v;
  3676. bool out_of_bounds = false;
  3677. if (v < 0) {
  3678. out_of_bounds = true;
  3679. } else if (open_range) {
  3680. out_of_bounds = v > max_count;
  3681. } else {
  3682. out_of_bounds = v >= max_count;
  3683. }
  3684. if (out_of_bounds) {
  3685. TEMPORARY_ALLOCATOR_GUARD();
  3686. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3687. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3688. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3689. return false;
  3690. }
  3691. return true;
  3692. }
  3693. } else {
  3694. if (value) *value = exact_value_to_i64(operand.value);
  3695. return true;
  3696. }
  3697. }
  3698. // NOTE(bill): It's alright :D
  3699. if (value) *value = -1;
  3700. return true;
  3701. }
  3702. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3703. if (value.kind == ExactValue_String) {
  3704. GB_ASSERT(0 <= index && index < value.value_string.len);
  3705. u8 val = value.value_string[index];
  3706. if (success_) *success_ = true;
  3707. if (finish_) *finish_ = true;
  3708. return exact_value_u64(val);
  3709. }
  3710. if (value.kind != ExactValue_Compound) {
  3711. if (success_) *success_ = true;
  3712. if (finish_) *finish_ = true;
  3713. return value;
  3714. }
  3715. Ast *node = value.value_compound;
  3716. switch (node->kind) {
  3717. case_ast_node(cl, CompoundLit, node);
  3718. if (cl->elems.count == 0) {
  3719. if (success_) *success_ = true;
  3720. if (finish_) *finish_ = true;
  3721. return empty_exact_value;
  3722. }
  3723. if (cl->elems[0]->kind == Ast_FieldValue) {
  3724. if (is_type_struct(node->tav.type)) {
  3725. bool found = false;
  3726. for (Ast *elem : cl->elems) {
  3727. if (elem->kind != Ast_FieldValue) {
  3728. continue;
  3729. }
  3730. ast_node(fv, FieldValue, elem);
  3731. String name = fv->field->Ident.token.string;
  3732. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3733. defer (array_free(&sub_sel.index));
  3734. if (sub_sel.index[0] == index) {
  3735. value = fv->value->tav.value;
  3736. found = true;
  3737. break;
  3738. }
  3739. }
  3740. if (!found) {
  3741. // Use the zero value if it is not found
  3742. value = {};
  3743. }
  3744. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3745. for (Ast *elem : cl->elems) {
  3746. if (elem->kind != Ast_FieldValue) {
  3747. continue;
  3748. }
  3749. ast_node(fv, FieldValue, elem);
  3750. if (is_ast_range(fv->field)) {
  3751. ast_node(ie, BinaryExpr, fv->field);
  3752. TypeAndValue lo_tav = ie->left->tav;
  3753. TypeAndValue hi_tav = ie->right->tav;
  3754. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3755. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3756. TokenKind op = ie->op.kind;
  3757. i64 lo = exact_value_to_i64(lo_tav.value);
  3758. i64 hi = exact_value_to_i64(hi_tav.value);
  3759. i64 corrected_index = index;
  3760. if (is_type_enumerated_array(node->tav.type)) {
  3761. Type *bt = base_type(node->tav.type);
  3762. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3763. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3764. }
  3765. if (op != Token_RangeHalf) {
  3766. if (lo <= corrected_index && corrected_index <= hi) {
  3767. TypeAndValue tav = fv->value->tav;
  3768. if (success_) *success_ = true;
  3769. if (finish_) *finish_ = false;
  3770. return tav.value;
  3771. }
  3772. } else {
  3773. if (lo <= corrected_index && corrected_index < hi) {
  3774. TypeAndValue tav = fv->value->tav;
  3775. if (success_) *success_ = true;
  3776. if (finish_) *finish_ = false;
  3777. return tav.value;
  3778. }
  3779. }
  3780. } else {
  3781. TypeAndValue index_tav = fv->field->tav;
  3782. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3783. ExactValue index_value = index_tav.value;
  3784. if (is_type_enumerated_array(node->tav.type)) {
  3785. Type *bt = base_type(node->tav.type);
  3786. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3787. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3788. }
  3789. i64 field_index = exact_value_to_i64(index_value);
  3790. if (index == field_index) {
  3791. TypeAndValue tav = fv->value->tav;
  3792. if (success_) *success_ = true;
  3793. if (finish_) *finish_ = false;
  3794. return tav.value;;
  3795. }
  3796. }
  3797. }
  3798. }
  3799. } else {
  3800. i32 count = (i32)cl->elems.count;
  3801. if (count < index) {
  3802. if (success_) *success_ = false;
  3803. if (finish_) *finish_ = true;
  3804. return empty_exact_value;
  3805. }
  3806. if (cl->elems.count <= index) {
  3807. if (success_) *success_ = false;
  3808. if (finish_) *finish_ = false;
  3809. return value;
  3810. }
  3811. TypeAndValue tav = cl->elems[index]->tav;
  3812. if (tav.mode == Addressing_Constant) {
  3813. if (success_) *success_ = true;
  3814. if (finish_) *finish_ = false;
  3815. return tav.value;
  3816. } else {
  3817. GB_ASSERT(is_type_untyped_nil(tav.type));
  3818. if (success_) *success_ = true;
  3819. if (finish_) *finish_ = false;
  3820. return tav.value;
  3821. }
  3822. }
  3823. case_end;
  3824. default:
  3825. // TODO(bill): Should this be a general fallback?
  3826. if (success_) *success_ = true;
  3827. if (finish_) *finish_ = true;
  3828. return empty_exact_value;
  3829. }
  3830. if (finish_) *finish_ = false;
  3831. return value;
  3832. }
  3833. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3834. if (operand->mode != Addressing_Constant) {
  3835. if (success_) *success_ = false;
  3836. return empty_exact_value;
  3837. }
  3838. if (sel.indirect) {
  3839. if (success_) *success_ = false;
  3840. return empty_exact_value;
  3841. }
  3842. if (sel.index.count == 0) {
  3843. if (success_) *success_ = false;
  3844. return empty_exact_value;
  3845. }
  3846. ExactValue value = operand->value;
  3847. if (value.kind == ExactValue_Compound) {
  3848. while (sel.index.count > 0) {
  3849. i32 index = sel.index[0];
  3850. sel = sub_selection(sel, 1);
  3851. bool finish = false;
  3852. value = get_constant_field_single(c, value, index, success_, &finish);
  3853. if (finish) {
  3854. return value;
  3855. }
  3856. }
  3857. if (success_) *success_ = true;
  3858. return value;
  3859. } else if (value.kind == ExactValue_Quaternion) {
  3860. // @QuaternionLayout
  3861. Quaternion256 q = *value.value_quaternion;
  3862. GB_ASSERT(sel.index.count == 1);
  3863. switch (sel.index[0]) {
  3864. case 3: // w
  3865. if (success_) *success_ = true;
  3866. return exact_value_float(q.real);
  3867. case 0: // x
  3868. if (success_) *success_ = true;
  3869. return exact_value_float(q.imag);
  3870. case 1: // y
  3871. if (success_) *success_ = true;
  3872. return exact_value_float(q.jmag);
  3873. case 2: // z
  3874. if (success_) *success_ = true;
  3875. return exact_value_float(q.kmag);
  3876. }
  3877. if (success_) *success_ = false;
  3878. return empty_exact_value;
  3879. } else if (value.kind == ExactValue_Complex) {
  3880. // @QuaternionLayout
  3881. Complex128 c = *value.value_complex;
  3882. GB_ASSERT(sel.index.count == 1);
  3883. switch (sel.index[0]) {
  3884. case 0: // real
  3885. if (success_) *success_ = true;
  3886. return exact_value_float(c.real);
  3887. case 1: // imag
  3888. if (success_) *success_ = true;
  3889. return exact_value_float(c.imag);
  3890. }
  3891. if (success_) *success_ = false;
  3892. return empty_exact_value;
  3893. }
  3894. if (success_) *success_ = true;
  3895. return empty_exact_value;
  3896. }
  3897. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  3898. Type *array_type = base_type(type_deref(original_type));
  3899. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  3900. if (array_type->kind == Type_SimdVector) {
  3901. Type *elem_type = array_type->SimdVector.elem;
  3902. return alloc_type_simd_vector(new_count, elem_type);
  3903. }
  3904. Type *elem_type = array_type->Array.elem;
  3905. Type *swizzle_array_type = nullptr;
  3906. Type *bth = base_type(type_deref(type_hint));
  3907. if (bth != nullptr && bth->kind == Type_Array &&
  3908. bth->Array.count == new_count &&
  3909. are_types_identical(bth->Array.elem, elem_type)) {
  3910. swizzle_array_type = type_hint;
  3911. } else {
  3912. i64 max_count = array_type->Array.count;
  3913. if (new_count == max_count) {
  3914. swizzle_array_type = original_type;
  3915. } else {
  3916. swizzle_array_type = alloc_type_array(elem_type, new_count);
  3917. }
  3918. }
  3919. return swizzle_array_type;
  3920. }
  3921. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  3922. bool is_declared = entity != nullptr;
  3923. if (is_declared) {
  3924. if (entity->kind == Entity_Builtin) {
  3925. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  3926. // This means that we should just ignore the found result through it
  3927. *allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  3928. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  3929. is_declared = false;
  3930. }
  3931. }
  3932. return is_declared;
  3933. }
  3934. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  3935. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  3936. if (node->kind == Ast_Ident) {
  3937. String name = node->Ident.token.string;
  3938. return scope_lookup(c->scope, name);
  3939. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  3940. ast_node(se, SelectorExpr, node);
  3941. if (se->token.kind == Token_ArrowRight) {
  3942. return nullptr;
  3943. }
  3944. Ast *op_expr = se->expr;
  3945. Ast *selector = unparen_expr(se->selector);
  3946. if (selector == nullptr) {
  3947. return nullptr;
  3948. }
  3949. if (selector->kind != Ast_Ident) {
  3950. return nullptr;
  3951. }
  3952. Entity *entity = nullptr;
  3953. Entity *expr_entity = nullptr;
  3954. bool check_op_expr = true;
  3955. if (op_expr->kind == Ast_Ident) {
  3956. String op_name = op_expr->Ident.token.string;
  3957. Entity *e = scope_lookup(c->scope, op_name);
  3958. if (e == nullptr) {
  3959. return nullptr;
  3960. }
  3961. add_entity_use(c, op_expr, e);
  3962. expr_entity = e;
  3963. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  3964. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  3965. // It pretty much needs to be in this order and this way
  3966. // If you can clean this up, please do but be really careful
  3967. String import_name = op_name;
  3968. Scope *import_scope = e->ImportName.scope;
  3969. String entity_name = selector->Ident.token.string;
  3970. check_op_expr = false;
  3971. entity = scope_lookup_current(import_scope, entity_name);
  3972. bool allow_builtin = false;
  3973. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  3974. return nullptr;
  3975. }
  3976. check_entity_decl(c, entity, nullptr, nullptr);
  3977. if (entity->kind == Entity_ProcGroup) {
  3978. return entity;
  3979. }
  3980. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  3981. }
  3982. }
  3983. Operand operand = {};
  3984. if (check_op_expr) {
  3985. check_expr_base(c, &operand, op_expr, nullptr);
  3986. if (operand.mode == Addressing_Invalid) {
  3987. return nullptr;
  3988. }
  3989. }
  3990. if (entity == nullptr && selector->kind == Ast_Ident) {
  3991. String field_name = selector->Ident.token.string;
  3992. if (is_type_dynamic_array(type_deref(operand.type))) {
  3993. init_mem_allocator(c->checker);
  3994. }
  3995. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  3996. entity = sel.entity;
  3997. }
  3998. if (entity != nullptr) {
  3999. return entity;
  4000. }
  4001. }
  4002. return nullptr;
  4003. }
  4004. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4005. ast_node(se, SelectorExpr, node);
  4006. bool check_op_expr = true;
  4007. Entity *expr_entity = nullptr;
  4008. Entity *entity = nullptr;
  4009. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4010. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4011. error(node, "Illegal use of -> selector shorthand outside of a call");
  4012. operand->mode = Addressing_Invalid;
  4013. operand->expr = node;
  4014. return nullptr;
  4015. }
  4016. operand->expr = node;
  4017. Ast *op_expr = se->expr;
  4018. Ast *selector = unparen_expr(se->selector);
  4019. if (selector == nullptr) {
  4020. operand->mode = Addressing_Invalid;
  4021. operand->expr = node;
  4022. return nullptr;
  4023. }
  4024. if (selector->kind != Ast_Ident) {
  4025. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4026. operand->mode = Addressing_Invalid;
  4027. operand->expr = node;
  4028. return nullptr;
  4029. }
  4030. if (op_expr->kind == Ast_Ident) {
  4031. String op_name = op_expr->Ident.token.string;
  4032. Entity *e = scope_lookup(c->scope, op_name);
  4033. add_entity_use(c, op_expr, e);
  4034. expr_entity = e;
  4035. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4036. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4037. // It pretty much needs to be in this order and this way
  4038. // If you can clean this up, please do but be really careful
  4039. String import_name = op_name;
  4040. Scope *import_scope = e->ImportName.scope;
  4041. String entity_name = selector->Ident.token.string;
  4042. check_op_expr = false;
  4043. entity = scope_lookup_current(import_scope, entity_name);
  4044. bool allow_builtin = false;
  4045. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4046. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4047. operand->mode = Addressing_Invalid;
  4048. operand->expr = node;
  4049. check_did_you_mean_scope(entity_name, import_scope);
  4050. return nullptr;
  4051. }
  4052. check_entity_decl(c, entity, nullptr, nullptr);
  4053. if (entity->kind == Entity_ProcGroup) {
  4054. operand->mode = Addressing_ProcGroup;
  4055. operand->proc_group = entity;
  4056. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4057. return entity;
  4058. }
  4059. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4060. if (!is_entity_exported(entity, allow_builtin)) {
  4061. gbString sel_str = expr_to_string(selector);
  4062. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4063. gb_string_free(sel_str);
  4064. // NOTE(bill): make the state valid still, even if it's "invalid"
  4065. // operand->mode = Addressing_Invalid;
  4066. // operand->expr = node;
  4067. // return nullptr;
  4068. }
  4069. if (entity->kind == Entity_ProcGroup) {
  4070. Array<Entity *> procs = entity->ProcGroup.entities;
  4071. bool skip = false;
  4072. for (Entity *p : procs) {
  4073. Type *t = base_type(p->type);
  4074. if (t == t_invalid) {
  4075. continue;
  4076. }
  4077. Operand x = {};
  4078. x.mode = Addressing_Value;
  4079. x.type = t;
  4080. if (type_hint != nullptr) {
  4081. if (check_is_assignable_to(c, &x, type_hint)) {
  4082. entity = p;
  4083. skip = true;
  4084. break;
  4085. }
  4086. }
  4087. }
  4088. if (!skip) {
  4089. GB_ASSERT(entity != nullptr);
  4090. operand->mode = Addressing_ProcGroup;
  4091. operand->type = t_invalid;
  4092. operand->expr = node;
  4093. operand->proc_group = entity;
  4094. return entity;
  4095. }
  4096. }
  4097. }
  4098. }
  4099. if (check_op_expr) {
  4100. check_expr_base(c, operand, op_expr, nullptr);
  4101. if (operand->mode == Addressing_Invalid) {
  4102. operand->mode = Addressing_Invalid;
  4103. operand->expr = node;
  4104. return nullptr;
  4105. }
  4106. }
  4107. if (entity == nullptr && selector->kind == Ast_Ident) {
  4108. String field_name = selector->Ident.token.string;
  4109. if (is_type_dynamic_array(type_deref(operand->type))) {
  4110. init_mem_allocator(c->checker);
  4111. }
  4112. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4113. entity = sel.entity;
  4114. // NOTE(bill): Add type info needed for fields like 'names'
  4115. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4116. add_type_info_type(c, operand->type);
  4117. }
  4118. if (is_type_enum(operand->type)) {
  4119. add_type_info_type(c, operand->type);
  4120. }
  4121. }
  4122. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  4123. // TODO(bill): Simd_Vector swizzling
  4124. String field_name = selector->Ident.token.string;
  4125. if (1 < field_name.len && field_name.len <= 4) {
  4126. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4127. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4128. bool found_xyzw = false;
  4129. bool found_rgba = false;
  4130. for (isize i = 0; i < field_name.len; i++) {
  4131. bool valid = false;
  4132. for (isize j = 0; j < 4; j++) {
  4133. if (field_name.text[i] == swizzles_xyzw[j]) {
  4134. found_xyzw = true;
  4135. valid = true;
  4136. break;
  4137. }
  4138. if (field_name.text[i] == swizzles_rgba[j]) {
  4139. found_rgba = true;
  4140. valid = true;
  4141. break;
  4142. }
  4143. }
  4144. if (!valid) {
  4145. goto end_of_array_selector_swizzle;
  4146. }
  4147. }
  4148. u8 *swizzles = nullptr;
  4149. u8 index_count = cast(u8)field_name.len;
  4150. if (found_xyzw && found_rgba) {
  4151. gbString op_str = expr_to_string(op_expr);
  4152. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4153. gb_string_free(op_str);
  4154. operand->mode = Addressing_Invalid;
  4155. operand->expr = node;
  4156. return nullptr;
  4157. }
  4158. u8 indices = 0;
  4159. if (found_xyzw) {
  4160. swizzles = swizzles_xyzw;
  4161. } else if (found_rgba) {
  4162. swizzles = swizzles_rgba;
  4163. }
  4164. for (isize i = 0; i < field_name.len; i++) {
  4165. for (isize j = 0; j < 4; j++) {
  4166. if (field_name.text[i] == swizzles[j]) {
  4167. indices |= cast(u8)(j)<<(i*2);
  4168. break;
  4169. }
  4170. }
  4171. }
  4172. Type *original_type = operand->type;
  4173. Type *array_type = base_type(type_deref(original_type));
  4174. GB_ASSERT(array_type->kind == Type_Array);
  4175. i64 array_count = array_type->Array.count;
  4176. for (u8 i = 0; i < index_count; i++) {
  4177. u8 idx = indices>>(i*2) & 3;
  4178. if (idx >= array_count) {
  4179. char c = 0;
  4180. if (found_xyzw) {
  4181. c = swizzles_xyzw[idx];
  4182. } else if (found_rgba) {
  4183. c = swizzles_rgba[idx];
  4184. } else {
  4185. GB_PANIC("unknown swizzle kind");
  4186. }
  4187. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4188. break;
  4189. }
  4190. }
  4191. se->swizzle_count = index_count;
  4192. se->swizzle_indices = indices;
  4193. AddressingMode prev_mode = operand->mode;
  4194. operand->mode = Addressing_SwizzleValue;
  4195. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4196. operand->expr = node;
  4197. switch (prev_mode) {
  4198. case Addressing_Variable:
  4199. case Addressing_SoaVariable:
  4200. case Addressing_SwizzleVariable:
  4201. operand->mode = Addressing_SwizzleVariable;
  4202. break;
  4203. }
  4204. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4205. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4206. return swizzle_entity;
  4207. }
  4208. end_of_array_selector_swizzle:;
  4209. }
  4210. if (entity == nullptr) {
  4211. gbString op_str = expr_to_string(op_expr);
  4212. gbString type_str = type_to_string_shorthand(operand->type);
  4213. gbString sel_str = expr_to_string(selector);
  4214. if (operand->mode == Addressing_Type) {
  4215. if (is_type_polymorphic(operand->type, true)) {
  4216. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4217. } else {
  4218. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4219. }
  4220. } else {
  4221. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4222. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4223. String const &name = selector->Ident.token.string;
  4224. Type *bt = base_type(operand->type);
  4225. if (operand->type->kind == Type_Named &&
  4226. operand->type->Named.type_name &&
  4227. operand->type->Named.type_name->kind == Entity_TypeName &&
  4228. operand->type->Named.type_name->TypeName.objc_metadata) {
  4229. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4230. } else if (bt->kind == Type_Struct) {
  4231. check_did_you_mean_type(name, bt->Struct.fields);
  4232. } else if (bt->kind == Type_Enum) {
  4233. check_did_you_mean_type(name, bt->Enum.fields);
  4234. }
  4235. }
  4236. }
  4237. gb_string_free(sel_str);
  4238. gb_string_free(type_str);
  4239. gb_string_free(op_str);
  4240. operand->mode = Addressing_Invalid;
  4241. operand->expr = node;
  4242. return nullptr;
  4243. }
  4244. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4245. bool success = false;
  4246. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4247. if (success) {
  4248. operand->mode = Addressing_Constant;
  4249. operand->expr = node;
  4250. operand->value = field_value;
  4251. operand->type = entity->type;
  4252. add_entity_use(c, selector, entity);
  4253. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4254. return entity;
  4255. }
  4256. gbString op_str = expr_to_string(op_expr);
  4257. gbString type_str = type_to_string_shorthand(operand->type);
  4258. gbString sel_str = expr_to_string(selector);
  4259. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4260. gb_string_free(sel_str);
  4261. gb_string_free(type_str);
  4262. gb_string_free(op_str);
  4263. operand->mode = Addressing_Invalid;
  4264. operand->expr = node;
  4265. return nullptr;
  4266. }
  4267. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4268. bool success = false;
  4269. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4270. if (success) {
  4271. operand->mode = Addressing_Constant;
  4272. operand->expr = node;
  4273. operand->value = field_value;
  4274. operand->type = entity->type;
  4275. add_entity_use(c, selector, entity);
  4276. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4277. return entity;
  4278. }
  4279. gbString op_str = expr_to_string(op_expr);
  4280. gbString type_str = type_to_string_shorthand(operand->type);
  4281. gbString sel_str = expr_to_string(selector);
  4282. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4283. gb_string_free(sel_str);
  4284. gb_string_free(type_str);
  4285. gb_string_free(op_str);
  4286. operand->mode = Addressing_Invalid;
  4287. operand->expr = node;
  4288. return nullptr;
  4289. }
  4290. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4291. gbString op_str = expr_to_string(op_expr);
  4292. gbString type_str = type_to_string_shorthand(operand->type);
  4293. gbString sel_str = expr_to_string(selector);
  4294. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4295. gb_string_free(sel_str);
  4296. gb_string_free(type_str);
  4297. gb_string_free(op_str);
  4298. operand->mode = Addressing_Invalid;
  4299. operand->expr = node;
  4300. return nullptr;
  4301. }
  4302. add_entity_use(c, selector, entity);
  4303. operand->type = entity->type;
  4304. operand->expr = node;
  4305. switch (entity->kind) {
  4306. case Entity_Constant:
  4307. operand->value = entity->Constant.value;
  4308. operand->mode = Addressing_Constant;
  4309. if (operand->value.kind == ExactValue_Procedure) {
  4310. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4311. if (proc != nullptr) {
  4312. operand->mode = Addressing_Value;
  4313. operand->type = proc->type;
  4314. }
  4315. }
  4316. break;
  4317. case Entity_Variable:
  4318. if (sel.indirect) {
  4319. operand->mode = Addressing_Variable;
  4320. } else if (operand->mode == Addressing_Context) {
  4321. // Do nothing
  4322. } else if (operand->mode == Addressing_MapIndex) {
  4323. operand->mode = Addressing_Value;
  4324. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4325. operand->mode = Addressing_SoaVariable;
  4326. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4327. operand->mode = Addressing_Value;
  4328. } else if (operand->mode == Addressing_SoaVariable) {
  4329. operand->mode = Addressing_Variable;
  4330. } else if (operand->mode != Addressing_Value) {
  4331. operand->mode = Addressing_Variable;
  4332. } else {
  4333. operand->mode = Addressing_Value;
  4334. }
  4335. break;
  4336. case Entity_TypeName:
  4337. operand->mode = Addressing_Type;
  4338. break;
  4339. case Entity_Procedure:
  4340. operand->mode = Addressing_Value;
  4341. operand->value = exact_value_procedure(node);
  4342. break;
  4343. case Entity_Builtin:
  4344. operand->mode = Addressing_Builtin;
  4345. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4346. break;
  4347. case Entity_ProcGroup:
  4348. operand->mode = Addressing_ProcGroup;
  4349. operand->proc_group = entity;
  4350. break;
  4351. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4352. case Entity_Nil:
  4353. operand->mode = Addressing_Value;
  4354. break;
  4355. }
  4356. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4357. return entity;
  4358. }
  4359. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4360. ptr = base_type(ptr);
  4361. if (is_type_pointer(ptr)) {
  4362. if (is_type_rawptr(ptr)) {
  4363. return false;
  4364. }
  4365. if (elem) *elem = ptr->Pointer.elem;
  4366. return true;
  4367. }
  4368. return false;
  4369. }
  4370. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4371. elem = core_type(elem);
  4372. if (is_type_internally_pointer_like(elem)) {
  4373. return true;
  4374. }
  4375. if (elem->kind == Type_BitSet) {
  4376. elem = bit_set_to_int(elem);
  4377. }
  4378. if (elem->kind != Type_Basic) {
  4379. return false;
  4380. }
  4381. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4382. }
  4383. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4384. switch (node->kind) {
  4385. case_ast_node(i, Ident, node);
  4386. String name = i->token.string;
  4387. if (nested) {
  4388. Entity *e = scope_lookup_current(s, name);
  4389. if (e != nullptr) {
  4390. if (out_scope) *out_scope = e->scope;
  4391. return true;
  4392. }
  4393. } else {
  4394. Entity *e = scope_lookup(s, name);
  4395. if (e != nullptr) {
  4396. if (out_scope) *out_scope = e->scope;
  4397. return true;
  4398. }
  4399. }
  4400. case_end;
  4401. case_ast_node(se, SelectorExpr, node);
  4402. Ast *lhs = se->expr;
  4403. Ast *rhs = se->selector;
  4404. Scope *lhs_scope = nullptr;
  4405. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4406. return check_identifier_exists(lhs_scope, rhs, true);
  4407. }
  4408. case_end;
  4409. }
  4410. return false;
  4411. }
  4412. gb_internal isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) {
  4413. if (lhs != nullptr && c->decl != nullptr) {
  4414. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4415. Entity *e = lhs[tuple_index + j];
  4416. if (e != nullptr) {
  4417. DeclInfo *decl = decl_info_of_entity(e);
  4418. if (decl != nullptr) {
  4419. rw_mutex_shared_lock(&decl->deps_mutex);
  4420. rw_mutex_lock(&c->decl->deps_mutex);
  4421. for (Entity *dep : decl->deps) {
  4422. ptr_set_add(&c->decl->deps, dep);
  4423. }
  4424. rw_mutex_unlock(&c->decl->deps_mutex);
  4425. rw_mutex_shared_unlock(&decl->deps_mutex);
  4426. }
  4427. }
  4428. }
  4429. }
  4430. return tuple_count;
  4431. }
  4432. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4433. bool optional_ok = false;
  4434. isize tuple_index = 0;
  4435. for (Ast *rhs_expr : rhs) {
  4436. CheckerContext c_ = *ctx;
  4437. CheckerContext *c = &c_;
  4438. Operand o = {};
  4439. Type *type_hint = nullptr;
  4440. if (tuple_index < lhs.count) {
  4441. type_hint = lhs[tuple_index].type;
  4442. }
  4443. check_expr_base(c, &o, rhs_expr, type_hint);
  4444. if (o.mode == Addressing_NoValue) {
  4445. error_operand_no_value(&o);
  4446. o.mode = Addressing_Invalid;
  4447. }
  4448. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4449. if (lhs.count == 2 && rhs.count == 1 &&
  4450. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4451. Ast *expr = unparen_expr(o.expr);
  4452. Operand val0 = o;
  4453. Operand val1 = o;
  4454. val0.mode = Addressing_Value;
  4455. val1.mode = Addressing_Value;
  4456. val1.type = t_untyped_bool;
  4457. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4458. if (expr->kind == Ast_TypeAssertion &&
  4459. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4460. // NOTE(bill): Used only for optimizations in the backend
  4461. if (is_blank_ident(lhs[0].expr)) {
  4462. expr->TypeAssertion.ignores[0] = true;
  4463. }
  4464. if (is_blank_ident(lhs[1].expr)) {
  4465. expr->TypeAssertion.ignores[1] = true;
  4466. }
  4467. }
  4468. array_add(operands, val0);
  4469. array_add(operands, val1);
  4470. optional_ok = true;
  4471. tuple_index += 2;
  4472. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4473. Type *tuple = o.type;
  4474. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4475. Ast *expr = unparen_expr(o.expr);
  4476. if (expr->kind == Ast_CallExpr) {
  4477. expr->CallExpr.optional_ok_one = true;
  4478. }
  4479. Operand val = o;
  4480. val.type = tuple->Tuple.variables[0]->type;
  4481. val.mode = Addressing_Value;
  4482. array_add(operands, val);
  4483. tuple_index += tuple->Tuple.variables.count;
  4484. } else {
  4485. array_add(operands, o);
  4486. tuple_index += 1;
  4487. }
  4488. } else {
  4489. TypeTuple *tuple = &o.type->Tuple;
  4490. for (Entity *e : tuple->variables) {
  4491. o.type = e->type;
  4492. array_add(operands, o);
  4493. }
  4494. tuple_index += tuple->variables.count;
  4495. }
  4496. }
  4497. return optional_ok;
  4498. }
  4499. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs, bool allow_ok, bool is_variadic) {
  4500. bool optional_ok = false;
  4501. isize tuple_index = 0;
  4502. for_array(i, rhs) {
  4503. CheckerContext c_ = *ctx;
  4504. CheckerContext *c = &c_;
  4505. Operand o = {};
  4506. Type *type_hint = nullptr;
  4507. if (lhs != nullptr && tuple_index < lhs_count) {
  4508. // NOTE(bill): override DeclInfo for dependency
  4509. Entity *e = lhs[tuple_index];
  4510. if (e != nullptr) {
  4511. // DeclInfo *decl = decl_info_of_entity(e);
  4512. // if (decl) c->decl = decl;
  4513. type_hint = e->type;
  4514. if (e->flags & EntityFlag_Ellipsis) {
  4515. GB_ASSERT(is_type_slice(e->type));
  4516. GB_ASSERT(e->type->kind == Type_Slice);
  4517. type_hint = e->type->Slice.elem;
  4518. }
  4519. }
  4520. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4521. // NOTE(bill): override DeclInfo for dependency
  4522. Entity *e = lhs[lhs_count-1];
  4523. if (e != nullptr) {
  4524. // DeclInfo *decl = decl_info_of_entity(e);
  4525. // if (decl) c->decl = decl;
  4526. type_hint = e->type;
  4527. if (e->flags & EntityFlag_Ellipsis) {
  4528. GB_ASSERT(is_type_slice(e->type));
  4529. GB_ASSERT(e->type->kind == Type_Slice);
  4530. type_hint = e->type->Slice.elem;
  4531. }
  4532. }
  4533. }
  4534. check_expr_base(c, &o, rhs[i], type_hint);
  4535. if (o.mode == Addressing_NoValue) {
  4536. error_operand_no_value(&o);
  4537. o.mode = Addressing_Invalid;
  4538. }
  4539. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4540. if (allow_ok && lhs_count == 2 && rhs.count == 1 &&
  4541. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4542. Ast *expr = unparen_expr(o.expr);
  4543. Operand val0 = o;
  4544. Operand val1 = o;
  4545. val0.mode = Addressing_Value;
  4546. val1.mode = Addressing_Value;
  4547. val1.type = t_untyped_bool;
  4548. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4549. if (expr->kind == Ast_TypeAssertion &&
  4550. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4551. // NOTE(bill): Used only for optimizations in the backend
  4552. if (is_blank_ident(lhs[0]->token)) {
  4553. expr->TypeAssertion.ignores[0] = true;
  4554. }
  4555. if (is_blank_ident(lhs[1]->token)) {
  4556. expr->TypeAssertion.ignores[1] = true;
  4557. }
  4558. }
  4559. array_add(operands, val0);
  4560. array_add(operands, val1);
  4561. optional_ok = true;
  4562. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4563. } else {
  4564. array_add(operands, o);
  4565. tuple_index += 1;
  4566. }
  4567. } else {
  4568. TypeTuple *tuple = &o.type->Tuple;
  4569. for (Entity *e : tuple->variables) {
  4570. o.type = e->type;
  4571. array_add(operands, o);
  4572. }
  4573. isize count = tuple->variables.count;
  4574. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4575. }
  4576. }
  4577. return optional_ok;
  4578. }
  4579. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4580. GB_ASSERT(pt != nullptr);
  4581. GB_ASSERT(pt->kind == Type_Proc);
  4582. isize param_count = 0;
  4583. isize param_count_excluding_defaults = 0;
  4584. bool variadic = pt->Proc.variadic;
  4585. TypeTuple *param_tuple = nullptr;
  4586. if (pt->Proc.params != nullptr) {
  4587. param_tuple = &pt->Proc.params->Tuple;
  4588. param_count = param_tuple->variables.count;
  4589. if (variadic) {
  4590. for (isize i = param_count-1; i >= 0; i--) {
  4591. Entity *e = param_tuple->variables[i];
  4592. if (e->kind == Entity_TypeName) {
  4593. break;
  4594. }
  4595. if (e->kind == Entity_Variable) {
  4596. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4597. param_count--;
  4598. continue;
  4599. }
  4600. }
  4601. break;
  4602. }
  4603. param_count--;
  4604. }
  4605. }
  4606. param_count_excluding_defaults = param_count;
  4607. if (param_tuple != nullptr) {
  4608. for (isize i = param_count-1; i >= 0; i--) {
  4609. Entity *e = param_tuple->variables[i];
  4610. if (e->kind == Entity_TypeName) {
  4611. break;
  4612. }
  4613. if (e->kind == Entity_Variable) {
  4614. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4615. param_count_excluding_defaults--;
  4616. continue;
  4617. }
  4618. }
  4619. break;
  4620. }
  4621. }
  4622. if (param_count_) *param_count_ = param_count;
  4623. return param_count_excluding_defaults;
  4624. }
  4625. gb_internal CALL_ARGUMENT_CHECKER(check_call_arguments_internal) {
  4626. ast_node(ce, CallExpr, call);
  4627. GB_ASSERT(is_type_proc(proc_type));
  4628. proc_type = base_type(proc_type);
  4629. TypeProc *pt = &proc_type->Proc;
  4630. isize param_count = 0;
  4631. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4632. bool variadic = pt->variadic;
  4633. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4634. i64 score = 0;
  4635. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  4636. TypeTuple *param_tuple = nullptr;
  4637. if (pt->params != nullptr) {
  4638. param_tuple = &pt->params->Tuple;
  4639. }
  4640. CallArgumentError err = CallArgumentError_None;
  4641. Type *final_proc_type = proc_type;
  4642. Entity *gen_entity = nullptr;
  4643. if (vari_expand && !variadic) {
  4644. if (show_error) {
  4645. error(ce->ellipsis,
  4646. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4647. LIT(ce->proc->Ident.token.string));
  4648. }
  4649. err = CallArgumentError_NonVariadicExpand;
  4650. } else if (vari_expand && pt->c_vararg) {
  4651. if (show_error) {
  4652. error(ce->ellipsis,
  4653. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4654. LIT(ce->proc->Ident.token.string));
  4655. }
  4656. err = CallArgumentError_NonVariadicExpand;
  4657. } else if (operands.count == 0 && param_count_excluding_defaults == 0) {
  4658. err = CallArgumentError_None;
  4659. if (variadic) {
  4660. GB_ASSERT(param_tuple != nullptr && param_tuple->variables.count > 0);
  4661. Type *t = param_tuple->variables[0]->type;
  4662. if (is_type_polymorphic(t)) {
  4663. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4664. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4665. }
  4666. }
  4667. } else {
  4668. i32 error_code = 0;
  4669. if (operands.count < param_count_excluding_defaults) {
  4670. error_code = -1;
  4671. } else if (!variadic && operands.count > param_count) {
  4672. error_code = +1;
  4673. }
  4674. if (error_code != 0) {
  4675. err = CallArgumentError_TooManyArguments;
  4676. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4677. if (error_code < 0) {
  4678. err = CallArgumentError_TooFewArguments;
  4679. err_fmt = "Too few arguments for '%s', expected %td arguments, got %td";
  4680. }
  4681. if (show_error) {
  4682. gbString proc_str = expr_to_string(ce->proc);
  4683. defer (gb_string_free(proc_str));
  4684. error(call, err_fmt, proc_str, param_count_excluding_defaults, operands.count);
  4685. #if 0
  4686. error_line("\t");
  4687. for_array(i, operands) {
  4688. if (i > 0) {
  4689. error_line(", ");
  4690. }
  4691. gbString s = expr_to_string(operands[i].expr);
  4692. error_line("%s", s);
  4693. gb_string_free(s);
  4694. }
  4695. error_line("\n");
  4696. #endif
  4697. }
  4698. } else {
  4699. // NOTE(bill): Generate the procedure type for this generic instance
  4700. if (pt->is_polymorphic && !pt->is_poly_specialized) {
  4701. PolyProcData poly_proc_data = {};
  4702. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &operands, call, &poly_proc_data)) {
  4703. gen_entity = poly_proc_data.gen_entity;
  4704. GB_ASSERT(is_type_proc(gen_entity->type));
  4705. final_proc_type = gen_entity->type;
  4706. } else {
  4707. err = CallArgumentError_WrongTypes;
  4708. }
  4709. }
  4710. GB_ASSERT(is_type_proc(final_proc_type));
  4711. TypeProc *pt = &final_proc_type->Proc;
  4712. GB_ASSERT(pt->params != nullptr);
  4713. auto sig_params = pt->params->Tuple.variables;
  4714. isize operand_index = 0;
  4715. isize max_operand_count = gb_min(param_count, operands.count);
  4716. for (; operand_index < max_operand_count; operand_index++) {
  4717. Entity *e = sig_params[operand_index];
  4718. Type *t = e->type;
  4719. Operand o = operands[operand_index];
  4720. if (o.expr != nullptr) {
  4721. call->viral_state_flags |= o.expr->viral_state_flags;
  4722. }
  4723. if (e->kind == Entity_TypeName) {
  4724. // GB_ASSERT(!variadic);
  4725. if (o.mode == Addressing_Invalid) {
  4726. continue;
  4727. } else if (o.mode != Addressing_Type) {
  4728. if (show_error) {
  4729. error(o.expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  4730. }
  4731. err = CallArgumentError_WrongTypes;
  4732. }
  4733. if (are_types_identical(e->type, o.type)) {
  4734. score += assign_score_function(1);
  4735. } else {
  4736. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4737. }
  4738. continue;
  4739. }
  4740. bool param_is_variadic = pt->variadic && pt->variadic_index == operand_index;
  4741. i64 s = 0;
  4742. if (!check_is_assignable_to_with_score(c, &o, t, &s, param_is_variadic)) {
  4743. bool ok = false;
  4744. if (e->flags & EntityFlag_AnyInt) {
  4745. if (is_type_integer(t)) {
  4746. ok = check_is_castable_to(c, &o, t);
  4747. }
  4748. }
  4749. if (ok) {
  4750. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4751. } else {
  4752. if (show_error) {
  4753. check_assignment(c, &o, t, str_lit("argument"));
  4754. }
  4755. // TODO(bill, 2021-05-05): Is this incorrect logic to only fail if there is ambiguity for definite?
  4756. if (o.mode == Addressing_Invalid) {
  4757. err = CallArgumentError_WrongTypes;
  4758. }
  4759. }
  4760. } else if (show_error) {
  4761. check_assignment(c, &o, t, str_lit("argument"));
  4762. }
  4763. score += s;
  4764. if (e->flags & EntityFlag_ConstInput) {
  4765. if (o.mode != Addressing_Constant) {
  4766. if (show_error) {
  4767. error(o.expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4768. }
  4769. err = CallArgumentError_NoneConstantParameter;
  4770. }
  4771. }
  4772. if (o.mode == Addressing_Type && is_type_typeid(e->type)) {
  4773. add_type_info_type(c, o.type);
  4774. add_type_and_value(c, o.expr, Addressing_Value, e->type, exact_value_typeid(o.type));
  4775. } else if (show_error && is_type_untyped(o.type)) {
  4776. update_untyped_expr_type(c, o.expr, t, true);
  4777. }
  4778. }
  4779. if (variadic) {
  4780. bool variadic_expand = false;
  4781. Type *slice = sig_params[param_count]->type;
  4782. GB_ASSERT(is_type_slice(slice));
  4783. Type *elem = base_type(slice)->Slice.elem;
  4784. Type *t = elem;
  4785. if (is_type_polymorphic(t)) {
  4786. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4787. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4788. }
  4789. for (; operand_index < operands.count; operand_index++) {
  4790. Operand o = operands[operand_index];
  4791. if (vari_expand) {
  4792. variadic_expand = true;
  4793. t = slice;
  4794. if (operand_index != param_count) {
  4795. if (show_error) {
  4796. error(o.expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  4797. }
  4798. if (data) {
  4799. data->score = score;
  4800. data->result_type = final_proc_type->Proc.results;
  4801. data->gen_entity = gen_entity;
  4802. }
  4803. return CallArgumentError_MultipleVariadicExpand;
  4804. }
  4805. }
  4806. i64 s = 0;
  4807. if (!check_is_assignable_to_with_score(c, &o, t, &s, true)) {
  4808. if (show_error) {
  4809. check_assignment(c, &o, t, str_lit("argument"));
  4810. }
  4811. err = CallArgumentError_WrongTypes;
  4812. } else if (show_error) {
  4813. check_assignment(c, &o, t, str_lit("argument"));
  4814. }
  4815. score += s;
  4816. if (is_type_any(elem)) {
  4817. add_type_info_type(c, o.type);
  4818. }
  4819. if (o.mode == Addressing_Type && is_type_typeid(t)) {
  4820. add_type_info_type(c, o.type);
  4821. add_type_and_value(c, o.expr, Addressing_Value, t, exact_value_typeid(o.type));
  4822. } else if (show_error && is_type_untyped(o.type)) {
  4823. update_untyped_expr_type(c, o.expr, t, true);
  4824. }
  4825. }
  4826. }
  4827. }
  4828. }
  4829. if (data) {
  4830. data->score = score;
  4831. data->result_type = final_proc_type->Proc.results;
  4832. data->gen_entity = gen_entity;
  4833. Ast *proc_lit = nullptr;
  4834. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  4835. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  4836. if (vp && vp->kind == Ast_ProcLit) {
  4837. proc_lit = vp;
  4838. }
  4839. }
  4840. if (proc_lit == nullptr) {
  4841. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  4842. }
  4843. }
  4844. return err;
  4845. }
  4846. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  4847. GB_ASSERT(ce != nullptr);
  4848. if (ce->args.count == 0) {
  4849. return false;
  4850. }
  4851. return ce->args[0]->kind == Ast_FieldValue;
  4852. }
  4853. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String parameter_name) {
  4854. isize param_count = pt->param_count;
  4855. for (isize i = 0; i < param_count; i++) {
  4856. Entity *e = pt->params->Tuple.variables[i];
  4857. String name = e->token.string;
  4858. if (is_blank_ident(name)) {
  4859. continue;
  4860. }
  4861. if (name == parameter_name) {
  4862. return i;
  4863. }
  4864. }
  4865. return -1;
  4866. }
  4867. gb_internal CALL_ARGUMENT_CHECKER(check_named_call_arguments) {
  4868. ast_node(ce, CallExpr, call);
  4869. GB_ASSERT(is_type_proc(proc_type));
  4870. proc_type = base_type(proc_type);
  4871. TypeProc *pt = &proc_type->Proc;
  4872. i64 score = 0;
  4873. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  4874. CallArgumentError err = CallArgumentError_None;
  4875. TEMPORARY_ALLOCATOR_GUARD();
  4876. isize param_count = pt->param_count;
  4877. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  4878. auto ordered_operands = array_make<Operand>(temporary_allocator(), param_count);
  4879. defer ({
  4880. for (Operand const &o : ordered_operands) {
  4881. if (o.expr != nullptr) {
  4882. call->viral_state_flags |= o.expr->viral_state_flags;
  4883. }
  4884. }
  4885. });
  4886. for_array(i, ce->args) {
  4887. Ast *arg = ce->args[i];
  4888. ast_node(fv, FieldValue, arg);
  4889. if (fv->field->kind != Ast_Ident) {
  4890. if (show_error) {
  4891. gbString expr_str = expr_to_string(fv->field);
  4892. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4893. gb_string_free(expr_str);
  4894. }
  4895. err = CallArgumentError_InvalidFieldValue;
  4896. continue;
  4897. }
  4898. String name = fv->field->Ident.token.string;
  4899. isize index = lookup_procedure_parameter(pt, name);
  4900. if (index < 0) {
  4901. if (show_error) {
  4902. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4903. }
  4904. err = CallArgumentError_ParameterNotFound;
  4905. continue;
  4906. }
  4907. if (visited[index]) {
  4908. if (show_error) {
  4909. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4910. }
  4911. err = CallArgumentError_DuplicateParameter;
  4912. continue;
  4913. }
  4914. visited[index] = true;
  4915. ordered_operands[index] = operands[i];
  4916. }
  4917. // NOTE(bill): Check for default values and missing parameters
  4918. isize param_count_to_check = param_count;
  4919. if (pt->variadic) {
  4920. param_count_to_check--;
  4921. }
  4922. for (isize i = 0; i < param_count_to_check; i++) {
  4923. if (!visited[i]) {
  4924. Entity *e = pt->params->Tuple.variables[i];
  4925. if (is_blank_ident(e->token)) {
  4926. continue;
  4927. }
  4928. if (e->kind == Entity_Variable) {
  4929. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4930. score += assign_score_function(1);
  4931. continue;
  4932. }
  4933. }
  4934. if (show_error) {
  4935. if (e->kind == Entity_TypeName) {
  4936. error(call, "Type parameter '%.*s' is missing in procedure call",
  4937. LIT(e->token.string));
  4938. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4939. // Ignore
  4940. } else {
  4941. gbString str = type_to_string(e->type);
  4942. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4943. LIT(e->token.string), str);
  4944. gb_string_free(str);
  4945. }
  4946. }
  4947. err = CallArgumentError_ParameterMissing;
  4948. }
  4949. }
  4950. Entity *gen_entity = nullptr;
  4951. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  4952. PolyProcData poly_proc_data = {};
  4953. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  4954. gen_entity = poly_proc_data.gen_entity;
  4955. Type *gept = base_type(gen_entity->type);
  4956. GB_ASSERT(is_type_proc(gept));
  4957. proc_type = gept;
  4958. pt = &gept->Proc;
  4959. } else {
  4960. err = CallArgumentError_WrongTypes;
  4961. }
  4962. }
  4963. for (isize i = 0; i < param_count; i++) {
  4964. Entity *e = pt->params->Tuple.variables[i];
  4965. Operand *o = &ordered_operands[i];
  4966. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  4967. if (o->mode == Addressing_Invalid) {
  4968. if (param_is_variadic) {
  4969. Type *slice = e->type;
  4970. GB_ASSERT(is_type_slice(slice));
  4971. Type *elem = base_type(slice)->Slice.elem;
  4972. if (is_type_polymorphic(elem)) {
  4973. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4974. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4975. return err;
  4976. }
  4977. }
  4978. continue;
  4979. }
  4980. if (e->kind == Entity_TypeName) {
  4981. GB_ASSERT(pt->is_polymorphic);
  4982. if (o->mode != Addressing_Type) {
  4983. if (show_error) {
  4984. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  4985. }
  4986. err = CallArgumentError_WrongTypes;
  4987. }
  4988. if (are_types_identical(e->type, o->type)) {
  4989. score += assign_score_function(1);
  4990. } else {
  4991. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4992. }
  4993. } else {
  4994. i64 s = 0;
  4995. if (!check_is_assignable_to_with_score(c, o, e->type, &s, param_is_variadic)) {
  4996. bool ok = false;
  4997. if (ok) {
  4998. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4999. } else {
  5000. if (show_error) {
  5001. check_assignment(c, o, e->type, str_lit("procedure argument"));
  5002. }
  5003. err = CallArgumentError_WrongTypes;
  5004. }
  5005. if (e->flags & EntityFlag_ConstInput) {
  5006. if (o->mode != Addressing_Constant) {
  5007. if (show_error) {
  5008. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5009. }
  5010. err = CallArgumentError_NoneConstantParameter;
  5011. }
  5012. }
  5013. } else if (show_error) {
  5014. check_assignment(c, o, e->type, str_lit("procedure argument"));
  5015. }
  5016. score += s;
  5017. }
  5018. if (o->mode == Addressing_Type && is_type_typeid(e->type)) {
  5019. add_type_info_type(c, o->type);
  5020. add_type_and_value(c, o->expr, Addressing_Value, e->type, exact_value_typeid(o->type));
  5021. }
  5022. }
  5023. if (data) {
  5024. data->score = score;
  5025. data->result_type = pt->results;
  5026. data->gen_entity = gen_entity;
  5027. add_type_and_value(c, ce->proc, Addressing_Value, proc_type, {});
  5028. }
  5029. return err;
  5030. }
  5031. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5032. Entity **lhs = nullptr;
  5033. isize lhs_count = -1;
  5034. if (proc_type == nullptr) {
  5035. return nullptr;
  5036. }
  5037. GB_ASSERT(is_type_proc(proc_type));
  5038. TypeProc *pt = &base_type(proc_type)->Proc;
  5039. *is_variadic = pt->variadic;
  5040. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5041. if (pt->params != nullptr) {
  5042. lhs = pt->params->Tuple.variables.data;
  5043. lhs_count = pt->params->Tuple.variables.count;
  5044. }
  5045. } else {
  5046. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5047. if (pt->params == nullptr) {
  5048. lhs_count = 0;
  5049. } else {
  5050. lhs_count = pt->params->Tuple.variables.count;
  5051. }
  5052. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5053. for (isize i = 0; i < lhs_count; i++) {
  5054. Entity *e = pt->params->Tuple.variables[i];
  5055. if (!is_type_polymorphic(e->type)) {
  5056. lhs[i] = e;
  5057. }
  5058. }
  5059. }
  5060. if (lhs_count_) *lhs_count_ = lhs_count;
  5061. return lhs;
  5062. }
  5063. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5064. if (clauses != nullptr) {
  5065. for (Ast *clause : *clauses) {
  5066. Operand o = {};
  5067. check_expr(ctx, &o, clause);
  5068. if (o.mode != Addressing_Constant) {
  5069. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5070. if (print_err && call_expr) error(call_expr, "at caller location");
  5071. return false;
  5072. } else if (o.value.kind != ExactValue_Bool) {
  5073. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5074. if (print_err && call_expr) error(call_expr, "at caller location");
  5075. return false;
  5076. } else if (!o.value.value_bool) {
  5077. if (print_err) {
  5078. ERROR_BLOCK();
  5079. gbString str = expr_to_string(clause);
  5080. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5081. gb_string_free(str);
  5082. if (scope != nullptr) {
  5083. isize print_count = 0;
  5084. for (auto const &entry : scope->elements) {
  5085. Entity *e = entry.value;
  5086. switch (e->kind) {
  5087. case Entity_TypeName: {
  5088. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5089. gbString str = type_to_string(e->type);
  5090. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5091. gb_string_free(str);
  5092. print_count += 1;
  5093. break;
  5094. }
  5095. case Entity_Constant: {
  5096. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5097. gbString str = exact_value_to_string(e->Constant.value);
  5098. if (is_type_untyped(e->type)) {
  5099. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5100. } else {
  5101. gbString t = type_to_string(e->type);
  5102. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5103. gb_string_free(t);
  5104. }
  5105. gb_string_free(str);
  5106. print_count += 1;
  5107. break;
  5108. }
  5109. }
  5110. }
  5111. }
  5112. if (call_expr) error(call_expr, "at caller location");
  5113. }
  5114. return false;
  5115. }
  5116. }
  5117. }
  5118. return true;
  5119. }
  5120. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Type *proc_type, Ast *call, Slice<Ast *> const &args) {
  5121. ast_node(ce, CallExpr, call);
  5122. CallArgumentCheckerType *call_checker = check_call_arguments_internal;
  5123. Array<Operand> operands = {};
  5124. defer (array_free(&operands));
  5125. Type *result_type = t_invalid;
  5126. if (is_call_expr_field_value(ce)) {
  5127. call_checker = check_named_call_arguments;
  5128. operands = array_make<Operand>(heap_allocator(), args.count);
  5129. // NOTE(bill): This is give type hints for the named parameters
  5130. // in order to improve the type inference system
  5131. StringMap<Type *> type_hint_map = {}; // Key: String
  5132. string_map_init(&type_hint_map, 2*args.count);
  5133. defer (string_map_destroy(&type_hint_map));
  5134. Type *ptype = nullptr;
  5135. bool single_case = true;
  5136. if (operand->mode == Addressing_ProcGroup) {
  5137. single_case = false;
  5138. Array<Entity *> procs = proc_group_entities(c, *operand);
  5139. if (procs.count == 1) {
  5140. ptype = procs[0]->type;
  5141. single_case = true;
  5142. }
  5143. } else {
  5144. ptype = proc_type;
  5145. }
  5146. if (single_case) {
  5147. Type *bptype = base_type(ptype);
  5148. if (is_type_proc(bptype)) {
  5149. TypeProc *pt = &bptype->Proc;
  5150. TypeTuple *param_tuple = nullptr;
  5151. if (pt->params != nullptr) {
  5152. param_tuple = &pt->params->Tuple;
  5153. }
  5154. if (param_tuple != nullptr) {
  5155. for (Entity *e : param_tuple->variables) {
  5156. if (is_blank_ident(e->token)) {
  5157. continue;
  5158. }
  5159. string_map_set(&type_hint_map, e->token.string, e->type);
  5160. }
  5161. }
  5162. }
  5163. } else {
  5164. Array<Entity *> procs = proc_group_entities(c, *operand);
  5165. for (Entity *proc : procs) {
  5166. Type *proc_type = base_type(proc->type);
  5167. if (is_type_proc(proc_type)) {
  5168. TypeProc *pt = &proc_type->Proc;
  5169. TypeTuple *param_tuple = nullptr;
  5170. if (pt->params != nullptr) {
  5171. param_tuple = &pt->params->Tuple;
  5172. }
  5173. if (param_tuple == nullptr) {
  5174. continue;
  5175. }
  5176. for (Entity *e : param_tuple->variables) {
  5177. if (is_blank_ident(e->token)) {
  5178. continue;
  5179. }
  5180. StringHashKey key = string_hash_string(e->token.string);
  5181. Type **found = string_map_get(&type_hint_map, key);
  5182. if (found) {
  5183. Type *t = *found;
  5184. if (t == nullptr) {
  5185. // NOTE(bill): Ambiguous named parameter across all types
  5186. continue;
  5187. }
  5188. if (are_types_identical(t, e->type)) {
  5189. // NOTE(bill): No need to set again
  5190. } else {
  5191. // NOTE(bill): Ambiguous named parameter across all types so set it to a nullptr
  5192. string_map_set(&type_hint_map, key, cast(Type *)nullptr);
  5193. }
  5194. } else {
  5195. string_map_set(&type_hint_map, key, e->type);
  5196. }
  5197. }
  5198. }
  5199. }
  5200. }
  5201. for_array(i, args) {
  5202. Ast *arg = args[i];
  5203. ast_node(fv, FieldValue, arg);
  5204. Ast *field = fv->field;
  5205. Type *type_hint = nullptr;
  5206. if (field != nullptr && field->kind == Ast_Ident) {
  5207. String key = field->Ident.token.string;
  5208. Type **found = string_map_get(&type_hint_map, key);
  5209. if (found) {
  5210. type_hint = *found;
  5211. }
  5212. }
  5213. check_expr_or_type(c, &operands[i], fv->value, type_hint);
  5214. }
  5215. } else {
  5216. operands = array_make<Operand>(heap_allocator(), 0, 2*args.count);
  5217. Entity **lhs = nullptr;
  5218. isize lhs_count = -1;
  5219. bool is_variadic = false;
  5220. if (proc_type != nullptr && is_type_proc(proc_type)) {
  5221. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5222. }
  5223. if (operand->mode != Addressing_ProcGroup) {
  5224. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, is_variadic);
  5225. }
  5226. }
  5227. if (operand->mode == Addressing_ProcGroup) {
  5228. check_entity_decl(c, operand->proc_group, nullptr, nullptr);
  5229. auto procs = proc_group_entities_cloned(c, *operand);
  5230. if (procs.count > 1) {
  5231. isize max_arg_count = args.count;
  5232. for (Ast *arg : args) {
  5233. // NOTE(bill): The only thing that may have multiple values
  5234. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5235. arg = strip_or_return_expr(arg);
  5236. if (arg && arg->kind == Ast_CallExpr) {
  5237. max_arg_count = ISIZE_MAX;
  5238. break;
  5239. }
  5240. }
  5241. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5242. Entity *proc = procs[proc_index];
  5243. Type *pt = base_type(proc->type);
  5244. if (!(pt != nullptr && is_type_proc(pt))) {
  5245. proc_index++;
  5246. continue;
  5247. }
  5248. isize param_count = 0;
  5249. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5250. if (param_count_excluding_defaults > max_arg_count) {
  5251. array_unordered_remove(&procs, proc_index);
  5252. } else {
  5253. proc_index++;
  5254. }
  5255. }
  5256. }
  5257. if (procs.count == 1) {
  5258. Ast *ident = operand->expr;
  5259. while (ident->kind == Ast_SelectorExpr) {
  5260. Ast *s = ident->SelectorExpr.selector;
  5261. ident = s;
  5262. }
  5263. Entity *e = procs[0];
  5264. Entity **lhs = nullptr;
  5265. isize lhs_count = -1;
  5266. bool is_variadic = false;
  5267. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5268. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, is_variadic);
  5269. CallArgumentData data = {};
  5270. CallArgumentError err = call_checker(c, call, e->type, e, operands, CallArgumentMode_ShowErrors, &data);
  5271. if (err != CallArgumentError_None) {
  5272. // handle error
  5273. }
  5274. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5275. add_entity_use(c, ident, entity_to_use);
  5276. if (entity_to_use != nullptr) {
  5277. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5278. }
  5279. return data;
  5280. }
  5281. Entity **lhs = nullptr;
  5282. isize lhs_count = -1;
  5283. {
  5284. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5285. // where the same positional parameter has the same type value (and ellipsis)
  5286. bool proc_arg_count_all_equal = true;
  5287. isize proc_arg_count = -1;
  5288. for (Entity *p : procs) {
  5289. Type *pt = base_type(p->type);
  5290. if (pt != nullptr && is_type_proc(pt)) {
  5291. if (proc_arg_count < 0) {
  5292. proc_arg_count = pt->Proc.param_count;
  5293. } else {
  5294. if (proc_arg_count != pt->Proc.param_count) {
  5295. proc_arg_count_all_equal = false;
  5296. break;
  5297. }
  5298. }
  5299. }
  5300. }
  5301. if (proc_arg_count >= 0 && proc_arg_count_all_equal) {
  5302. lhs_count = proc_arg_count;
  5303. if (lhs_count > 0) {
  5304. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5305. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5306. Entity *e = nullptr;
  5307. for (Entity *p : procs) {
  5308. Type *pt = base_type(p->type);
  5309. if (pt != nullptr && is_type_proc(pt)) {
  5310. if (e == nullptr) {
  5311. e = pt->Proc.params->Tuple.variables[param_index];
  5312. } else {
  5313. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5314. if (e == f) {
  5315. continue;
  5316. }
  5317. if (are_types_identical(e->type, f->type)) {
  5318. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5319. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5320. if (ee == fe) {
  5321. continue;
  5322. }
  5323. }
  5324. // NOTE(bill): Entities are not close enough to be used
  5325. e = nullptr;
  5326. break;
  5327. }
  5328. }
  5329. }
  5330. lhs[param_index] = e;
  5331. }
  5332. }
  5333. }
  5334. }
  5335. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, false);
  5336. if (lhs != nullptr) {
  5337. gb_free(heap_allocator(), lhs);
  5338. }
  5339. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5340. defer (array_free(&valids));
  5341. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5342. defer (array_free(&proc_entities));
  5343. for (Entity *proc : procs) {
  5344. array_add(&proc_entities, proc);
  5345. }
  5346. gbString expr_name = expr_to_string(operand->expr);
  5347. defer (gb_string_free(expr_name));
  5348. for_array(i, procs) {
  5349. Entity *p = procs[i];
  5350. Type *pt = base_type(p->type);
  5351. if (pt != nullptr && is_type_proc(pt)) {
  5352. CallArgumentError err = CallArgumentError_None;
  5353. CallArgumentData data = {};
  5354. CheckerContext ctx = *c;
  5355. ctx.no_polymorphic_errors = true;
  5356. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5357. ctx.hide_polymorphic_errors = true;
  5358. err = call_checker(&ctx, call, pt, p, operands, CallArgumentMode_NoErrors, &data);
  5359. if (err != CallArgumentError_None) {
  5360. continue;
  5361. }
  5362. isize index = i;
  5363. if (data.gen_entity != nullptr) {
  5364. Entity *e = data.gen_entity;
  5365. DeclInfo *decl = data.gen_entity->decl_info;
  5366. ctx.scope = decl->scope;
  5367. ctx.decl = decl;
  5368. ctx.proc_name = e->token.string;
  5369. ctx.curr_proc_decl = decl;
  5370. ctx.curr_proc_sig = e->type;
  5371. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5372. if (!evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, false)) {
  5373. continue;
  5374. }
  5375. array_add(&proc_entities, data.gen_entity);
  5376. index = proc_entities.count-1;
  5377. }
  5378. ValidIndexAndScore item = {};
  5379. item.index = index;
  5380. item.score = data.score;
  5381. array_add(&valids, item);
  5382. }
  5383. }
  5384. if (valids.count > 1) {
  5385. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  5386. i64 best_score = valids[0].score;
  5387. Entity *best_entity = proc_entities[valids[0].index];
  5388. GB_ASSERT(best_entity != nullptr);
  5389. for (isize i = 1; i < valids.count; i++) {
  5390. if (best_score > valids[i].score) {
  5391. valids.count = i;
  5392. break;
  5393. }
  5394. if (best_entity == proc_entities[valids[i].index]) {
  5395. valids.count = i;
  5396. break;
  5397. }
  5398. }
  5399. }
  5400. if (valids.count == 0) {
  5401. begin_error_block();
  5402. defer (end_error_block());
  5403. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5404. if (operands.count == 0) {
  5405. error_line("\tNo given arguments\n");
  5406. } else {
  5407. error_line("\tGiven argument types: (");
  5408. for_array(i, operands) {
  5409. Operand o = operands[i];
  5410. if (i > 0) error_line(", ");
  5411. gbString type = type_to_string(o.type);
  5412. defer (gb_string_free(type));
  5413. error_line("%s", type);
  5414. }
  5415. error_line(")\n");
  5416. }
  5417. if (procs.count > 0) {
  5418. error_line("Did you mean to use one of the following:\n");
  5419. }
  5420. for (Entity *proc : procs) {
  5421. TokenPos pos = proc->token.pos;
  5422. Type *t = base_type(proc->type);
  5423. if (t == t_invalid) continue;
  5424. GB_ASSERT(t->kind == Type_Proc);
  5425. gbString pt;
  5426. defer (gb_string_free(pt));
  5427. if (t->Proc.node != nullptr) {
  5428. pt = expr_to_string(t->Proc.node);
  5429. } else {
  5430. pt = type_to_string(t);
  5431. }
  5432. String prefix = {};
  5433. String prefix_sep = {};
  5434. if (proc->pkg) {
  5435. prefix = proc->pkg->name;
  5436. prefix_sep = str_lit(".");
  5437. }
  5438. String name = proc->token.string;
  5439. char const *sep = "::";
  5440. if (proc->kind == Entity_Variable) {
  5441. sep = ":=";
  5442. }
  5443. error_line("\t%.*s%.*s%.*s %s %s at %s\n", LIT(prefix), LIT(prefix_sep), LIT(name), sep, pt, token_pos_to_string(pos));
  5444. }
  5445. if (procs.count > 0) {
  5446. error_line("\n");
  5447. }
  5448. result_type = t_invalid;
  5449. } else if (valids.count > 1) {
  5450. begin_error_block();
  5451. defer (end_error_block());
  5452. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5453. error_line("\tGiven argument types: (");
  5454. for_array(i, operands) {
  5455. Operand o = operands[i];
  5456. if (i > 0) error_line(", ");
  5457. gbString type = type_to_string(o.type);
  5458. defer (gb_string_free(type));
  5459. error_line("%s", type);
  5460. }
  5461. error_line(")\n");
  5462. for (isize i = 0; i < valids.count; i++) {
  5463. Entity *proc = proc_entities[valids[i].index];
  5464. GB_ASSERT(proc != nullptr);
  5465. TokenPos pos = proc->token.pos;
  5466. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5467. gbString pt = nullptr;
  5468. defer (gb_string_free(pt));
  5469. if (t->Proc.node != nullptr) {
  5470. pt = expr_to_string(t->Proc.node);
  5471. } else {
  5472. pt = type_to_string(t);
  5473. }
  5474. String name = proc->token.string;
  5475. char const *sep = "::";
  5476. if (proc->kind == Entity_Variable) {
  5477. sep = ":=";
  5478. }
  5479. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5480. if (proc->decl_info->proc_lit != nullptr) {
  5481. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5482. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5483. if (pl->where_token.kind != Token_Invalid) {
  5484. error_line("\n\t\twhere ");
  5485. for_array(j, pl->where_clauses) {
  5486. Ast *clause = pl->where_clauses[j];
  5487. if (j != 0) {
  5488. error_line("\t\t ");
  5489. }
  5490. gbString str = expr_to_string(clause);
  5491. error_line("%s", str);
  5492. gb_string_free(str);
  5493. if (j != pl->where_clauses.count-1) {
  5494. error_line(",");
  5495. }
  5496. }
  5497. error_line("\n\t");
  5498. }
  5499. }
  5500. error_line("at %s\n", token_pos_to_string(pos));
  5501. }
  5502. result_type = t_invalid;
  5503. } else {
  5504. GB_ASSERT(valids.count == 1);
  5505. Ast *ident = operand->expr;
  5506. while (ident->kind == Ast_SelectorExpr) {
  5507. Ast *s = ident->SelectorExpr.selector;
  5508. ident = s;
  5509. }
  5510. Entity *e = proc_entities[valids[0].index];
  5511. GB_ASSERT(e != nullptr);
  5512. proc_type = e->type;
  5513. CallArgumentData data = {};
  5514. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  5515. gb_unused(err);
  5516. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5517. add_entity_use(c, ident, entity_to_use);
  5518. if (entity_to_use != nullptr) {
  5519. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5520. }
  5521. if (data.gen_entity != nullptr) {
  5522. Entity *e = data.gen_entity;
  5523. DeclInfo *decl = data.gen_entity->decl_info;
  5524. CheckerContext ctx = *c;
  5525. ctx.scope = decl->scope;
  5526. ctx.decl = decl;
  5527. ctx.proc_name = e->token.string;
  5528. ctx.curr_proc_decl = decl;
  5529. ctx.curr_proc_sig = e->type;
  5530. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5531. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5532. decl->where_clauses_evaluated = true;
  5533. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5534. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5535. }
  5536. }
  5537. return data;
  5538. }
  5539. } else {
  5540. Ast *ident = operand->expr;
  5541. while (ident->kind == Ast_SelectorExpr) {
  5542. Ast *s = ident->SelectorExpr.selector;
  5543. ident = s;
  5544. }
  5545. Entity *e = entity_of_node(ident);
  5546. CallArgumentData data = {};
  5547. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  5548. gb_unused(err);
  5549. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5550. add_entity_use(c, ident, entity_to_use);
  5551. if (entity_to_use != nullptr) {
  5552. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5553. }
  5554. if (data.gen_entity != nullptr) {
  5555. Entity *e = data.gen_entity;
  5556. DeclInfo *decl = data.gen_entity->decl_info;
  5557. CheckerContext ctx = *c;
  5558. ctx.scope = decl->scope;
  5559. ctx.decl = decl;
  5560. ctx.proc_name = e->token.string;
  5561. ctx.curr_proc_decl = decl;
  5562. ctx.curr_proc_sig = e->type;
  5563. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5564. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5565. decl->where_clauses_evaluated = true;
  5566. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5567. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5568. }
  5569. }
  5570. return data;
  5571. }
  5572. CallArgumentData data = {};
  5573. data.result_type = t_invalid;
  5574. return data;
  5575. }
  5576. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5577. if (!is_type_polymorphic_record(t)) {
  5578. return -1;
  5579. }
  5580. TypeTuple *params = get_record_polymorphic_params(t);
  5581. if (params == nullptr) {
  5582. return -1;
  5583. }
  5584. for_array(i, params->variables) {
  5585. Entity *e = params->variables[i];
  5586. String name = e->token.string;
  5587. if (is_blank_ident(name)) {
  5588. continue;
  5589. }
  5590. if (name == parameter_name) {
  5591. return i;
  5592. }
  5593. }
  5594. return -1;
  5595. }
  5596. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5597. ast_node(ce, CallExpr, call);
  5598. Type *original_type = operand->type;
  5599. GB_ASSERT(is_type_polymorphic_record(original_type));
  5600. bool show_error = true;
  5601. Array<Operand> operands = {};
  5602. defer (array_free(&operands));
  5603. bool named_fields = false;
  5604. {
  5605. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5606. auto prev_type_path = c->type_path;
  5607. c->type_path = new_checker_type_path();
  5608. defer ({
  5609. destroy_checker_type_path(c->type_path);
  5610. c->type_path = prev_type_path;
  5611. });
  5612. if (is_call_expr_field_value(ce)) {
  5613. named_fields = true;
  5614. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5615. for_array(i, ce->args) {
  5616. Ast *arg = ce->args[i];
  5617. ast_node(fv, FieldValue, arg);
  5618. if (fv->field->kind == Ast_Ident) {
  5619. String name = fv->field->Ident.token.string;
  5620. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5621. if (index >= 0) {
  5622. TypeTuple *params = get_record_polymorphic_params(original_type);
  5623. Entity *e = params->variables[i];
  5624. if (e->kind == Entity_Constant) {
  5625. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5626. continue;
  5627. }
  5628. }
  5629. }
  5630. check_expr_or_type(c, &operands[i], fv->value);
  5631. }
  5632. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5633. if (vari_expand) {
  5634. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5635. }
  5636. } else {
  5637. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5638. Entity **lhs = nullptr;
  5639. isize lhs_count = -1;
  5640. TypeTuple *params = get_record_polymorphic_params(original_type);
  5641. if (params != nullptr) {
  5642. lhs = params->variables.data;
  5643. lhs_count = params->variables.count;
  5644. }
  5645. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, false, false);
  5646. }
  5647. }
  5648. CallArgumentError err = CallArgumentError_None;
  5649. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5650. isize param_count = tuple->variables.count;
  5651. isize minimum_param_count = param_count;
  5652. for (; minimum_param_count > 0; minimum_param_count--) {
  5653. Entity *e = tuple->variables[minimum_param_count-1];
  5654. if (e->kind != Entity_Constant) {
  5655. break;
  5656. }
  5657. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5658. break;
  5659. }
  5660. }
  5661. Array<Operand> ordered_operands = operands;
  5662. if (!named_fields) {
  5663. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5664. array_copy(&ordered_operands, operands, 0);
  5665. } else {
  5666. TEMPORARY_ALLOCATOR_GUARD();
  5667. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5668. // LEAK(bill)
  5669. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5670. for_array(i, ce->args) {
  5671. Ast *arg = ce->args[i];
  5672. ast_node(fv, FieldValue, arg);
  5673. if (fv->field->kind != Ast_Ident) {
  5674. if (show_error) {
  5675. gbString expr_str = expr_to_string(fv->field);
  5676. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5677. gb_string_free(expr_str);
  5678. }
  5679. err = CallArgumentError_InvalidFieldValue;
  5680. continue;
  5681. }
  5682. String name = fv->field->Ident.token.string;
  5683. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5684. if (index < 0) {
  5685. if (show_error) {
  5686. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5687. }
  5688. err = CallArgumentError_ParameterNotFound;
  5689. continue;
  5690. }
  5691. if (visited[index]) {
  5692. if (show_error) {
  5693. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5694. }
  5695. err = CallArgumentError_DuplicateParameter;
  5696. continue;
  5697. }
  5698. visited[index] = true;
  5699. ordered_operands[index] = operands[i];
  5700. }
  5701. for (isize i = 0; i < param_count; i++) {
  5702. if (!visited[i]) {
  5703. Entity *e = tuple->variables[i];
  5704. if (is_blank_ident(e->token)) {
  5705. continue;
  5706. }
  5707. if (show_error) {
  5708. if (e->kind == Entity_TypeName) {
  5709. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5710. LIT(e->token.string));
  5711. } else {
  5712. gbString str = type_to_string(e->type);
  5713. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5714. LIT(e->token.string), str);
  5715. gb_string_free(str);
  5716. }
  5717. }
  5718. err = CallArgumentError_ParameterMissing;
  5719. }
  5720. }
  5721. }
  5722. if (err != 0) {
  5723. operand->mode = Addressing_Invalid;
  5724. return err;
  5725. }
  5726. while (ordered_operands.count > 0) {
  5727. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5728. break;
  5729. }
  5730. array_pop(&ordered_operands);
  5731. }
  5732. if (minimum_param_count != param_count) {
  5733. if (param_count < ordered_operands.count) {
  5734. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  5735. err = CallArgumentError_TooManyArguments;
  5736. } else if (minimum_param_count > ordered_operands.count) {
  5737. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  5738. err = CallArgumentError_TooFewArguments;
  5739. }
  5740. } else {
  5741. if (param_count < ordered_operands.count) {
  5742. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5743. err = CallArgumentError_TooManyArguments;
  5744. } else if (param_count > ordered_operands.count) {
  5745. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5746. err = CallArgumentError_TooFewArguments;
  5747. }
  5748. }
  5749. if (err != 0) {
  5750. return err;
  5751. }
  5752. if (minimum_param_count != param_count) {
  5753. array_resize(&ordered_operands, param_count);
  5754. isize missing_count = 0;
  5755. // NOTE(bill): Replace missing operands with the default values (if possible)
  5756. for_array(i, ordered_operands) {
  5757. Operand *o = &ordered_operands[i];
  5758. if (o->expr == nullptr) {
  5759. Entity *e = tuple->variables[i];
  5760. if (e->kind == Entity_Constant) {
  5761. missing_count += 1;
  5762. o->mode = Addressing_Constant;
  5763. o->type = default_type(e->type);
  5764. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  5765. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  5766. o->value = e->Constant.param_value.value;
  5767. }
  5768. } else if (e->kind == Entity_TypeName) {
  5769. missing_count += 1;
  5770. o->mode = Addressing_Type;
  5771. o->type = e->type;
  5772. o->expr = e->identifier;
  5773. }
  5774. }
  5775. }
  5776. }
  5777. isize oo_count = gb_min(param_count, ordered_operands.count);
  5778. i64 score = 0;
  5779. for (isize i = 0; i < oo_count; i++) {
  5780. Entity *e = tuple->variables[i];
  5781. Operand *o = &ordered_operands[i];
  5782. if (o->mode == Addressing_Invalid) {
  5783. continue;
  5784. }
  5785. if (e->kind == Entity_TypeName) {
  5786. if (o->mode != Addressing_Type) {
  5787. if (show_error) {
  5788. gbString expr = expr_to_string(o->expr);
  5789. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  5790. gb_string_free(expr);
  5791. }
  5792. err = CallArgumentError_WrongTypes;
  5793. }
  5794. if (are_types_identical(e->type, o->type)) {
  5795. score += assign_score_function(1);
  5796. } else {
  5797. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5798. }
  5799. } else {
  5800. i64 s = 0;
  5801. if (o->type->kind == Type_Generic) {
  5802. // Polymorphic name!
  5803. score += assign_score_function(1);
  5804. continue;
  5805. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  5806. if (show_error) {
  5807. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  5808. }
  5809. err = CallArgumentError_WrongTypes;
  5810. }
  5811. o->type = e->type;
  5812. if (o->mode != Addressing_Constant) {
  5813. bool valid = false;
  5814. if (is_type_proc(o->type)) {
  5815. Entity *proc_entity = entity_from_expr(o->expr);
  5816. valid = proc_entity != nullptr;
  5817. }
  5818. if (!valid) {
  5819. if (show_error) {
  5820. error(o->expr, "Expected a constant value for this polymorphic type argument");
  5821. }
  5822. err = CallArgumentError_NoneConstantParameter;
  5823. }
  5824. }
  5825. score += s;
  5826. }
  5827. // NOTE(bill): Add type info the parameters
  5828. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  5829. // add_type_info_type(c, o->type);
  5830. }
  5831. if (show_error && err) {
  5832. return err;
  5833. }
  5834. {
  5835. bool failure = false;
  5836. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  5837. if (found_entity) {
  5838. operand->mode = Addressing_Type;
  5839. operand->type = found_entity->type;
  5840. return err;
  5841. }
  5842. String generated_name = make_string_c(expr_to_string(call));
  5843. CheckerContext ctx = *c;
  5844. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  5845. ctx.scope = polymorphic_record_parent_scope(original_type);
  5846. GB_ASSERT(ctx.scope != nullptr);
  5847. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  5848. Type *bt = base_type(original_type);
  5849. if (bt->kind == Type_Struct) {
  5850. Ast *node = clone_ast(bt->Struct.node);
  5851. Type *struct_type = alloc_type_struct();
  5852. struct_type->Struct.node = node;
  5853. struct_type->Struct.polymorphic_parent = original_type;
  5854. set_base_type(named_type, struct_type);
  5855. check_open_scope(&ctx, node);
  5856. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  5857. check_close_scope(&ctx);
  5858. } else if (bt->kind == Type_Union) {
  5859. Ast *node = clone_ast(bt->Union.node);
  5860. Type *union_type = alloc_type_union();
  5861. union_type->Union.node = node;
  5862. union_type->Union.polymorphic_parent = original_type;
  5863. set_base_type(named_type, union_type);
  5864. check_open_scope(&ctx, node);
  5865. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  5866. check_close_scope(&ctx);
  5867. } else {
  5868. GB_PANIC("Unsupported parametric polymorphic record type");
  5869. }
  5870. operand->mode = Addressing_Type;
  5871. operand->type = named_type;
  5872. }
  5873. return err;
  5874. }
  5875. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  5876. if (proc != nullptr &&
  5877. proc->kind == Ast_BasicDirective) {
  5878. ast_node(bd, BasicDirective, proc);
  5879. String name = bd->name.string;
  5880. if (
  5881. name == "location" ||
  5882. name == "assert" ||
  5883. name == "panic" ||
  5884. name == "defined" ||
  5885. name == "config" ||
  5886. name == "load" ||
  5887. name == "load_hash" ||
  5888. name == "load_or"
  5889. ) {
  5890. operand->mode = Addressing_Builtin;
  5891. operand->builtin_id = BuiltinProc_DIRECTIVE;
  5892. operand->expr = proc;
  5893. operand->type = t_invalid;
  5894. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  5895. } else {
  5896. error(proc, "Unknown directive: #%.*s", LIT(name));
  5897. operand->expr = proc;
  5898. operand->type = t_invalid;
  5899. operand->mode = Addressing_Invalid;
  5900. return Expr_Expr;
  5901. }
  5902. if (inlining != ProcInlining_none) {
  5903. error(call, "Inlining operators are not allowed on built-in procedures");
  5904. }
  5905. } else {
  5906. if (proc != nullptr) {
  5907. check_expr_or_type(c, operand, proc);
  5908. } else {
  5909. GB_ASSERT(operand->expr != nullptr);
  5910. }
  5911. }
  5912. if (args.count > 0) {
  5913. bool fail = false;
  5914. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  5915. for (Ast *arg : args) {
  5916. bool mix = false;
  5917. if (first_is_field_value) {
  5918. mix = arg->kind != Ast_FieldValue;
  5919. } else {
  5920. mix = arg->kind == Ast_FieldValue;
  5921. }
  5922. if (mix) {
  5923. error(arg, "Mixture of 'field = value' and value elements in a procedure call is not allowed");
  5924. fail = true;
  5925. }
  5926. }
  5927. if (fail) {
  5928. operand->mode = Addressing_Invalid;
  5929. operand->expr = call;
  5930. return Expr_Stmt;
  5931. }
  5932. }
  5933. if (operand->mode == Addressing_Invalid) {
  5934. for (Ast *arg : args) {
  5935. if (arg->kind == Ast_FieldValue) {
  5936. arg = arg->FieldValue.value;
  5937. }
  5938. check_expr_base(c, operand, arg, nullptr);
  5939. }
  5940. operand->mode = Addressing_Invalid;
  5941. operand->expr = call;
  5942. return Expr_Stmt;
  5943. }
  5944. if (operand->mode == Addressing_Type) {
  5945. Type *t = operand->type;
  5946. if (is_type_polymorphic_record(t)) {
  5947. if (!is_type_named(t)) {
  5948. gbString s = expr_to_string(operand->expr);
  5949. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  5950. gb_string_free(s);
  5951. operand->mode = Addressing_Invalid;
  5952. operand->type = t_invalid;;
  5953. return Expr_Expr;
  5954. }
  5955. auto err = check_polymorphic_record_type(c, operand, call);
  5956. if (err == 0) {
  5957. Ast *ident = operand->expr;
  5958. while (ident->kind == Ast_SelectorExpr) {
  5959. Ast *s = ident->SelectorExpr.selector;
  5960. ident = s;
  5961. }
  5962. Type *ot = operand->type;
  5963. GB_ASSERT(ot->kind == Type_Named);
  5964. Entity *e = ot->Named.type_name;
  5965. add_entity_use(c, ident, e);
  5966. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  5967. } else {
  5968. operand->mode = Addressing_Invalid;
  5969. operand->type = t_invalid;
  5970. }
  5971. } else {
  5972. gbString str = type_to_string(t);
  5973. defer (gb_string_free(str));
  5974. operand->mode = Addressing_Invalid;
  5975. isize arg_count = args.count;
  5976. switch (arg_count) {
  5977. case 0: error(call, "Missing argument in conversion to '%s'", str); break;
  5978. default: error(call, "Too many arguments in conversion to '%s'", str); break;
  5979. case 1: {
  5980. Ast *arg = args[0];
  5981. if (arg->kind == Ast_FieldValue) {
  5982. error(call, "'field = value' cannot be used in a type conversion");
  5983. arg = arg->FieldValue.value;
  5984. // NOTE(bill): Carry on the cast regardless
  5985. }
  5986. check_expr_with_type_hint(c, operand, arg, t);
  5987. if (operand->mode != Addressing_Invalid) {
  5988. if (is_type_polymorphic(t)) {
  5989. error(call, "A polymorphic type cannot be used in a type conversion");
  5990. } else {
  5991. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  5992. // as it assumes it is determining the type
  5993. check_cast(c, operand, t);
  5994. }
  5995. }
  5996. operand->type = t;
  5997. operand->expr = call;
  5998. if (operand->mode != Addressing_Invalid) {
  5999. update_untyped_expr_type(c, arg, t, false);
  6000. }
  6001. break;
  6002. }
  6003. }
  6004. }
  6005. return Expr_Expr;
  6006. }
  6007. if (operand->mode == Addressing_Builtin) {
  6008. i32 id = operand->builtin_id;
  6009. Entity *e = entity_of_node(operand->expr);
  6010. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6011. warning(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6012. }
  6013. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6014. operand->mode = Addressing_Invalid;
  6015. operand->type = t_invalid;
  6016. }
  6017. operand->expr = call;
  6018. return builtin_procs[id].kind;
  6019. }
  6020. Entity *initial_entity = entity_of_node(operand->expr);
  6021. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6022. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6023. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6024. if (c->decl) {
  6025. c->decl->defer_used += 1;
  6026. }
  6027. }
  6028. }
  6029. Type *proc_type = base_type(operand->type);
  6030. if (operand->mode != Addressing_ProcGroup) {
  6031. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6032. bool valid_mode = is_operand_value(*operand);
  6033. if (!valid_type || !valid_mode) {
  6034. Ast *e = operand->expr;
  6035. gbString str = expr_to_string(e);
  6036. gbString type_str = type_to_string(operand->type);
  6037. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6038. gb_string_free(type_str);
  6039. gb_string_free(str);
  6040. operand->mode = Addressing_Invalid;
  6041. operand->expr = call;
  6042. return Expr_Stmt;
  6043. }
  6044. }
  6045. CallArgumentData data = check_call_arguments(c, operand, proc_type, call, args);
  6046. Type *result_type = data.result_type;
  6047. gb_zero_item(operand);
  6048. operand->expr = call;
  6049. if (result_type == t_invalid) {
  6050. operand->mode = Addressing_Invalid;
  6051. operand->type = t_invalid;
  6052. return Expr_Stmt;
  6053. }
  6054. Type *pt = base_type(proc_type);
  6055. if (pt == t_invalid) {
  6056. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6057. pt = type_of_expr(operand->expr->CallExpr.proc);
  6058. }
  6059. if (pt == t_invalid && data.gen_entity) {
  6060. pt = data.gen_entity->type;
  6061. }
  6062. }
  6063. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6064. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6065. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6066. }
  6067. }
  6068. if (result_type == nullptr) {
  6069. operand->mode = Addressing_NoValue;
  6070. } else {
  6071. GB_ASSERT(is_type_tuple(result_type));
  6072. isize count = result_type->Tuple.variables.count;
  6073. switch (count) {
  6074. case 0:
  6075. operand->mode = Addressing_NoValue;
  6076. break;
  6077. case 1:
  6078. operand->mode = Addressing_Value;
  6079. operand->type = result_type->Tuple.variables[0]->type;
  6080. break;
  6081. default:
  6082. operand->mode = Addressing_Value;
  6083. operand->type = result_type;
  6084. break;
  6085. }
  6086. }
  6087. switch (inlining) {
  6088. case ProcInlining_inline:
  6089. if (proc != nullptr) {
  6090. Entity *e = entity_from_expr(proc);
  6091. if (e != nullptr && e->kind == Entity_Procedure) {
  6092. DeclInfo *decl = e->decl_info;
  6093. if (decl->proc_lit) {
  6094. ast_node(pl, ProcLit, decl->proc_lit);
  6095. if (pl->inlining == ProcInlining_no_inline) {
  6096. error(call, "'inline' cannot be applied to a procedure that has be marked as 'no_inline'");
  6097. }
  6098. }
  6099. }
  6100. }
  6101. break;
  6102. case ProcInlining_no_inline:
  6103. break;
  6104. }
  6105. operand->expr = call;
  6106. {
  6107. if (proc_type == t_invalid) {
  6108. // gb_printf_err("%s\n", expr_to_string(operand->expr));
  6109. }
  6110. Type *type = nullptr;
  6111. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6112. type = type_of_expr(operand->expr->CallExpr.proc);
  6113. }
  6114. if (type == nullptr) {
  6115. type = pt;
  6116. }
  6117. type = base_type(type);
  6118. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6119. operand->mode = Addressing_OptionalOk;
  6120. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6121. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6122. operand->expr->CallExpr.optional_ok_one = true;
  6123. }
  6124. }
  6125. }
  6126. // add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  6127. return Expr_Expr;
  6128. }
  6129. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6130. check_expr_base(c, o, e, t);
  6131. check_not_tuple(c, o);
  6132. char const *err_str = nullptr;
  6133. switch (o->mode) {
  6134. case Addressing_NoValue:
  6135. err_str = "used as a value";
  6136. break;
  6137. case Addressing_Type:
  6138. if (t == nullptr || !is_type_typeid(t)) {
  6139. err_str = "is not an expression but a type, in this context it is ambiguous";
  6140. }
  6141. break;
  6142. case Addressing_Builtin:
  6143. err_str = "must be called";
  6144. break;
  6145. }
  6146. if (err_str != nullptr) {
  6147. gbString str = expr_to_string(e);
  6148. error(e, "'%s' %s", str, err_str);
  6149. gb_string_free(str);
  6150. o->mode = Addressing_Invalid;
  6151. }
  6152. }
  6153. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6154. switch (t->kind) {
  6155. case Type_Basic:
  6156. if (t->Basic.kind == Basic_string) {
  6157. if (o->mode == Addressing_Constant) {
  6158. *max_count = o->value.value_string.len;
  6159. }
  6160. if (o->mode != Addressing_Constant) {
  6161. o->mode = Addressing_Value;
  6162. }
  6163. o->type = t_u8;
  6164. return true;
  6165. } else if (t->Basic.kind == Basic_UntypedString) {
  6166. if (o->mode == Addressing_Constant) {
  6167. *max_count = o->value.value_string.len;
  6168. o->type = t_u8;
  6169. return true;
  6170. }
  6171. return false;
  6172. }
  6173. break;
  6174. case Type_MultiPointer:
  6175. o->type = t->MultiPointer.elem;
  6176. if (o->mode != Addressing_Constant) {
  6177. o->mode = Addressing_Variable;
  6178. }
  6179. return true;
  6180. case Type_Array:
  6181. *max_count = t->Array.count;
  6182. if (indirection) {
  6183. o->mode = Addressing_Variable;
  6184. } else if (o->mode != Addressing_Variable &&
  6185. o->mode != Addressing_Constant) {
  6186. o->mode = Addressing_Value;
  6187. }
  6188. o->type = t->Array.elem;
  6189. return true;
  6190. case Type_EnumeratedArray:
  6191. *max_count = t->EnumeratedArray.count;
  6192. if (indirection) {
  6193. o->mode = Addressing_Variable;
  6194. } else if (o->mode != Addressing_Variable &&
  6195. o->mode != Addressing_Constant) {
  6196. o->mode = Addressing_Value;
  6197. }
  6198. o->type = t->EnumeratedArray.elem;
  6199. return true;
  6200. case Type_Matrix:
  6201. *max_count = t->Matrix.column_count;
  6202. if (indirection) {
  6203. o->mode = Addressing_Variable;
  6204. } else if (o->mode != Addressing_Variable) {
  6205. o->mode = Addressing_Value;
  6206. }
  6207. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6208. return true;
  6209. case Type_Slice:
  6210. o->type = t->Slice.elem;
  6211. if (o->mode != Addressing_Constant) {
  6212. o->mode = Addressing_Variable;
  6213. }
  6214. return true;
  6215. case Type_RelativeSlice:
  6216. {
  6217. Type *slice_type = base_type(t->RelativeSlice.slice_type);
  6218. GB_ASSERT(slice_type->kind == Type_Slice);
  6219. o->type = slice_type->Slice.elem;
  6220. if (o->mode != Addressing_Constant) {
  6221. o->mode = Addressing_Variable;
  6222. }
  6223. }
  6224. return true;
  6225. case Type_DynamicArray:
  6226. o->type = t->DynamicArray.elem;
  6227. if (o->mode != Addressing_Constant) {
  6228. o->mode = Addressing_Variable;
  6229. }
  6230. return true;
  6231. case Type_Struct:
  6232. if (t->Struct.soa_kind != StructSoa_None) {
  6233. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6234. *max_count = t->Struct.soa_count;
  6235. }
  6236. o->type = t->Struct.soa_elem;
  6237. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  6238. o->mode = Addressing_SoaVariable;
  6239. } else {
  6240. o->mode = Addressing_Value;
  6241. }
  6242. return true;
  6243. }
  6244. return false;
  6245. }
  6246. if (is_type_pointer(original_type) && indirection) {
  6247. Type *ptr = base_type(original_type);
  6248. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6249. o->type = ptr->Pointer.elem;
  6250. o->mode = Addressing_Value;
  6251. return true;
  6252. }
  6253. }
  6254. return false;
  6255. }
  6256. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6257. if (is_type_untyped_undef(x) && type_has_undef(y)) {
  6258. return true;
  6259. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6260. return true;
  6261. } else if (is_type_untyped_undef(y) && type_has_undef(x)) {
  6262. return true;
  6263. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6264. return true;
  6265. }
  6266. return are_types_identical(x, y);
  6267. }
  6268. 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) {
  6269. if (!is_ast_range(node)) {
  6270. return false;
  6271. }
  6272. ast_node(ie, BinaryExpr, node);
  6273. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6274. if (x->mode == Addressing_Invalid) {
  6275. return false;
  6276. }
  6277. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6278. if (y->mode == Addressing_Invalid) {
  6279. return false;
  6280. }
  6281. convert_to_typed(c, x, y->type);
  6282. if (x->mode == Addressing_Invalid) {
  6283. return false;
  6284. }
  6285. convert_to_typed(c, y, x->type);
  6286. if (y->mode == Addressing_Invalid) {
  6287. return false;
  6288. }
  6289. convert_to_typed(c, x, default_type(y->type));
  6290. if (x->mode == Addressing_Invalid) {
  6291. return false;
  6292. }
  6293. convert_to_typed(c, y, default_type(x->type));
  6294. if (y->mode == Addressing_Invalid) {
  6295. return false;
  6296. }
  6297. if (!are_types_identical(x->type, y->type)) {
  6298. if (x->type != t_invalid &&
  6299. y->type != t_invalid) {
  6300. gbString xt = type_to_string(x->type);
  6301. gbString yt = type_to_string(y->type);
  6302. gbString expr_str = expr_to_string(x->expr);
  6303. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6304. gb_string_free(expr_str);
  6305. gb_string_free(yt);
  6306. gb_string_free(xt);
  6307. }
  6308. return false;
  6309. }
  6310. Type *type = x->type;
  6311. if (is_for_loop) {
  6312. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6313. error(ie->op, "Only numerical types are allowed within interval expressions");
  6314. return false;
  6315. }
  6316. } else {
  6317. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6318. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6319. return false;
  6320. }
  6321. }
  6322. if (x->mode == Addressing_Constant &&
  6323. y->mode == Addressing_Constant) {
  6324. ExactValue a = x->value;
  6325. ExactValue b = y->value;
  6326. GB_ASSERT(are_types_identical(x->type, y->type));
  6327. TokenKind op = Token_Lt;
  6328. switch (ie->op.kind) {
  6329. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6330. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6331. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6332. default: error(ie->op, "Invalid range operator"); break;
  6333. }
  6334. bool ok = compare_exact_values(op, a, b);
  6335. if (!ok) {
  6336. // TODO(bill): Better error message
  6337. error(ie->op, "Invalid interval range");
  6338. return false;
  6339. }
  6340. ExactValue inline_for_depth = exact_value_sub(b, a);
  6341. if (ie->op.kind != Token_RangeHalf) {
  6342. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6343. }
  6344. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6345. } else if (inline_for_depth_ != nullptr) {
  6346. error(ie->op, "Interval expressions must be constant");
  6347. return false;
  6348. }
  6349. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6350. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6351. return true;
  6352. }
  6353. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6354. if (is_operand_nil(*o)) {
  6355. return true;
  6356. }
  6357. Ast *expr = unparen_expr(o->expr);
  6358. if (expr != nullptr) {
  6359. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6360. if (e != nullptr && e->kind == Entity_Procedure) {
  6361. return true;
  6362. }
  6363. if (expr->kind == Ast_ProcLit) {
  6364. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6365. return true;
  6366. }
  6367. }
  6368. return o->mode == Addressing_Constant;
  6369. }
  6370. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6371. if (is_type_enum(th)) {
  6372. Type *enum_type = base_type(th);
  6373. GB_ASSERT(enum_type->kind == Type_Enum);
  6374. String name = ise->selector->Ident.token.string;
  6375. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6376. if (e == nullptr) {
  6377. return false;
  6378. }
  6379. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6380. GB_ASSERT(e->kind == Entity_Constant);
  6381. o->value = e->Constant.value;
  6382. o->mode = Addressing_Constant;
  6383. o->type = e->type;
  6384. return true;
  6385. }
  6386. if (is_type_union(th)) {
  6387. TEMPORARY_ALLOCATOR_GUARD();
  6388. Type *union_type = base_type(th);
  6389. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6390. for (Type *vt : union_type->Union.variants) {
  6391. Operand x = {};
  6392. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6393. array_add(&operands, x);
  6394. }
  6395. }
  6396. if (operands.count == 1) {
  6397. *o = operands[0];
  6398. return true;
  6399. }
  6400. }
  6401. return false;
  6402. }
  6403. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6404. ast_node(ise, ImplicitSelectorExpr, node);
  6405. o->type = t_invalid;
  6406. o->expr = node;
  6407. o->mode = Addressing_Invalid;
  6408. Type *th = type_hint;
  6409. if (th == nullptr) {
  6410. gbString str = expr_to_string(node);
  6411. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6412. gb_string_free(str);
  6413. return Expr_Expr;
  6414. }
  6415. o->type = th;
  6416. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6417. if (!ok) {
  6418. String name = ise->selector->Ident.token.string;
  6419. if (is_type_enum(th)) {
  6420. Type *bt = base_type(th);
  6421. GB_ASSERT(bt->kind == Type_Enum);
  6422. gbString typ = type_to_string(th);
  6423. defer (gb_string_free(typ));
  6424. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6425. check_did_you_mean_type(name, bt->Enum.fields);
  6426. } else {
  6427. gbString typ = type_to_string(th);
  6428. gbString str = expr_to_string(node);
  6429. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6430. gb_string_free(str);
  6431. gb_string_free(typ);
  6432. }
  6433. }
  6434. o->expr = node;
  6435. return Expr_Expr;
  6436. }
  6437. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  6438. switch (x->mode) {
  6439. case Addressing_MapIndex:
  6440. case Addressing_OptionalOk:
  6441. case Addressing_OptionalOkPtr:
  6442. if (val_type_) *val_type_ = x->type;
  6443. break;
  6444. default:
  6445. if (ok_type_) *ok_type_ = x->type;
  6446. return;
  6447. }
  6448. Ast *expr = unparen_expr(x->expr);
  6449. if (expr->kind == Ast_CallExpr) {
  6450. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6451. if (is_type_proc(pt)) {
  6452. Type *tuple = pt->Proc.results;
  6453. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6454. if (pt->Proc.result_count >= 2) {
  6455. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6456. }
  6457. expr->CallExpr.optional_ok_one = false;
  6458. x->type = tuple;
  6459. return;
  6460. }
  6461. }
  6462. Type *tuple = make_optional_ok_type(x->type);
  6463. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6464. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6465. x->type = tuple;
  6466. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6467. }
  6468. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6469. ast_node(ie, MatrixIndexExpr, node);
  6470. check_expr(c, o, ie->expr);
  6471. node->viral_state_flags |= ie->expr->viral_state_flags;
  6472. if (o->mode == Addressing_Invalid) {
  6473. o->expr = node;
  6474. return;
  6475. }
  6476. Type *t = base_type(type_deref(o->type));
  6477. bool is_ptr = is_type_pointer(o->type);
  6478. bool is_const = o->mode == Addressing_Constant;
  6479. if (t->kind != Type_Matrix) {
  6480. gbString str = expr_to_string(o->expr);
  6481. gbString type_str = type_to_string(o->type);
  6482. defer (gb_string_free(str));
  6483. defer (gb_string_free(type_str));
  6484. if (is_const) {
  6485. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6486. } else {
  6487. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6488. }
  6489. o->mode = Addressing_Invalid;
  6490. o->expr = node;
  6491. return;
  6492. }
  6493. o->type = t->Matrix.elem;
  6494. if (is_ptr) {
  6495. o->mode = Addressing_Variable;
  6496. } else if (o->mode != Addressing_Variable) {
  6497. o->mode = Addressing_Value;
  6498. }
  6499. if (ie->row_index == nullptr) {
  6500. gbString str = expr_to_string(o->expr);
  6501. error(o->expr, "Missing row index for '%s'", str);
  6502. gb_string_free(str);
  6503. o->mode = Addressing_Invalid;
  6504. o->expr = node;
  6505. return;
  6506. }
  6507. if (ie->column_index == nullptr) {
  6508. gbString str = expr_to_string(o->expr);
  6509. error(o->expr, "Missing column index for '%s'", str);
  6510. gb_string_free(str);
  6511. o->mode = Addressing_Invalid;
  6512. o->expr = node;
  6513. return;
  6514. }
  6515. i64 row_count = t->Matrix.row_count;
  6516. i64 column_count = t->Matrix.column_count;
  6517. i64 row_index = 0;
  6518. i64 column_index = 0;
  6519. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6520. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6521. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  6522. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  6523. }
  6524. gb_unused(row_ok);
  6525. gb_unused(column_ok);
  6526. }
  6527. struct TypeAndToken {
  6528. Type *type;
  6529. Token token;
  6530. };
  6531. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  6532. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  6533. if (operand.mode != Addressing_Constant) {
  6534. return;
  6535. }
  6536. if (operand.value.kind == ExactValue_Invalid) {
  6537. return;
  6538. }
  6539. uintptr key = hash_exact_value(operand.value);
  6540. TypeAndToken *found = map_get(seen, key);
  6541. if (found != nullptr) {
  6542. TEMPORARY_ALLOCATOR_GUARD();
  6543. isize count = multi_map_count(seen, key);
  6544. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  6545. multi_map_get_all(seen, key, taps);
  6546. for (isize i = 0; i < count; i++) {
  6547. TypeAndToken tap = taps[i];
  6548. if (!are_types_identical(operand.type, tap.type)) {
  6549. continue;
  6550. }
  6551. TokenPos pos = tap.token.pos;
  6552. if (use_expr) {
  6553. gbString expr_str = expr_to_string(operand.expr);
  6554. error(operand.expr,
  6555. "Duplicate case '%s'\n"
  6556. "\tprevious case at %s",
  6557. expr_str,
  6558. token_pos_to_string(pos));
  6559. gb_string_free(expr_str);
  6560. } else {
  6561. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  6562. }
  6563. return;
  6564. }
  6565. }
  6566. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  6567. multi_map_insert(seen, key, tap);
  6568. }
  6569. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  6570. if (is_type_enum(x.type)) {
  6571. // TODO(bill): Fix this logic so it's fast!!!
  6572. i64 v0 = exact_value_to_i64(lhs.value);
  6573. i64 v1 = exact_value_to_i64(rhs.value);
  6574. Operand v = {};
  6575. v.mode = Addressing_Constant;
  6576. v.type = x.type;
  6577. v.expr = x.expr;
  6578. Type *bt = base_type(x.type);
  6579. GB_ASSERT(bt->kind == Type_Enum);
  6580. for (i64 vi = v0; vi <= v1; vi++) {
  6581. if (upper_op != Token_LtEq && vi == v1) {
  6582. break;
  6583. }
  6584. bool found = false;
  6585. for (Entity *f : bt->Enum.fields) {
  6586. GB_ASSERT(f->kind == Entity_Constant);
  6587. i64 fv = exact_value_to_i64(f->Constant.value);
  6588. if (fv == vi) {
  6589. found = true;
  6590. break;
  6591. }
  6592. }
  6593. if (found) {
  6594. v.value = exact_value_i64(vi);
  6595. add_constant_switch_case(ctx, seen, v);
  6596. }
  6597. }
  6598. } else {
  6599. add_constant_switch_case(ctx, seen, lhs);
  6600. if (upper_op == Token_LtEq) {
  6601. add_constant_switch_case(ctx, seen, rhs);
  6602. }
  6603. }
  6604. }
  6605. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  6606. add_constant_switch_case(ctx, seen, x);
  6607. }
  6608. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6609. ast_node(bd, BasicDirective, node);
  6610. ExprKind kind = Expr_Expr;
  6611. o->mode = Addressing_Constant;
  6612. String name = bd->name.string;
  6613. if (name == "file") {
  6614. o->type = t_untyped_string;
  6615. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6616. } else if (name == "line") {
  6617. o->type = t_untyped_integer;
  6618. o->value = exact_value_i64(bd->token.pos.line);
  6619. } else if (name == "procedure") {
  6620. if (c->curr_proc_decl == nullptr) {
  6621. error(node, "#procedure may only be used within procedures");
  6622. o->type = t_untyped_string;
  6623. o->value = exact_value_string(str_lit(""));
  6624. } else {
  6625. o->type = t_untyped_string;
  6626. o->value = exact_value_string(c->proc_name);
  6627. }
  6628. } else if (name == "caller_location") {
  6629. init_core_source_code_location(c->checker);
  6630. error(node, "#caller_location may only be used as a default argument parameter");
  6631. o->type = t_source_code_location;
  6632. o->mode = Addressing_Value;
  6633. } else {
  6634. if (name == "location") {
  6635. init_core_source_code_location(c->checker);
  6636. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  6637. o->type = t_source_code_location;
  6638. o->mode = Addressing_Value;
  6639. } else if (
  6640. name == "assert" ||
  6641. name == "defined" ||
  6642. name == "config" ||
  6643. name == "load" ||
  6644. name == "load_hash" ||
  6645. name == "load_or"
  6646. ) {
  6647. error(node, "'#%.*s' must be used as a call", LIT(name));
  6648. o->type = t_invalid;
  6649. o->mode = Addressing_Invalid;
  6650. } else {
  6651. error(node, "Unknown directive: #%.*s", LIT(name));
  6652. o->type = t_invalid;
  6653. o->mode = Addressing_Invalid;
  6654. }
  6655. }
  6656. return kind;
  6657. }
  6658. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6659. ExprKind kind = Expr_Expr;
  6660. Operand cond = {Addressing_Invalid};
  6661. ast_node(te, TernaryIfExpr, node);
  6662. check_expr(c, &cond, te->cond);
  6663. node->viral_state_flags |= te->cond->viral_state_flags;
  6664. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6665. error(te->cond, "Non-boolean condition in ternary if expression");
  6666. }
  6667. Operand x = {Addressing_Invalid};
  6668. Operand y = {Addressing_Invalid};
  6669. check_expr_or_type(c, &x, te->x, type_hint);
  6670. node->viral_state_flags |= te->x->viral_state_flags;
  6671. if (te->y != nullptr) {
  6672. Type *th = type_hint;
  6673. if (type_hint == nullptr && is_type_typed(x.type)) {
  6674. th = x.type;
  6675. }
  6676. check_expr_or_type(c, &y, te->y, th);
  6677. node->viral_state_flags |= te->y->viral_state_flags;
  6678. } else {
  6679. error(node, "A ternary expression must have an else clause");
  6680. return kind;
  6681. }
  6682. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  6683. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  6684. gbString type_string = expr_to_string(type_expr);
  6685. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  6686. gb_string_free(type_string);
  6687. return kind;
  6688. }
  6689. if (x.type == nullptr || x.type == t_invalid ||
  6690. y.type == nullptr || y.type == t_invalid) {
  6691. return kind;
  6692. }
  6693. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  6694. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  6695. if (x.mode == Addressing_Invalid) {
  6696. return kind;
  6697. }
  6698. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  6699. if (y.mode == Addressing_Invalid) {
  6700. x.mode = Addressing_Invalid;
  6701. return kind;
  6702. }
  6703. // NOTE(bill, 2023-01-30): Allow for expression like this:
  6704. // x: union{f32} = f32(123) if cond else nil
  6705. if (type_hint && !is_type_any(type_hint) && !ternary_compare_types(x.type, y.type)) {
  6706. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  6707. check_cast(c, &x, type_hint);
  6708. check_cast(c, &y, type_hint);
  6709. }
  6710. }
  6711. if (!ternary_compare_types(x.type, y.type)) {
  6712. gbString its = type_to_string(x.type);
  6713. gbString ets = type_to_string(y.type);
  6714. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  6715. gb_string_free(ets);
  6716. gb_string_free(its);
  6717. return kind;
  6718. }
  6719. o->type = x.type;
  6720. if (is_type_untyped_nil(o->type) || is_type_untyped_undef(o->type)) {
  6721. o->type = y.type;
  6722. }
  6723. o->mode = Addressing_Value;
  6724. o->expr = node;
  6725. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  6726. if (check_cast_internal(c, &x, type_hint) &&
  6727. check_cast_internal(c, &y, type_hint)) {
  6728. convert_to_typed(c, o, type_hint);
  6729. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  6730. o->type = type_hint;
  6731. }
  6732. }
  6733. return kind;
  6734. }
  6735. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6736. ExprKind kind = Expr_Expr;
  6737. Operand cond = {};
  6738. ast_node(te, TernaryWhenExpr, node);
  6739. check_expr(c, &cond, te->cond);
  6740. node->viral_state_flags |= te->cond->viral_state_flags;
  6741. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  6742. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  6743. return kind;
  6744. }
  6745. if (cond.value.value_bool) {
  6746. check_expr_or_type(c, o, te->x, type_hint);
  6747. node->viral_state_flags |= te->x->viral_state_flags;
  6748. } else {
  6749. if (te->y != nullptr) {
  6750. check_expr_or_type(c, o, te->y, type_hint);
  6751. node->viral_state_flags |= te->y->viral_state_flags;
  6752. } else {
  6753. error(node, "A ternary when expression must have an else clause");
  6754. return kind;
  6755. }
  6756. }
  6757. return kind;
  6758. }
  6759. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6760. ast_node(oe, OrElseExpr, node);
  6761. String name = oe->token.string;
  6762. Ast *arg = oe->x;
  6763. Ast *default_value = oe->y;
  6764. Operand x = {};
  6765. Operand y = {};
  6766. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  6767. if (is_load_directive_call(arg)) {
  6768. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  6769. // Allow for chaining of '#load(path) or_else #load(path)'
  6770. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  6771. bool y_is_diverging = false;
  6772. check_expr_base(c, &y, default_value, x.type);
  6773. switch (y.mode) {
  6774. case Addressing_NoValue:
  6775. if (is_diverging_expr(y.expr)) {
  6776. // Allow
  6777. y.mode = Addressing_Value;
  6778. y_is_diverging = true;
  6779. } else {
  6780. error_operand_no_value(&y);
  6781. y.mode = Addressing_Invalid;
  6782. }
  6783. break;
  6784. case Addressing_Type:
  6785. error_operand_not_expression(&y);
  6786. y.mode = Addressing_Invalid;
  6787. break;
  6788. }
  6789. if (y.mode == Addressing_Invalid) {
  6790. o->mode = Addressing_Value;
  6791. o->type = t_invalid;
  6792. o->expr = node;
  6793. return Expr_Expr;
  6794. }
  6795. if (!y_is_diverging) {
  6796. check_assignment(c, &y, x.type, name);
  6797. if (y.mode != Addressing_Constant) {
  6798. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  6799. }
  6800. }
  6801. }
  6802. if (res == LoadDirective_Success) {
  6803. *o = x;
  6804. } else {
  6805. *o = y;
  6806. }
  6807. o->expr = node;
  6808. return Expr_Expr;
  6809. }
  6810. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  6811. if (x.mode == Addressing_Invalid) {
  6812. o->mode = Addressing_Value;
  6813. o->type = t_invalid;
  6814. o->expr = node;
  6815. return Expr_Expr;
  6816. }
  6817. bool y_is_diverging = false;
  6818. check_expr_base(c, &y, default_value, x.type);
  6819. switch (y.mode) {
  6820. case Addressing_NoValue:
  6821. if (is_diverging_expr(y.expr)) {
  6822. // Allow
  6823. y.mode = Addressing_Value;
  6824. y_is_diverging = true;
  6825. } else {
  6826. error_operand_no_value(&y);
  6827. y.mode = Addressing_Invalid;
  6828. }
  6829. break;
  6830. case Addressing_Type:
  6831. error_operand_not_expression(&y);
  6832. y.mode = Addressing_Invalid;
  6833. break;
  6834. }
  6835. if (y.mode == Addressing_Invalid) {
  6836. o->mode = Addressing_Value;
  6837. o->type = t_invalid;
  6838. o->expr = node;
  6839. return Expr_Expr;
  6840. }
  6841. Type *left_type = nullptr;
  6842. Type *right_type = nullptr;
  6843. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  6844. add_type_and_value(c, arg, x.mode, x.type, x.value);
  6845. if (left_type != nullptr) {
  6846. if (!y_is_diverging) {
  6847. check_assignment(c, &y, left_type, name);
  6848. }
  6849. } else {
  6850. check_or_else_expr_no_value_error(c, name, x, type_hint);
  6851. }
  6852. if (left_type == nullptr) {
  6853. left_type = t_invalid;
  6854. }
  6855. o->mode = Addressing_Value;
  6856. o->type = left_type;
  6857. o->expr = node;
  6858. return Expr_Expr;
  6859. }
  6860. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6861. ast_node(re, OrReturnExpr, node);
  6862. String name = re->token.string;
  6863. Operand x = {};
  6864. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  6865. if (x.mode == Addressing_Invalid) {
  6866. o->mode = Addressing_Value;
  6867. o->type = t_invalid;
  6868. o->expr = node;
  6869. return Expr_Expr;
  6870. }
  6871. Type *left_type = nullptr;
  6872. Type *right_type = nullptr;
  6873. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  6874. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  6875. if (right_type == nullptr) {
  6876. check_or_else_expr_no_value_error(c, name, x, type_hint);
  6877. } else {
  6878. Type *proc_type = base_type(c->curr_proc_sig);
  6879. GB_ASSERT(proc_type->kind == Type_Proc);
  6880. Type *result_type = proc_type->Proc.results;
  6881. if (result_type == nullptr) {
  6882. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  6883. } else {
  6884. GB_ASSERT(result_type->kind == Type_Tuple);
  6885. auto const &vars = result_type->Tuple.variables;
  6886. Type *end_type = vars[vars.count-1]->type;
  6887. if (vars.count > 1) {
  6888. if (!proc_type->Proc.has_named_results) {
  6889. 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));
  6890. }
  6891. }
  6892. Operand rhs = {};
  6893. rhs.type = right_type;
  6894. rhs.mode = Addressing_Value;
  6895. // TODO(bill): better error message
  6896. if (!check_is_assignable_to(c, &rhs, end_type)) {
  6897. gbString a = type_to_string(right_type);
  6898. gbString b = type_to_string(end_type);
  6899. gbString ret_type = type_to_string(result_type);
  6900. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  6901. if (vars.count == 1) {
  6902. error_line("\tProcedure return value type: %s\n", ret_type);
  6903. } else {
  6904. error_line("\tProcedure return value types: (%s)\n", ret_type);
  6905. }
  6906. gb_string_free(ret_type);
  6907. gb_string_free(b);
  6908. gb_string_free(a);
  6909. }
  6910. }
  6911. }
  6912. o->expr = node;
  6913. o->type = left_type;
  6914. if (left_type != nullptr) {
  6915. o->mode = Addressing_Value;
  6916. } else {
  6917. o->mode = Addressing_NoValue;
  6918. }
  6919. if (c->curr_proc_sig == nullptr) {
  6920. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  6921. }
  6922. if (c->in_defer) {
  6923. error(node, "'or_return' cannot be used within a defer statement");
  6924. }
  6925. return Expr_Expr;
  6926. }
  6927. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  6928. Type *bt = base_type(type);
  6929. StringSet fields_visited = {};
  6930. defer (string_set_destroy(&fields_visited));
  6931. StringMap<String> fields_visited_through_raw_union = {};
  6932. defer (string_map_destroy(&fields_visited_through_raw_union));
  6933. for (Ast *elem : elems) {
  6934. if (elem->kind != Ast_FieldValue) {
  6935. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6936. continue;
  6937. }
  6938. ast_node(fv, FieldValue, elem);
  6939. if (fv->field->kind != Ast_Ident) {
  6940. gbString expr_str = expr_to_string(fv->field);
  6941. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  6942. gb_string_free(expr_str);
  6943. continue;
  6944. }
  6945. String name = fv->field->Ident.token.string;
  6946. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6947. bool is_unknown = sel.entity == nullptr;
  6948. if (is_unknown) {
  6949. error(fv->field, "Unknown field '%.*s' in structure literal", LIT(name));
  6950. continue;
  6951. }
  6952. Entity *field = bt->Struct.fields[sel.index[0]];
  6953. add_entity_use(c, fv->field, field);
  6954. if (string_set_update(&fields_visited, name)) {
  6955. if (sel.index.count > 1) {
  6956. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  6957. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  6958. } else {
  6959. error(fv->field, "Duplicate or reused field '%.*s' in structure literal", LIT(sel.entity->token.string));
  6960. }
  6961. } else {
  6962. error(fv->field, "Duplicate field '%.*s' in structure literal", LIT(field->token.string));
  6963. }
  6964. continue;
  6965. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  6966. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  6967. continue;
  6968. }
  6969. if (sel.indirect) {
  6970. error(fv->field, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a structure literal", cast(int)sel.index.count-1, LIT(name));
  6971. continue;
  6972. }
  6973. if (sel.index.count > 1) {
  6974. if (is_constant) {
  6975. Type *ft = type;
  6976. for (i32 index : sel.index) {
  6977. Type *bt = base_type(ft);
  6978. switch (bt->kind) {
  6979. case Type_Struct:
  6980. if (bt->Struct.is_raw_union) {
  6981. is_constant = false;
  6982. break;
  6983. }
  6984. ft = bt->Struct.fields[index]->type;
  6985. break;
  6986. case Type_Array:
  6987. ft = bt->Array.elem;
  6988. break;
  6989. default:
  6990. GB_PANIC("invalid type: %s", type_to_string(ft));
  6991. break;
  6992. }
  6993. }
  6994. if (is_constant &&
  6995. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  6996. is_constant = false;
  6997. }
  6998. }
  6999. Type *nested_ft = bt;
  7000. for (i32 index : sel.index) {
  7001. Type *bt = base_type(nested_ft);
  7002. switch (bt->kind) {
  7003. case Type_Struct:
  7004. if (bt->Struct.is_raw_union) {
  7005. for (Entity *re : bt->Struct.fields) {
  7006. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7007. }
  7008. }
  7009. nested_ft = bt->Struct.fields[index]->type;
  7010. break;
  7011. case Type_Array:
  7012. nested_ft = bt->Array.elem;
  7013. break;
  7014. default:
  7015. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7016. break;
  7017. }
  7018. }
  7019. field = sel.entity;
  7020. }
  7021. Operand o = {};
  7022. check_expr_or_type(c, &o, fv->value, field->type);
  7023. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7024. is_constant = false;
  7025. }
  7026. if (is_constant) {
  7027. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7028. }
  7029. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7030. }
  7031. }
  7032. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7033. ExprKind kind = Expr_Expr;
  7034. ast_node(cl, CompoundLit, node);
  7035. Type *type = type_hint;
  7036. if (type != nullptr && is_type_untyped(type)) {
  7037. type = nullptr;
  7038. }
  7039. bool is_to_be_determined_array_count = false;
  7040. bool is_constant = true;
  7041. if (cl->type != nullptr) {
  7042. type = nullptr;
  7043. // [?]Type
  7044. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  7045. Ast *count = cl->type->ArrayType.count;
  7046. if (count->kind == Ast_UnaryExpr &&
  7047. count->UnaryExpr.op.kind == Token_Question) {
  7048. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  7049. is_to_be_determined_array_count = true;
  7050. }
  7051. if (cl->elems.count > 0) {
  7052. if (cl->type->ArrayType.tag != nullptr) {
  7053. Ast *tag = cl->type->ArrayType.tag;
  7054. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7055. String name = tag->BasicDirective.name.string;
  7056. if (name == "soa") {
  7057. error(node, "#soa arrays are not supported for compound literals");
  7058. return kind;
  7059. }
  7060. }
  7061. }
  7062. }
  7063. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  7064. if (cl->elems.count > 0) {
  7065. Ast *tag = cl->type->DynamicArrayType.tag;
  7066. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7067. String name = tag->BasicDirective.name.string;
  7068. if (name == "soa") {
  7069. error(node, "#soa arrays are not supported for compound literals");
  7070. return kind;
  7071. }
  7072. }
  7073. }
  7074. if (type == nullptr) {
  7075. type = check_type(c, cl->type);
  7076. }
  7077. }
  7078. if (type == nullptr) {
  7079. error(node, "Missing type in compound literal");
  7080. return kind;
  7081. }
  7082. Type *t = base_type(type);
  7083. if (is_type_polymorphic(t)) {
  7084. gbString str = type_to_string(type);
  7085. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7086. o->expr = node;
  7087. o->type = type;
  7088. gb_string_free(str);
  7089. return kind;
  7090. }
  7091. switch (t->kind) {
  7092. case Type_Struct: {
  7093. if (cl->elems.count == 0) {
  7094. break; // NOTE(bill): No need to init
  7095. }
  7096. if (t->Struct.is_raw_union) {
  7097. if (cl->elems.count > 0) {
  7098. // NOTE: unions cannot be constant
  7099. is_constant = false;
  7100. if (cl->elems[0]->kind != Ast_FieldValue) {
  7101. gbString type_str = type_to_string(type);
  7102. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7103. gb_string_free(type_str);
  7104. } else {
  7105. if (cl->elems.count != 1) {
  7106. gbString type_str = type_to_string(type);
  7107. 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);
  7108. gb_string_free(type_str);
  7109. } else {
  7110. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7111. }
  7112. }
  7113. }
  7114. break;
  7115. }
  7116. isize field_count = t->Struct.fields.count;
  7117. isize min_field_count = t->Struct.fields.count;
  7118. for (isize i = min_field_count-1; i >= 0; i--) {
  7119. Entity *e = t->Struct.fields[i];
  7120. GB_ASSERT(e->kind == Entity_Variable);
  7121. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7122. min_field_count--;
  7123. } else {
  7124. break;
  7125. }
  7126. }
  7127. if (cl->elems[0]->kind == Ast_FieldValue) {
  7128. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7129. } else {
  7130. bool seen_field_value = false;
  7131. for_array(index, cl->elems) {
  7132. Entity *field = nullptr;
  7133. Ast *elem = cl->elems[index];
  7134. if (elem->kind == Ast_FieldValue) {
  7135. seen_field_value = true;
  7136. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7137. continue;
  7138. } else if (seen_field_value) {
  7139. error(elem, "Value elements cannot be used after a 'field = value'");
  7140. continue;
  7141. }
  7142. if (index >= field_count) {
  7143. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7144. break;
  7145. }
  7146. if (field == nullptr) {
  7147. field = t->Struct.fields[index];
  7148. }
  7149. Operand o = {};
  7150. check_expr_or_type(c, &o, elem, field->type);
  7151. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7152. is_constant = false;
  7153. }
  7154. if (is_constant) {
  7155. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7156. }
  7157. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7158. }
  7159. if (cl->elems.count < field_count) {
  7160. if (min_field_count < field_count) {
  7161. if (cl->elems.count < min_field_count) {
  7162. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7163. }
  7164. } else {
  7165. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7166. }
  7167. }
  7168. }
  7169. break;
  7170. }
  7171. case Type_Slice:
  7172. case Type_Array:
  7173. case Type_DynamicArray:
  7174. case Type_SimdVector:
  7175. case Type_Matrix:
  7176. {
  7177. Type *elem_type = nullptr;
  7178. String context_name = {};
  7179. i64 max_type_count = -1;
  7180. if (t->kind == Type_Slice) {
  7181. elem_type = t->Slice.elem;
  7182. context_name = str_lit("slice literal");
  7183. } else if (t->kind == Type_Array) {
  7184. elem_type = t->Array.elem;
  7185. context_name = str_lit("array literal");
  7186. if (!is_to_be_determined_array_count) {
  7187. max_type_count = t->Array.count;
  7188. }
  7189. } else if (t->kind == Type_DynamicArray) {
  7190. elem_type = t->DynamicArray.elem;
  7191. context_name = str_lit("dynamic array literal");
  7192. is_constant = false;
  7193. if (!build_context.no_dynamic_literals) {
  7194. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7195. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7196. }
  7197. } else if (t->kind == Type_SimdVector) {
  7198. elem_type = t->SimdVector.elem;
  7199. context_name = str_lit("simd vector literal");
  7200. max_type_count = t->SimdVector.count;
  7201. } else if (t->kind == Type_Matrix) {
  7202. elem_type = t->Matrix.elem;
  7203. context_name = str_lit("matrix literal");
  7204. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7205. } else {
  7206. GB_PANIC("unreachable");
  7207. }
  7208. i64 max = 0;
  7209. Type *bet = base_type(elem_type);
  7210. if (!elem_type_can_be_constant(bet)) {
  7211. is_constant = false;
  7212. }
  7213. if (bet == t_invalid) {
  7214. break;
  7215. }
  7216. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7217. RangeCache rc = range_cache_make(heap_allocator());
  7218. defer (range_cache_destroy(&rc));
  7219. for (Ast *elem : cl->elems) {
  7220. if (elem->kind != Ast_FieldValue) {
  7221. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7222. continue;
  7223. }
  7224. ast_node(fv, FieldValue, elem);
  7225. if (is_ast_range(fv->field)) {
  7226. Token op = fv->field->BinaryExpr.op;
  7227. Operand x = {};
  7228. Operand y = {};
  7229. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7230. if (!ok) {
  7231. continue;
  7232. }
  7233. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7234. error(x.expr, "Expected a constant integer as an array field");
  7235. continue;
  7236. }
  7237. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7238. error(y.expr, "Expected a constant integer as an array field");
  7239. continue;
  7240. }
  7241. i64 lo = exact_value_to_i64(x.value);
  7242. i64 hi = exact_value_to_i64(y.value);
  7243. i64 max_index = hi;
  7244. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7245. hi -= 1;
  7246. } else { // .. (inclusive)
  7247. max_index += 1;
  7248. }
  7249. bool new_range = range_cache_add_range(&rc, lo, hi);
  7250. if (!new_range) {
  7251. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7252. continue;
  7253. }
  7254. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7255. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7256. continue;
  7257. }
  7258. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7259. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7260. continue;
  7261. }
  7262. if (max < hi) {
  7263. max = max_index;
  7264. }
  7265. Operand operand = {};
  7266. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7267. check_assignment(c, &operand, elem_type, context_name);
  7268. is_constant = is_constant && operand.mode == Addressing_Constant;
  7269. } else {
  7270. Operand op_index = {};
  7271. check_expr(c, &op_index, fv->field);
  7272. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7273. error(elem, "Expected a constant integer as an array field");
  7274. continue;
  7275. }
  7276. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7277. i64 index = exact_value_to_i64(op_index.value);
  7278. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7279. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7280. continue;
  7281. }
  7282. bool new_index = range_cache_add_index(&rc, index);
  7283. if (!new_index) {
  7284. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7285. continue;
  7286. }
  7287. if (max < index+1) {
  7288. max = index+1;
  7289. }
  7290. Operand operand = {};
  7291. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7292. check_assignment(c, &operand, elem_type, context_name);
  7293. is_constant = is_constant && operand.mode == Addressing_Constant;
  7294. }
  7295. }
  7296. cl->max_count = max;
  7297. } else {
  7298. isize index = 0;
  7299. for (; index < cl->elems.count; index++) {
  7300. Ast *e = cl->elems[index];
  7301. if (e == nullptr) {
  7302. error(node, "Invalid literal element");
  7303. continue;
  7304. }
  7305. if (e->kind == Ast_FieldValue) {
  7306. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7307. continue;
  7308. }
  7309. if (0 <= max_type_count && max_type_count <= index) {
  7310. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7311. }
  7312. Operand operand = {};
  7313. check_expr_with_type_hint(c, &operand, e, elem_type);
  7314. check_assignment(c, &operand, elem_type, context_name);
  7315. is_constant = is_constant && operand.mode == Addressing_Constant;
  7316. }
  7317. if (max < index) {
  7318. max = index;
  7319. }
  7320. }
  7321. if (t->kind == Type_Array) {
  7322. if (is_to_be_determined_array_count) {
  7323. t->Array.count = max;
  7324. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7325. if (0 < max && max < t->Array.count) {
  7326. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7327. }
  7328. }
  7329. }
  7330. if (t->kind == Type_SimdVector) {
  7331. if (!is_constant) {
  7332. // error(node, "Expected all constant elements for a simd vector");
  7333. }
  7334. }
  7335. if (t->kind == Type_DynamicArray) {
  7336. if (build_context.no_dynamic_literals && cl->elems.count) {
  7337. error(node, "Compound literals of dynamic types have been disabled");
  7338. }
  7339. }
  7340. if (t->kind == Type_Matrix) {
  7341. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7342. if (0 < max && max < max_type_count) {
  7343. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7344. }
  7345. }
  7346. }
  7347. break;
  7348. }
  7349. case Type_EnumeratedArray:
  7350. {
  7351. Type *elem_type = t->EnumeratedArray.elem;
  7352. Type *index_type = t->EnumeratedArray.index;
  7353. String context_name = str_lit("enumerated array literal");
  7354. i64 max_type_count = t->EnumeratedArray.count;
  7355. gbString index_type_str = type_to_string(index_type);
  7356. defer (gb_string_free(index_type_str));
  7357. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7358. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7359. String total_lo_string = {};
  7360. String total_hi_string = {};
  7361. GB_ASSERT(is_type_enum(index_type));
  7362. {
  7363. Type *bt = base_type(index_type);
  7364. GB_ASSERT(bt->kind == Type_Enum);
  7365. for (Entity *f : bt->Enum.fields) {
  7366. if (f->kind != Entity_Constant) {
  7367. continue;
  7368. }
  7369. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7370. total_lo_string = f->token.string;
  7371. }
  7372. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7373. total_hi_string = f->token.string;
  7374. }
  7375. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  7376. break;
  7377. }
  7378. }
  7379. }
  7380. i64 max = 0;
  7381. Type *bet = base_type(elem_type);
  7382. if (!elem_type_can_be_constant(bet)) {
  7383. is_constant = false;
  7384. }
  7385. if (bet == t_invalid) {
  7386. break;
  7387. }
  7388. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  7389. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  7390. defer (map_destroy(&seen));
  7391. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7392. RangeCache rc = range_cache_make(heap_allocator());
  7393. defer (range_cache_destroy(&rc));
  7394. for (Ast *elem : cl->elems) {
  7395. if (elem->kind != Ast_FieldValue) {
  7396. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7397. continue;
  7398. }
  7399. ast_node(fv, FieldValue, elem);
  7400. if (is_ast_range(fv->field)) {
  7401. Token op = fv->field->BinaryExpr.op;
  7402. Operand x = {};
  7403. Operand y = {};
  7404. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  7405. if (!ok) {
  7406. continue;
  7407. }
  7408. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7409. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7410. continue;
  7411. }
  7412. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7413. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7414. continue;
  7415. }
  7416. i64 lo = exact_value_to_i64(x.value);
  7417. i64 hi = exact_value_to_i64(y.value);
  7418. i64 max_index = hi;
  7419. if (op.kind == Token_RangeHalf) {
  7420. hi -= 1;
  7421. }
  7422. bool new_range = range_cache_add_range(&rc, lo, hi);
  7423. if (!new_range) {
  7424. gbString lo_str = expr_to_string(x.expr);
  7425. gbString hi_str = expr_to_string(y.expr);
  7426. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  7427. gb_string_free(hi_str);
  7428. gb_string_free(lo_str);
  7429. continue;
  7430. }
  7431. // NOTE(bill): These are sanity checks for invalid enum values
  7432. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  7433. gbString lo_str = expr_to_string(x.expr);
  7434. 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));
  7435. gb_string_free(lo_str);
  7436. continue;
  7437. }
  7438. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  7439. gbString hi_str = expr_to_string(y.expr);
  7440. 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));
  7441. gb_string_free(hi_str);
  7442. continue;
  7443. }
  7444. if (max < hi) {
  7445. max = max_index;
  7446. }
  7447. Operand operand = {};
  7448. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7449. check_assignment(c, &operand, elem_type, context_name);
  7450. is_constant = is_constant && operand.mode == Addressing_Constant;
  7451. TokenKind upper_op = Token_LtEq;
  7452. if (op.kind == Token_RangeHalf) {
  7453. upper_op = Token_Lt;
  7454. }
  7455. add_to_seen_map(c, &seen, upper_op, x, x, y);
  7456. } else {
  7457. Operand op_index = {};
  7458. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  7459. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  7460. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7461. continue;
  7462. }
  7463. i64 index = exact_value_to_i64(op_index.value);
  7464. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  7465. gbString idx_str = expr_to_string(op_index.expr);
  7466. 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));
  7467. gb_string_free(idx_str);
  7468. continue;
  7469. }
  7470. bool new_index = range_cache_add_index(&rc, index);
  7471. if (!new_index) {
  7472. gbString idx_str = expr_to_string(op_index.expr);
  7473. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  7474. gb_string_free(idx_str);
  7475. continue;
  7476. }
  7477. if (max < index+1) {
  7478. max = index+1;
  7479. }
  7480. Operand operand = {};
  7481. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7482. check_assignment(c, &operand, elem_type, context_name);
  7483. is_constant = is_constant && operand.mode == Addressing_Constant;
  7484. add_to_seen_map(c, &seen, op_index);
  7485. }
  7486. }
  7487. cl->max_count = max;
  7488. } else {
  7489. isize index = 0;
  7490. for (; index < cl->elems.count; index++) {
  7491. Ast *e = cl->elems[index];
  7492. if (e == nullptr) {
  7493. error(node, "Invalid literal element");
  7494. continue;
  7495. }
  7496. if (e->kind == Ast_FieldValue) {
  7497. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7498. continue;
  7499. }
  7500. if (0 <= max_type_count && max_type_count <= index) {
  7501. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7502. }
  7503. Operand operand = {};
  7504. check_expr_with_type_hint(c, &operand, e, elem_type);
  7505. check_assignment(c, &operand, elem_type, context_name);
  7506. is_constant = is_constant && operand.mode == Addressing_Constant;
  7507. }
  7508. if (max < index) {
  7509. max = index;
  7510. }
  7511. }
  7512. bool was_error = false;
  7513. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7514. if (0 < max && max < t->EnumeratedArray.count) {
  7515. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  7516. was_error = true;
  7517. } else {
  7518. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  7519. was_error = true;
  7520. }
  7521. }
  7522. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  7523. if (cl->elems.count > 0 && !was_error && !is_partial) {
  7524. TEMPORARY_ALLOCATOR_GUARD();
  7525. Type *et = base_type(index_type);
  7526. GB_ASSERT(et->kind == Type_Enum);
  7527. auto fields = et->Enum.fields;
  7528. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  7529. for (Entity *f : fields) {
  7530. if (f->kind != Entity_Constant) {
  7531. continue;
  7532. }
  7533. ExactValue v = f->Constant.value;
  7534. auto found = map_get(&seen, hash_exact_value(v));
  7535. if (!found) {
  7536. array_add(&unhandled, f);
  7537. }
  7538. }
  7539. if (unhandled.count > 0) {
  7540. begin_error_block();
  7541. defer (end_error_block());
  7542. if (unhandled.count == 1) {
  7543. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  7544. } else {
  7545. error(node, "Unhandled enumerated array cases:");
  7546. for_array(i, unhandled) {
  7547. Entity *f = unhandled[i];
  7548. error_line("\t%.*s\n", LIT(f->token.string));
  7549. }
  7550. }
  7551. error_line("\n");
  7552. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  7553. }
  7554. }
  7555. break;
  7556. }
  7557. case Type_Basic: {
  7558. if (!is_type_any(t)) {
  7559. if (cl->elems.count != 0) {
  7560. gbString s = type_to_string(t);
  7561. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  7562. gb_string_free(s);
  7563. is_constant = false;
  7564. }
  7565. break;
  7566. }
  7567. if (cl->elems.count == 0) {
  7568. break; // NOTE(bill): No need to init
  7569. }
  7570. { // Checker values
  7571. Type *field_types[2] = {t_rawptr, t_typeid};
  7572. isize field_count = 2;
  7573. if (cl->elems[0]->kind == Ast_FieldValue) {
  7574. bool fields_visited[2] = {};
  7575. for_array(i, cl->elems) {
  7576. Ast *elem = cl->elems[i];
  7577. if (elem->kind != Ast_FieldValue) {
  7578. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7579. continue;
  7580. }
  7581. ast_node(fv, FieldValue, elem);
  7582. if (fv->field->kind != Ast_Ident) {
  7583. gbString expr_str = expr_to_string(fv->field);
  7584. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  7585. gb_string_free(expr_str);
  7586. continue;
  7587. }
  7588. String name = fv->field->Ident.token.string;
  7589. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7590. if (sel.entity == nullptr) {
  7591. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  7592. continue;
  7593. }
  7594. isize index = sel.index[0];
  7595. if (fields_visited[index]) {
  7596. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  7597. continue;
  7598. }
  7599. fields_visited[index] = true;
  7600. check_expr(c, o, fv->value);
  7601. // NOTE(bill): 'any' literals can never be constant
  7602. is_constant = false;
  7603. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7604. }
  7605. } else {
  7606. for_array(index, cl->elems) {
  7607. Ast *elem = cl->elems[index];
  7608. if (elem->kind == Ast_FieldValue) {
  7609. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7610. continue;
  7611. }
  7612. check_expr(c, o, elem);
  7613. if (index >= field_count) {
  7614. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  7615. break;
  7616. }
  7617. // NOTE(bill): 'any' literals can never be constant
  7618. is_constant = false;
  7619. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7620. }
  7621. if (cl->elems.count < field_count) {
  7622. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  7623. }
  7624. }
  7625. }
  7626. break;
  7627. }
  7628. case Type_Map: {
  7629. if (cl->elems.count == 0) {
  7630. break;
  7631. }
  7632. is_constant = false;
  7633. { // Checker values
  7634. bool key_is_typeid = is_type_typeid(t->Map.key);
  7635. bool value_is_typeid = is_type_typeid(t->Map.value);
  7636. for (Ast *elem : cl->elems) {
  7637. if (elem->kind != Ast_FieldValue) {
  7638. error(elem, "Only 'field = value' elements are allowed in a map literal");
  7639. continue;
  7640. }
  7641. ast_node(fv, FieldValue, elem);
  7642. if (key_is_typeid) {
  7643. check_expr_or_type(c, o, fv->field, t->Map.key);
  7644. } else {
  7645. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  7646. }
  7647. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  7648. if (o->mode == Addressing_Invalid) {
  7649. continue;
  7650. }
  7651. if (value_is_typeid) {
  7652. check_expr_or_type(c, o, fv->value, t->Map.value);
  7653. } else {
  7654. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  7655. }
  7656. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  7657. }
  7658. }
  7659. if (build_context.no_dynamic_literals && cl->elems.count) {
  7660. error(node, "Compound literals of dynamic types have been disabled");
  7661. } else {
  7662. add_map_reserve_dependencies(c);
  7663. add_map_set_dependencies(c);
  7664. }
  7665. break;
  7666. }
  7667. case Type_BitSet: {
  7668. if (cl->elems.count == 0) {
  7669. break; // NOTE(bill): No need to init
  7670. }
  7671. Type *et = base_type(t->BitSet.elem);
  7672. isize field_count = 0;
  7673. if (et->kind == Type_Enum) {
  7674. field_count = et->Enum.fields.count;
  7675. }
  7676. if (cl->elems[0]->kind == Ast_FieldValue) {
  7677. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  7678. is_constant = false;
  7679. } else {
  7680. for (Ast *elem : cl->elems) {
  7681. if (elem->kind == Ast_FieldValue) {
  7682. error(elem, "'field = value' in a bit_set a literal is not allowed");
  7683. continue;
  7684. }
  7685. check_expr_with_type_hint(c, o, elem, et);
  7686. if (is_constant) {
  7687. is_constant = o->mode == Addressing_Constant;
  7688. }
  7689. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  7690. if (o->mode == Addressing_Constant) {
  7691. i64 lower = t->BitSet.lower;
  7692. i64 upper = t->BitSet.upper;
  7693. i64 v = exact_value_to_i64(o->value);
  7694. if (lower <= v && v <= upper) {
  7695. // okay
  7696. } else {
  7697. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  7698. continue;
  7699. }
  7700. }
  7701. }
  7702. }
  7703. break;
  7704. }
  7705. default: {
  7706. if (cl->elems.count == 0) {
  7707. break; // NOTE(bill): No need to init
  7708. }
  7709. gbString str = type_to_string(type);
  7710. error(node, "Invalid compound literal type '%s'", str);
  7711. gb_string_free(str);
  7712. return kind;
  7713. }
  7714. }
  7715. if (is_constant) {
  7716. o->mode = Addressing_Constant;
  7717. if (is_type_bit_set(type)) {
  7718. // NOTE(bill): Encode as an integer
  7719. Type *bt = base_type(type);
  7720. BigInt bits = {};
  7721. BigInt one = {};
  7722. big_int_from_u64(&one, 1);
  7723. for (Ast *e : cl->elems) {
  7724. GB_ASSERT(e->kind != Ast_FieldValue);
  7725. TypeAndValue tav = e->tav;
  7726. if (tav.mode != Addressing_Constant) {
  7727. continue;
  7728. }
  7729. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  7730. i64 v = big_int_to_i64(&tav.value.value_integer);
  7731. i64 lower = bt->BitSet.lower;
  7732. u64 index = cast(u64)(v-lower);
  7733. BigInt bit = {};
  7734. big_int_from_u64(&bit, index);
  7735. big_int_shl(&bit, &one, &bit);
  7736. big_int_or(&bits, &bits, &bit);
  7737. }
  7738. o->value.kind = ExactValue_Integer;
  7739. o->value.value_integer = bits;
  7740. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  7741. ExactValue value = exact_value_compound(node);
  7742. Type *bt = core_type(type);
  7743. if (bt->kind == Type_Basic) {
  7744. if (bt->Basic.flags & BasicFlag_Boolean) {
  7745. value = exact_value_bool(false);
  7746. } else if (bt->Basic.flags & BasicFlag_Integer) {
  7747. value = exact_value_i64(0);
  7748. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  7749. value = exact_value_i64(0);
  7750. } else if (bt->Basic.flags & BasicFlag_Float) {
  7751. value = exact_value_float(0);
  7752. } else if (bt->Basic.flags & BasicFlag_Complex) {
  7753. value = exact_value_complex(0, 0);
  7754. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  7755. value = exact_value_quaternion(0, 0, 0, 0);
  7756. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  7757. value = exact_value_pointer(0);
  7758. } else if (bt->Basic.flags & BasicFlag_String) {
  7759. String empty_string = {};
  7760. value = exact_value_string(empty_string);
  7761. } else if (bt->Basic.flags & BasicFlag_Rune) {
  7762. value = exact_value_i64(0);
  7763. }
  7764. }
  7765. o->value = value;
  7766. } else {
  7767. o->value = exact_value_compound(node);
  7768. }
  7769. } else {
  7770. o->mode = Addressing_Value;
  7771. }
  7772. o->type = type;
  7773. return kind;
  7774. }
  7775. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7776. ExprKind kind = Expr_Expr;
  7777. ast_node(ta, TypeAssertion, node);
  7778. check_expr(c, o, ta->expr);
  7779. node->viral_state_flags |= ta->expr->viral_state_flags;
  7780. if (o->mode == Addressing_Invalid) {
  7781. o->expr = node;
  7782. return kind;
  7783. }
  7784. if (o->mode == Addressing_Constant) {
  7785. gbString expr_str = expr_to_string(o->expr);
  7786. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  7787. gb_string_free(expr_str);
  7788. o->mode = Addressing_Invalid;
  7789. o->expr = node;
  7790. return kind;
  7791. }
  7792. if (is_type_untyped(o->type)) {
  7793. gbString expr_str = expr_to_string(o->expr);
  7794. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  7795. gb_string_free(expr_str);
  7796. o->mode = Addressing_Invalid;
  7797. o->expr = node;
  7798. return kind;
  7799. }
  7800. Type *src = type_deref(o->type);
  7801. Type *bsrc = base_type(src);
  7802. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  7803. if (!is_type_union(src)) {
  7804. gbString str = type_to_string(o->type);
  7805. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  7806. gb_string_free(str);
  7807. o->mode = Addressing_Invalid;
  7808. o->expr = node;
  7809. return kind;
  7810. }
  7811. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  7812. bool allowed = false;
  7813. for (Type *vt : bsrc->Union.variants) {
  7814. if (are_types_identical(vt, type_hint)) {
  7815. allowed = true;
  7816. add_type_info_type(c, vt);
  7817. break;
  7818. }
  7819. }
  7820. if (allowed) {
  7821. add_type_info_type(c, o->type);
  7822. o->type = type_hint;
  7823. o->mode = Addressing_OptionalOk;
  7824. return kind;
  7825. }
  7826. }
  7827. if (bsrc->Union.variants.count != 1) {
  7828. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  7829. o->mode = Addressing_Invalid;
  7830. o->expr = node;
  7831. return kind;
  7832. }
  7833. add_type_info_type(c, o->type);
  7834. add_type_info_type(c, bsrc->Union.variants[0]);
  7835. o->type = bsrc->Union.variants[0];
  7836. o->mode = Addressing_OptionalOk;
  7837. } else {
  7838. Type *t = check_type(c, ta->type);
  7839. Type *dst = t;
  7840. if (is_type_union(src)) {
  7841. bool ok = false;
  7842. for (Type *vt : bsrc->Union.variants) {
  7843. if (are_types_identical(vt, dst)) {
  7844. ok = true;
  7845. break;
  7846. }
  7847. }
  7848. if (!ok) {
  7849. gbString expr_str = expr_to_string(o->expr);
  7850. gbString dst_type_str = type_to_string(t);
  7851. defer (gb_string_free(expr_str));
  7852. defer (gb_string_free(dst_type_str));
  7853. if (bsrc->Union.variants.count == 0) {
  7854. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  7855. } else {
  7856. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  7857. }
  7858. o->mode = Addressing_Invalid;
  7859. o->expr = node;
  7860. return kind;
  7861. }
  7862. add_type_info_type(c, o->type);
  7863. add_type_info_type(c, t);
  7864. o->type = t;
  7865. o->mode = Addressing_OptionalOk;
  7866. } else if (is_type_any(src)) {
  7867. o->type = t;
  7868. o->mode = Addressing_OptionalOk;
  7869. add_type_info_type(c, o->type);
  7870. add_type_info_type(c, t);
  7871. } else {
  7872. gbString str = type_to_string(o->type);
  7873. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  7874. gb_string_free(str);
  7875. o->mode = Addressing_Invalid;
  7876. o->expr = node;
  7877. return kind;
  7878. }
  7879. }
  7880. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  7881. add_package_dependency(c, "runtime", "type_assertion_check");
  7882. add_package_dependency(c, "runtime", "type_assertion_check2");
  7883. }
  7884. return kind;
  7885. }
  7886. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7887. ast_node(se, SelectorCallExpr, node);
  7888. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  7889. // COM APIs is a great example of where this kind of thing is extremely useful
  7890. // General idea:
  7891. //
  7892. // x->y(123) == x.y(x, 123)
  7893. //
  7894. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  7895. // Just regenerating a new AST aids things
  7896. //
  7897. // TODO(bill): Is this a good hack or not?
  7898. //
  7899. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  7900. if (se->modified_call) {
  7901. // Prevent double evaluation
  7902. o->expr = node;
  7903. o->type = node->tav.type;
  7904. o->value = node->tav.value;
  7905. o->mode = node->tav.mode;
  7906. return Expr_Expr;
  7907. }
  7908. bool allow_arrow_right_selector_expr;
  7909. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  7910. c->allow_arrow_right_selector_expr = true;
  7911. Operand x = {};
  7912. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  7913. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  7914. if (x.mode == Addressing_Invalid || x.type == t_invalid) {
  7915. o->mode = Addressing_Invalid;
  7916. o->type = t_invalid;
  7917. o->expr = node;
  7918. return kind;
  7919. }
  7920. if (!is_type_proc(x.type)) {
  7921. gbString type_str = type_to_string(x.type);
  7922. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  7923. gb_string_free(type_str);
  7924. o->mode = Addressing_Invalid;
  7925. o->type = t_invalid;
  7926. o->expr = node;
  7927. return Expr_Stmt;
  7928. }
  7929. ast_node(ce, CallExpr, se->call);
  7930. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  7931. Ast *first_arg = x.expr->SelectorExpr.expr;
  7932. GB_ASSERT(first_arg != nullptr);
  7933. Entity *e = entity_of_node(se->expr);
  7934. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  7935. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  7936. }
  7937. Type *pt = base_type(x.type);
  7938. GB_ASSERT(pt->kind == Type_Proc);
  7939. Type *first_type = nullptr;
  7940. String first_arg_name = {};
  7941. if (pt->Proc.param_count > 0) {
  7942. Entity *f = pt->Proc.params->Tuple.variables[0];
  7943. first_type = f->type;
  7944. first_arg_name = f->token.string;
  7945. }
  7946. if (first_arg_name.len == 0) {
  7947. first_arg_name = str_lit("_");
  7948. }
  7949. if (first_type == nullptr) {
  7950. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  7951. o->mode = Addressing_Invalid;
  7952. o->type = t_invalid;
  7953. o->expr = node;
  7954. return Expr_Stmt;
  7955. }
  7956. Operand y = {};
  7957. y.mode = first_arg->tav.mode;
  7958. y.type = first_arg->tav.type;
  7959. y.value = first_arg->tav.value;
  7960. if (check_is_assignable_to(c, &y, first_type)) {
  7961. // Do nothing, it's valid
  7962. } else {
  7963. Operand z = y;
  7964. z.type = type_deref(y.type);
  7965. if (check_is_assignable_to(c, &z, first_type)) {
  7966. // NOTE(bill): AST GENERATION HACK!
  7967. Token op = {Token_Pointer};
  7968. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  7969. } else if (y.mode == Addressing_Variable) {
  7970. Operand w = y;
  7971. w.type = alloc_type_pointer(y.type);
  7972. if (check_is_assignable_to(c, &w, first_type)) {
  7973. // NOTE(bill): AST GENERATION HACK!
  7974. Token op = {Token_And};
  7975. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  7976. }
  7977. }
  7978. }
  7979. if (ce->args.count > 0) {
  7980. bool fail = false;
  7981. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  7982. for (Ast *arg : ce->args) {
  7983. bool mix = false;
  7984. if (first_is_field_value) {
  7985. mix = arg->kind != Ast_FieldValue;
  7986. } else {
  7987. mix = arg->kind == Ast_FieldValue;
  7988. }
  7989. if (mix) {
  7990. fail = true;
  7991. break;
  7992. }
  7993. }
  7994. if (!fail && first_is_field_value) {
  7995. Token op = {Token_Eq};
  7996. AstFile *f = first_arg->file();
  7997. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  7998. }
  7999. }
  8000. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8001. modified_args[0] = first_arg;
  8002. slice_copy(&modified_args, ce->args, 1);
  8003. ce->args = modified_args;
  8004. se->modified_call = true;
  8005. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8006. c->allow_arrow_right_selector_expr = true;
  8007. check_expr_base(c, o, se->call, type_hint);
  8008. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8009. o->expr = node;
  8010. return Expr_Expr;
  8011. }
  8012. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8013. ExprKind kind = Expr_Expr;
  8014. ast_node(ie, IndexExpr, node);
  8015. check_expr(c, o, ie->expr);
  8016. node->viral_state_flags |= ie->expr->viral_state_flags;
  8017. if (o->mode == Addressing_Invalid) {
  8018. o->expr = node;
  8019. return kind;
  8020. }
  8021. Type *t = base_type(type_deref(o->type));
  8022. bool is_ptr = is_type_pointer(o->type);
  8023. bool is_const = o->mode == Addressing_Constant;
  8024. if (is_type_map(t)) {
  8025. Operand key = {};
  8026. if (is_type_typeid(t->Map.key)) {
  8027. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8028. } else {
  8029. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8030. }
  8031. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8032. if (key.mode == Addressing_Invalid) {
  8033. o->mode = Addressing_Invalid;
  8034. o->expr = node;
  8035. return kind;
  8036. }
  8037. o->mode = Addressing_MapIndex;
  8038. o->type = t->Map.value;
  8039. o->expr = node;
  8040. add_map_get_dependencies(c);
  8041. add_map_set_dependencies(c);
  8042. return Expr_Expr;
  8043. }
  8044. i64 max_count = -1;
  8045. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8046. if (is_const) {
  8047. if (is_type_array(t)) {
  8048. // OKay
  8049. } else if (is_type_slice(t)) {
  8050. // Okay
  8051. } else if (is_type_enumerated_array(t)) {
  8052. // Okay
  8053. } else if (is_type_string(t)) {
  8054. // Okay
  8055. } else if (is_type_relative_slice(t)) {
  8056. // Okay
  8057. } else if (is_type_matrix(t)) {
  8058. // Okay
  8059. } else {
  8060. valid = false;
  8061. }
  8062. }
  8063. if (!valid) {
  8064. gbString str = expr_to_string(o->expr);
  8065. gbString type_str = type_to_string(o->type);
  8066. defer (gb_string_free(str));
  8067. defer (gb_string_free(type_str));
  8068. if (is_const) {
  8069. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8070. } else {
  8071. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8072. }
  8073. o->mode = Addressing_Invalid;
  8074. o->expr = node;
  8075. return kind;
  8076. }
  8077. if (ie->index == nullptr) {
  8078. gbString str = expr_to_string(o->expr);
  8079. error(o->expr, "Missing index for '%s'", str);
  8080. gb_string_free(str);
  8081. o->mode = Addressing_Invalid;
  8082. o->expr = node;
  8083. return kind;
  8084. }
  8085. Type *index_type_hint = nullptr;
  8086. if (is_type_enumerated_array(t)) {
  8087. Type *bt = base_type(t);
  8088. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8089. index_type_hint = bt->EnumeratedArray.index;
  8090. }
  8091. i64 index = 0;
  8092. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8093. if (is_const) {
  8094. if (index < 0) {
  8095. gbString str = expr_to_string(o->expr);
  8096. error(o->expr, "Cannot index a constant '%s'", str);
  8097. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8098. gb_string_free(str);
  8099. o->mode = Addressing_Invalid;
  8100. o->expr = node;
  8101. return kind;
  8102. } else if (ok) {
  8103. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8104. o->mode = Addressing_Constant;
  8105. bool success = false;
  8106. bool finish = false;
  8107. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8108. if (!success) {
  8109. gbString str = expr_to_string(o->expr);
  8110. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8111. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8112. gb_string_free(str);
  8113. o->mode = Addressing_Invalid;
  8114. o->expr = node;
  8115. return kind;
  8116. }
  8117. }
  8118. }
  8119. if (type_hint != nullptr && is_type_matrix(t)) {
  8120. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8121. // if a type hint exists
  8122. }
  8123. return kind;
  8124. }
  8125. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8126. ExprKind kind = Expr_Stmt;
  8127. ast_node(se, SliceExpr, node);
  8128. check_expr(c, o, se->expr);
  8129. node->viral_state_flags |= se->expr->viral_state_flags;
  8130. if (o->mode == Addressing_Invalid) {
  8131. o->mode = Addressing_Invalid;
  8132. o->expr = node;
  8133. return kind;
  8134. }
  8135. bool valid = false;
  8136. i64 max_count = -1;
  8137. Type *t = base_type(type_deref(o->type));
  8138. switch (t->kind) {
  8139. case Type_Basic:
  8140. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8141. valid = true;
  8142. if (o->mode == Addressing_Constant) {
  8143. max_count = o->value.value_string.len;
  8144. }
  8145. o->type = type_deref(o->type);
  8146. }
  8147. break;
  8148. case Type_Array:
  8149. valid = true;
  8150. max_count = t->Array.count;
  8151. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8152. gbString str = expr_to_string(node);
  8153. error(node, "Cannot slice array '%s', value is not addressable", str);
  8154. gb_string_free(str);
  8155. o->mode = Addressing_Invalid;
  8156. o->expr = node;
  8157. return kind;
  8158. }
  8159. o->type = alloc_type_slice(t->Array.elem);
  8160. break;
  8161. case Type_MultiPointer:
  8162. valid = true;
  8163. o->type = type_deref(o->type);
  8164. break;
  8165. case Type_Slice:
  8166. valid = true;
  8167. o->type = type_deref(o->type);
  8168. break;
  8169. case Type_DynamicArray:
  8170. valid = true;
  8171. o->type = alloc_type_slice(t->DynamicArray.elem);
  8172. break;
  8173. case Type_Struct:
  8174. if (is_type_soa_struct(t)) {
  8175. valid = true;
  8176. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8177. }
  8178. break;
  8179. case Type_RelativeSlice:
  8180. valid = true;
  8181. o->type = t->RelativeSlice.slice_type;
  8182. if (o->mode != Addressing_Variable) {
  8183. gbString str = expr_to_string(node);
  8184. error(node, "Cannot relative slice '%s', as value is not addressable", str);
  8185. gb_string_free(str);
  8186. o->mode = Addressing_Invalid;
  8187. o->expr = node;
  8188. return kind;
  8189. }
  8190. break;
  8191. case Type_EnumeratedArray:
  8192. {
  8193. gbString str = expr_to_string(o->expr);
  8194. gbString type_str = type_to_string(o->type);
  8195. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8196. gb_string_free(type_str);
  8197. gb_string_free(str);
  8198. o->mode = Addressing_Invalid;
  8199. o->expr = node;
  8200. return kind;
  8201. }
  8202. break;
  8203. }
  8204. if (!valid) {
  8205. gbString str = expr_to_string(o->expr);
  8206. gbString type_str = type_to_string(o->type);
  8207. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8208. gb_string_free(type_str);
  8209. gb_string_free(str);
  8210. o->mode = Addressing_Invalid;
  8211. o->expr = node;
  8212. return kind;
  8213. }
  8214. if (se->low == nullptr && se->high != nullptr) {
  8215. // It is okay to continue as it will assume the 1st index is zero
  8216. }
  8217. i64 indices[2] = {};
  8218. Ast *nodes[2] = {se->low, se->high};
  8219. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8220. i64 index = max_count;
  8221. if (nodes[i] != nullptr) {
  8222. i64 capacity = -1;
  8223. if (max_count >= 0) {
  8224. capacity = max_count;
  8225. }
  8226. i64 j = 0;
  8227. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8228. index = j;
  8229. }
  8230. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8231. } else if (i == 0) {
  8232. index = 0;
  8233. }
  8234. indices[i] = index;
  8235. }
  8236. for (isize i = 0; i < gb_count_of(indices); i++) {
  8237. i64 a = indices[i];
  8238. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8239. i64 b = indices[j];
  8240. if (a > b && b >= 0) {
  8241. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8242. }
  8243. }
  8244. }
  8245. if (max_count < 0) {
  8246. if (o->mode == Addressing_Constant) {
  8247. gbString s = expr_to_string(se->expr);
  8248. error(se->expr, "Cannot slice constant value '%s'", s);
  8249. gb_string_free(s);
  8250. }
  8251. }
  8252. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8253. /*
  8254. x[:] -> [^]T
  8255. x[i:] -> [^]T
  8256. x[:n] -> []T
  8257. x[i:n] -> []T
  8258. */
  8259. o->type = alloc_type_slice(t->MultiPointer.elem);
  8260. }
  8261. o->mode = Addressing_Value;
  8262. if (is_type_string(t) && max_count >= 0) {
  8263. bool all_constant = true;
  8264. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8265. if (nodes[i] != nullptr) {
  8266. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8267. if (tav.mode != Addressing_Constant) {
  8268. all_constant = false;
  8269. break;
  8270. }
  8271. }
  8272. }
  8273. if (!all_constant) {
  8274. gbString str = expr_to_string(o->expr);
  8275. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8276. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8277. gb_string_free(str);
  8278. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8279. o->expr = node;
  8280. return kind;
  8281. }
  8282. String s = {};
  8283. if (o->value.kind == ExactValue_String) {
  8284. s = o->value.value_string;
  8285. }
  8286. o->mode = Addressing_Constant;
  8287. o->type = t;
  8288. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8289. }
  8290. return kind;
  8291. }
  8292. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8293. u32 prev_state_flags = c->state_flags;
  8294. defer (c->state_flags = prev_state_flags);
  8295. if (node->state_flags != 0) {
  8296. u32 in = node->state_flags;
  8297. u32 out = c->state_flags;
  8298. if (in & StateFlag_no_bounds_check) {
  8299. out |= StateFlag_no_bounds_check;
  8300. out &= ~StateFlag_bounds_check;
  8301. } else if (in & StateFlag_bounds_check) {
  8302. out |= StateFlag_bounds_check;
  8303. out &= ~StateFlag_no_bounds_check;
  8304. }
  8305. if (in & StateFlag_no_type_assert) {
  8306. out |= StateFlag_no_type_assert;
  8307. out &= ~StateFlag_type_assert;
  8308. } else if (in & StateFlag_type_assert) {
  8309. out |= StateFlag_type_assert;
  8310. out &= ~StateFlag_no_type_assert;
  8311. }
  8312. c->state_flags = out;
  8313. }
  8314. ExprKind kind = Expr_Stmt;
  8315. o->mode = Addressing_Invalid;
  8316. o->type = t_invalid;
  8317. o->value = {ExactValue_Invalid};
  8318. switch (node->kind) {
  8319. default:
  8320. return kind;
  8321. case_ast_node(be, BadExpr, node)
  8322. return kind;
  8323. case_end;
  8324. case_ast_node(i, Implicit, node)
  8325. switch (i->kind) {
  8326. case Token_context:
  8327. {
  8328. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8329. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8330. return kind;
  8331. }
  8332. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8333. c->scope->flags |= ScopeFlag_ContextDefined;
  8334. }
  8335. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8336. error(node, "'context' has not been defined within this scope");
  8337. // Continue with value
  8338. }
  8339. init_core_context(c->checker);
  8340. o->mode = Addressing_Context;
  8341. o->type = t_context;
  8342. }
  8343. break;
  8344. default:
  8345. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8346. return kind;
  8347. }
  8348. case_end;
  8349. case_ast_node(i, Ident, node);
  8350. check_ident(c, o, node, nullptr, type_hint, false);
  8351. case_end;
  8352. case_ast_node(u, Undef, node);
  8353. o->mode = Addressing_Value;
  8354. o->type = t_untyped_undef;
  8355. case_end;
  8356. case_ast_node(bl, BasicLit, node);
  8357. Type *t = t_invalid;
  8358. switch (node->tav.value.kind) {
  8359. case ExactValue_String: t = t_untyped_string; break;
  8360. case ExactValue_Float: t = t_untyped_float; break;
  8361. case ExactValue_Complex: t = t_untyped_complex; break;
  8362. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  8363. case ExactValue_Integer:
  8364. t = t_untyped_integer;
  8365. if (bl->token.kind == Token_Rune) {
  8366. t = t_untyped_rune;
  8367. }
  8368. break;
  8369. default:
  8370. GB_PANIC("Unhandled value type for basic literal");
  8371. break;
  8372. }
  8373. o->mode = Addressing_Constant;
  8374. o->type = t;
  8375. o->value = node->tav.value;
  8376. case_end;
  8377. case_ast_node(bd, BasicDirective, node);
  8378. kind = check_basic_directive_expr(c, o, node, type_hint);
  8379. case_end;
  8380. case_ast_node(pg, ProcGroup, node);
  8381. error(node, "Illegal use of a procedure group");
  8382. o->mode = Addressing_Invalid;
  8383. case_end;
  8384. case_ast_node(pl, ProcLit, node);
  8385. CheckerContext ctx = *c;
  8386. DeclInfo *decl = nullptr;
  8387. Type *type = alloc_type(Type_Proc);
  8388. check_open_scope(&ctx, pl->type);
  8389. {
  8390. decl = make_decl_info(ctx.scope, ctx.decl);
  8391. decl->proc_lit = node;
  8392. ctx.decl = decl;
  8393. defer (ctx.decl = ctx.decl->parent);
  8394. if (pl->tags != 0) {
  8395. error(node, "A procedure literal cannot have tags");
  8396. pl->tags = 0; // TODO(bill): Should I zero this?!
  8397. }
  8398. check_procedure_type(&ctx, type, pl->type);
  8399. if (!is_type_proc(type)) {
  8400. gbString str = expr_to_string(node);
  8401. error(node, "Invalid procedure literal '%s'", str);
  8402. gb_string_free(str);
  8403. check_close_scope(&ctx);
  8404. return kind;
  8405. }
  8406. if (pl->body == nullptr) {
  8407. error(node, "A procedure literal must have a body");
  8408. return kind;
  8409. }
  8410. pl->decl = decl;
  8411. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  8412. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  8413. array_add(&ctx.checker->nested_proc_lits, decl);
  8414. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  8415. }
  8416. check_close_scope(&ctx);
  8417. o->mode = Addressing_Value;
  8418. o->type = type;
  8419. case_end;
  8420. case_ast_node(te, TernaryIfExpr, node);
  8421. kind = check_ternary_if_expr(c, o, node, type_hint);
  8422. case_end;
  8423. case_ast_node(te, TernaryWhenExpr, node);
  8424. kind = check_ternary_when_expr(c, o, node, type_hint);
  8425. case_end;
  8426. case_ast_node(oe, OrElseExpr, node);
  8427. return check_or_else_expr(c, o, node, type_hint);
  8428. case_end;
  8429. case_ast_node(re, OrReturnExpr, node);
  8430. return check_or_return_expr(c, o, node, type_hint);
  8431. case_end;
  8432. case_ast_node(cl, CompoundLit, node);
  8433. kind = check_compound_literal(c, o, node, type_hint);
  8434. case_end;
  8435. case_ast_node(pe, ParenExpr, node);
  8436. kind = check_expr_base(c, o, pe->expr, type_hint);
  8437. node->viral_state_flags |= pe->expr->viral_state_flags;
  8438. o->expr = node;
  8439. case_end;
  8440. case_ast_node(te, TagExpr, node);
  8441. String name = te->name.string;
  8442. error(node, "Unknown tag expression, #%.*s", LIT(name));
  8443. if (te->expr) {
  8444. kind = check_expr_base(c, o, te->expr, type_hint);
  8445. node->viral_state_flags |= te->expr->viral_state_flags;
  8446. }
  8447. o->expr = node;
  8448. case_end;
  8449. case_ast_node(ta, TypeAssertion, node);
  8450. kind = check_type_assertion(c, o, node, type_hint);
  8451. case_end;
  8452. case_ast_node(tc, TypeCast, node);
  8453. check_expr_or_type(c, o, tc->type);
  8454. if (o->mode != Addressing_Type) {
  8455. gbString str = expr_to_string(tc->type);
  8456. error(tc->type, "Expected a type, got %s", str);
  8457. gb_string_free(str);
  8458. o->mode = Addressing_Invalid;
  8459. }
  8460. if (o->mode == Addressing_Invalid) {
  8461. o->expr = node;
  8462. return kind;
  8463. }
  8464. Type *type = o->type;
  8465. check_expr_base(c, o, tc->expr, type);
  8466. node->viral_state_flags |= tc->expr->viral_state_flags;
  8467. if (o->mode != Addressing_Invalid) {
  8468. switch (tc->token.kind) {
  8469. case Token_transmute:
  8470. check_transmute(c, node, o, type);
  8471. break;
  8472. case Token_cast:
  8473. check_cast(c, o, type);
  8474. break;
  8475. default:
  8476. error(node, "Invalid AST: Invalid casting expression");
  8477. o->mode = Addressing_Invalid;
  8478. break;
  8479. }
  8480. }
  8481. return Expr_Expr;
  8482. case_end;
  8483. case_ast_node(ac, AutoCast, node);
  8484. check_expr_base(c, o, ac->expr, type_hint);
  8485. node->viral_state_flags |= ac->expr->viral_state_flags;
  8486. if (o->mode == Addressing_Invalid) {
  8487. o->expr = node;
  8488. return kind;
  8489. }
  8490. if (type_hint) {
  8491. Type *type = type_of_expr(ac->expr);
  8492. check_cast(c, o, type_hint);
  8493. if (is_type_typed(type) && are_types_identical(type, type_hint)) {
  8494. if (build_context.vet_extra) {
  8495. error(node, "Redundant 'auto_cast' applied to expression");
  8496. }
  8497. }
  8498. }
  8499. o->expr = node;
  8500. return Expr_Expr;
  8501. case_end;
  8502. case_ast_node(ue, UnaryExpr, node);
  8503. Type *th = type_hint;
  8504. if (ue->op.kind == Token_And) {
  8505. th = type_deref(th);
  8506. }
  8507. check_expr_base(c, o, ue->expr, th);
  8508. node->viral_state_flags |= ue->expr->viral_state_flags;
  8509. if (o->mode != Addressing_Invalid) {
  8510. check_unary_expr(c, o, ue->op, node);
  8511. }
  8512. o->expr = node;
  8513. return Expr_Expr;
  8514. case_end;
  8515. case_ast_node(be, BinaryExpr, node);
  8516. check_binary_expr(c, o, node, type_hint, true);
  8517. if (o->mode == Addressing_Invalid) {
  8518. o->expr = node;
  8519. return kind;
  8520. }
  8521. case_end;
  8522. case_ast_node(se, SelectorExpr, node);
  8523. check_selector(c, o, node, type_hint);
  8524. node->viral_state_flags |= se->expr->viral_state_flags;
  8525. case_end;
  8526. case_ast_node(se, SelectorCallExpr, node);
  8527. return check_selector_call_expr(c, o, node, type_hint);
  8528. case_end;
  8529. case_ast_node(ise, ImplicitSelectorExpr, node);
  8530. return check_implicit_selector_expr(c, o, node, type_hint);
  8531. case_end;
  8532. case_ast_node(ie, IndexExpr, node);
  8533. kind = check_index_expr(c, o, node, type_hint);
  8534. case_end;
  8535. case_ast_node(se, SliceExpr, node);
  8536. kind = check_slice_expr(c, o, node, type_hint);
  8537. case_end;
  8538. case_ast_node(mie, MatrixIndexExpr, node);
  8539. check_matrix_index_expr(c, o, node, type_hint);
  8540. o->expr = node;
  8541. return Expr_Expr;
  8542. case_end;
  8543. case_ast_node(ce, CallExpr, node);
  8544. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  8545. case_end;
  8546. case_ast_node(de, DerefExpr, node);
  8547. check_expr_or_type(c, o, de->expr);
  8548. node->viral_state_flags |= de->expr->viral_state_flags;
  8549. if (o->mode == Addressing_Invalid) {
  8550. o->mode = Addressing_Invalid;
  8551. o->expr = node;
  8552. return kind;
  8553. } else {
  8554. Type *t = base_type(o->type);
  8555. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  8556. o->mode = Addressing_Variable;
  8557. o->type = t->Pointer.elem;
  8558. } else if (t->kind == Type_SoaPointer) {
  8559. o->mode = Addressing_SoaVariable;
  8560. o->type = type_deref(t);
  8561. } else if (t->kind == Type_RelativePointer) {
  8562. if (o->mode != Addressing_Variable) {
  8563. gbString str = expr_to_string(o->expr);
  8564. gbString typ = type_to_string(o->type);
  8565. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  8566. gb_string_free(typ);
  8567. gb_string_free(str);
  8568. }
  8569. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  8570. add_type_info_type(c, o->type);
  8571. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  8572. GB_ASSERT(ptr_type->kind == Type_Pointer);
  8573. o->mode = Addressing_Variable;
  8574. o->type = ptr_type->Pointer.elem;
  8575. } else {
  8576. gbString str = expr_to_string(o->expr);
  8577. gbString typ = type_to_string(o->type);
  8578. begin_error_block();
  8579. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  8580. if (o->type && is_type_multi_pointer(o->type)) {
  8581. error_line("\tDid you mean '%s[0]'?\n", str);
  8582. }
  8583. end_error_block();
  8584. gb_string_free(typ);
  8585. gb_string_free(str);
  8586. o->mode = Addressing_Invalid;
  8587. o->expr = node;
  8588. return kind;
  8589. }
  8590. }
  8591. case_end;
  8592. case_ast_node(ia, InlineAsmExpr, node);
  8593. if (c->curr_proc_decl == nullptr) {
  8594. error(node, "Inline asm expressions are only allowed within a procedure body");
  8595. }
  8596. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  8597. Type *return_type = nullptr;
  8598. for_array(i, ia->param_types) {
  8599. param_types[i] = check_type(c, ia->param_types[i]);
  8600. }
  8601. if (ia->return_type != nullptr) {
  8602. return_type = check_type(c, ia->return_type);
  8603. }
  8604. Operand x = {};
  8605. check_expr(c, &x, ia->asm_string);
  8606. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8607. error(x.expr, "Expected a constant string for the inline asm main parameter");
  8608. }
  8609. check_expr(c, &x, ia->constraints_string);
  8610. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8611. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  8612. }
  8613. Scope *scope = create_scope(c->info, c->scope);
  8614. scope->flags |= ScopeFlag_Proc;
  8615. Type *params = alloc_type_tuple();
  8616. Type *results = alloc_type_tuple();
  8617. if (param_types.count != 0) {
  8618. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  8619. for_array(i, param_types) {
  8620. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  8621. }
  8622. }
  8623. if (return_type != nullptr) {
  8624. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  8625. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  8626. }
  8627. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  8628. o->type = pt;
  8629. o->mode = Addressing_Value;
  8630. o->expr = node;
  8631. return Expr_Expr;
  8632. case_end;
  8633. case Ast_TypeidType:
  8634. case Ast_PolyType:
  8635. case Ast_ProcType:
  8636. case Ast_PointerType:
  8637. case Ast_MultiPointerType:
  8638. case Ast_ArrayType:
  8639. case Ast_DynamicArrayType:
  8640. case Ast_StructType:
  8641. case Ast_UnionType:
  8642. case Ast_EnumType:
  8643. case Ast_MapType:
  8644. case Ast_BitSetType:
  8645. case Ast_MatrixType:
  8646. case Ast_RelativeType:
  8647. o->mode = Addressing_Type;
  8648. o->type = check_type(c, node);
  8649. break;
  8650. }
  8651. kind = Expr_Expr;
  8652. o->expr = node;
  8653. return kind;
  8654. }
  8655. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8656. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  8657. if (o->type != nullptr && core_type(o->type) == nullptr) {
  8658. o->type = t_invalid;
  8659. gbString xs = expr_to_string(o->expr);
  8660. if (o->mode == Addressing_Type) {
  8661. error(o->expr, "Invalid type usage '%s'", xs);
  8662. } else {
  8663. error(o->expr, "Invalid expression '%s'", xs);
  8664. }
  8665. gb_string_free(xs);
  8666. }
  8667. if (o->type != nullptr && is_type_untyped(o->type)) {
  8668. add_untyped(c, node, o->mode, o->type, o->value);
  8669. }
  8670. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  8671. add_type_and_value(c, node, o->mode, o->type, o->value);
  8672. return kind;
  8673. }
  8674. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  8675. check_expr_base(c, o, e, nullptr);
  8676. switch (o->mode) {
  8677. default:
  8678. return; // NOTE(bill): Valid
  8679. case Addressing_NoValue:
  8680. error_operand_no_value(o);
  8681. break;
  8682. }
  8683. o->mode = Addressing_Invalid;
  8684. }
  8685. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  8686. check_expr_base(c, o, e, nullptr);
  8687. switch (o->mode) {
  8688. default:
  8689. return; // NOTE(bill): Valid
  8690. case Addressing_NoValue:
  8691. error_operand_no_value(o);
  8692. break;
  8693. case Addressing_Type:
  8694. error_operand_not_expression(o);
  8695. break;
  8696. }
  8697. o->mode = Addressing_Invalid;
  8698. }
  8699. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  8700. check_expr_base(c, o, e, type_hint);
  8701. switch (o->mode) {
  8702. default:
  8703. return; // NOTE(bill): Valid
  8704. case Addressing_NoValue:
  8705. error_operand_no_value(o);
  8706. break;
  8707. case Addressing_Type:
  8708. error_operand_not_expression(o);
  8709. break;
  8710. }
  8711. o->mode = Addressing_Invalid;
  8712. }
  8713. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  8714. if (o->mode == Addressing_Value) {
  8715. // NOTE(bill): Tuples are not first class thus never named
  8716. if (o->type->kind == Type_Tuple) {
  8717. isize count = o->type->Tuple.variables.count;
  8718. error(o->expr,
  8719. "%td-valued expression found where single value expected", count);
  8720. o->mode = Addressing_Invalid;
  8721. GB_ASSERT(count != 1);
  8722. }
  8723. }
  8724. }
  8725. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  8726. check_multi_expr(c, o, e);
  8727. check_not_tuple(c, o);
  8728. }
  8729. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  8730. check_expr_base(c, o, e, type_hint);
  8731. check_not_tuple(c, o);
  8732. error_operand_no_value(o);
  8733. }
  8734. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  8735. switch (v.kind) {
  8736. case ExactValue_Invalid:
  8737. return true;
  8738. case ExactValue_Bool:
  8739. return !v.value_bool;
  8740. case ExactValue_String:
  8741. return v.value_string.len == 0;
  8742. case ExactValue_Integer:
  8743. return big_int_is_zero(&v.value_integer);
  8744. case ExactValue_Float:
  8745. return v.value_float == 0.0;
  8746. case ExactValue_Complex:
  8747. if (v.value_complex) {
  8748. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  8749. }
  8750. return true;
  8751. case ExactValue_Quaternion:
  8752. if (v.value_quaternion) {
  8753. return v.value_quaternion->real == 0.0 &&
  8754. v.value_quaternion->imag == 0.0 &&
  8755. v.value_quaternion->jmag == 0.0 &&
  8756. v.value_quaternion->kmag == 0.0;
  8757. }
  8758. return true;
  8759. case ExactValue_Pointer:
  8760. return v.value_pointer == 0;
  8761. case ExactValue_Compound:
  8762. if (v.value_compound == nullptr) {
  8763. return true;
  8764. } else {
  8765. ast_node(cl, CompoundLit, v.value_compound);
  8766. if (cl->elems.count == 0) {
  8767. return true;
  8768. } else {
  8769. for (Ast *elem : cl->elems) {
  8770. if (elem->tav.mode != Addressing_Constant) {
  8771. return false;
  8772. }
  8773. if (!is_exact_value_zero(elem->tav.value)) {
  8774. return false;
  8775. }
  8776. }
  8777. return true;
  8778. }
  8779. }
  8780. case ExactValue_Procedure:
  8781. return v.value_procedure == nullptr;
  8782. case ExactValue_Typeid:
  8783. return v.value_typeid == nullptr;
  8784. }
  8785. return true;
  8786. }
  8787. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  8788. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  8789. for_array(i, params) {
  8790. if (i > 0) {
  8791. str = gb_string_appendc(str, ", ");
  8792. }
  8793. str = write_expr_to_string(str, params[i], false);
  8794. }
  8795. return str;
  8796. }
  8797. gb_internal gbString string_append_string(gbString str, String string) {
  8798. if (string.len > 0) {
  8799. return gb_string_append_length(str, &string[0], string.len);
  8800. }
  8801. return str;
  8802. }
  8803. gb_internal gbString string_append_token(gbString str, Token token) {
  8804. str = string_append_string(str, token.string);
  8805. return str;
  8806. }
  8807. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  8808. if (node == nullptr)
  8809. return str;
  8810. if (is_ast_stmt(node)) {
  8811. GB_ASSERT("stmt passed to write_expr_to_string");
  8812. }
  8813. switch (node->kind) {
  8814. default:
  8815. str = gb_string_appendc(str, "(BadExpr)");
  8816. break;
  8817. case_ast_node(i, Ident, node);
  8818. str = string_append_token(str, i->token);
  8819. case_end;
  8820. case_ast_node(i, Implicit, node);
  8821. str = string_append_token(str, *i);
  8822. case_end;
  8823. case_ast_node(bl, BasicLit, node);
  8824. str = string_append_token(str, bl->token);
  8825. case_end;
  8826. case_ast_node(bd, BasicDirective, node);
  8827. str = gb_string_append_rune(str, '#');
  8828. str = string_append_string(str, bd->name.string);
  8829. case_end;
  8830. case_ast_node(ud, Undef, node);
  8831. str = gb_string_appendc(str, "---");
  8832. case_end;
  8833. case_ast_node(pg, ProcGroup, node);
  8834. str = gb_string_appendc(str, "proc{");
  8835. for_array(i, pg->args) {
  8836. if (i > 0) str = gb_string_appendc(str, ", ");
  8837. str = write_expr_to_string(str, pg->args[i], shorthand);
  8838. }
  8839. str = gb_string_append_rune(str, '}');
  8840. case_end;
  8841. case_ast_node(pl, ProcLit, node);
  8842. str = write_expr_to_string(str, pl->type, shorthand);
  8843. if (pl->body) {
  8844. str = gb_string_appendc(str, " {...}");
  8845. } else {
  8846. str = gb_string_appendc(str, " ---");
  8847. }
  8848. case_end;
  8849. case_ast_node(cl, CompoundLit, node);
  8850. str = write_expr_to_string(str, cl->type, shorthand);
  8851. str = gb_string_append_rune(str, '{');
  8852. if (shorthand) {
  8853. str = gb_string_appendc(str, "...");
  8854. } else {
  8855. for_array(i, cl->elems) {
  8856. if (i > 0) str = gb_string_appendc(str, ", ");
  8857. str = write_expr_to_string(str, cl->elems[i], shorthand);
  8858. }
  8859. }
  8860. str = gb_string_append_rune(str, '}');
  8861. case_end;
  8862. case_ast_node(te, TagExpr, node);
  8863. str = gb_string_append_rune(str, '#');
  8864. str = string_append_token(str, te->name);
  8865. str = write_expr_to_string(str, te->expr, shorthand);
  8866. case_end;
  8867. case_ast_node(ue, UnaryExpr, node);
  8868. str = string_append_token(str, ue->op);
  8869. str = write_expr_to_string(str, ue->expr, shorthand);
  8870. case_end;
  8871. case_ast_node(de, DerefExpr, node);
  8872. str = write_expr_to_string(str, de->expr, shorthand);
  8873. str = gb_string_append_rune(str, '^');
  8874. case_end;
  8875. case_ast_node(be, BinaryExpr, node);
  8876. str = write_expr_to_string(str, be->left, shorthand);
  8877. str = gb_string_append_rune(str, ' ');
  8878. str = string_append_token(str, be->op);
  8879. str = gb_string_append_rune(str, ' ');
  8880. str = write_expr_to_string(str, be->right, shorthand);
  8881. case_end;
  8882. case_ast_node(te, TernaryIfExpr, node);
  8883. TokenPos x = ast_token(te->x).pos;
  8884. TokenPos cond = ast_token(te->cond).pos;
  8885. if (x < cond) {
  8886. str = write_expr_to_string(str, te->x, shorthand);
  8887. str = gb_string_appendc(str, " if ");
  8888. str = write_expr_to_string(str, te->cond, shorthand);
  8889. str = gb_string_appendc(str, " else ");
  8890. str = write_expr_to_string(str, te->y, shorthand);
  8891. } else {
  8892. str = write_expr_to_string(str, te->cond, shorthand);
  8893. str = gb_string_appendc(str, " ? ");
  8894. str = write_expr_to_string(str, te->x, shorthand);
  8895. str = gb_string_appendc(str, " : ");
  8896. str = write_expr_to_string(str, te->y, shorthand);
  8897. }
  8898. case_end;
  8899. case_ast_node(te, TernaryWhenExpr, node);
  8900. str = write_expr_to_string(str, te->x, shorthand);
  8901. str = gb_string_appendc(str, " when ");
  8902. str = write_expr_to_string(str, te->cond, shorthand);
  8903. str = gb_string_appendc(str, " else ");
  8904. str = write_expr_to_string(str, te->y, shorthand);
  8905. case_end;
  8906. case_ast_node(oe, OrElseExpr, node);
  8907. str = write_expr_to_string(str, oe->x, shorthand);
  8908. str = gb_string_appendc(str, " or_else ");
  8909. str = write_expr_to_string(str, oe->y, shorthand);
  8910. case_end;
  8911. case_ast_node(oe, OrReturnExpr, node);
  8912. str = write_expr_to_string(str, oe->expr, shorthand);
  8913. str = gb_string_appendc(str, " or_return");
  8914. case_end;
  8915. case_ast_node(pe, ParenExpr, node);
  8916. str = gb_string_append_rune(str, '(');
  8917. str = write_expr_to_string(str, pe->expr, shorthand);
  8918. str = gb_string_append_rune(str, ')');
  8919. case_end;
  8920. case_ast_node(se, SelectorExpr, node);
  8921. str = write_expr_to_string(str, se->expr, shorthand);
  8922. str = string_append_token(str, se->token);
  8923. str = write_expr_to_string(str, se->selector, shorthand);
  8924. case_end;
  8925. case_ast_node(se, ImplicitSelectorExpr, node);
  8926. str = gb_string_append_rune(str, '.');
  8927. str = write_expr_to_string(str, se->selector, shorthand);
  8928. case_end;
  8929. case_ast_node(se, SelectorCallExpr, node);
  8930. str = write_expr_to_string(str, se->expr, shorthand);
  8931. str = gb_string_appendc(str, "(");
  8932. ast_node(ce, CallExpr, se->call);
  8933. isize start = se->modified_call ? 1 : 0;
  8934. for (isize i = start; i < ce->args.count; i++) {
  8935. Ast *arg = ce->args[i];
  8936. if (i > start) {
  8937. str = gb_string_appendc(str, ", ");
  8938. }
  8939. str = write_expr_to_string(str, arg, shorthand);
  8940. }
  8941. str = gb_string_appendc(str, ")");
  8942. case_end;
  8943. case_ast_node(ta, TypeAssertion, node);
  8944. str = write_expr_to_string(str, ta->expr, shorthand);
  8945. if (ta->type != nullptr &&
  8946. ta->type->kind == Ast_UnaryExpr &&
  8947. ta->type->UnaryExpr.op.kind == Token_Question) {
  8948. str = gb_string_appendc(str, ".?");
  8949. } else {
  8950. str = gb_string_appendc(str, ".(");
  8951. str = write_expr_to_string(str, ta->type, shorthand);
  8952. str = gb_string_append_rune(str, ')');
  8953. }
  8954. case_end;
  8955. case_ast_node(tc, TypeCast, node);
  8956. str = string_append_token(str, tc->token);
  8957. str = gb_string_append_rune(str, '(');
  8958. str = write_expr_to_string(str, tc->type, shorthand);
  8959. str = gb_string_append_rune(str, ')');
  8960. str = write_expr_to_string(str, tc->expr, shorthand);
  8961. case_end;
  8962. case_ast_node(ac, AutoCast, node);
  8963. str = string_append_token(str, ac->token);
  8964. str = gb_string_append_rune(str, ' ');
  8965. str = write_expr_to_string(str, ac->expr, shorthand);
  8966. case_end;
  8967. case_ast_node(ie, IndexExpr, node);
  8968. str = write_expr_to_string(str, ie->expr, shorthand);
  8969. str = gb_string_append_rune(str, '[');
  8970. str = write_expr_to_string(str, ie->index, shorthand);
  8971. str = gb_string_append_rune(str, ']');
  8972. case_end;
  8973. case_ast_node(se, SliceExpr, node);
  8974. str = write_expr_to_string(str, se->expr, shorthand);
  8975. str = gb_string_append_rune(str, '[');
  8976. str = write_expr_to_string(str, se->low, shorthand);
  8977. str = string_append_token(str, se->interval);
  8978. str = write_expr_to_string(str, se->high, shorthand);
  8979. str = gb_string_append_rune(str, ']');
  8980. case_end;
  8981. case_ast_node(mie, MatrixIndexExpr, node);
  8982. str = write_expr_to_string(str, mie->expr, shorthand);
  8983. str = gb_string_append_rune(str, '[');
  8984. str = write_expr_to_string(str, mie->row_index, shorthand);
  8985. str = gb_string_appendc(str, ", ");
  8986. str = write_expr_to_string(str, mie->column_index, shorthand);
  8987. str = gb_string_append_rune(str, ']');
  8988. case_end;
  8989. case_ast_node(e, Ellipsis, node);
  8990. str = gb_string_appendc(str, "..");
  8991. str = write_expr_to_string(str, e->expr, shorthand);
  8992. case_end;
  8993. case_ast_node(fv, FieldValue, node);
  8994. str = write_expr_to_string(str, fv->field, shorthand);
  8995. str = gb_string_appendc(str, " = ");
  8996. str = write_expr_to_string(str, fv->value, shorthand);
  8997. case_end;
  8998. case_ast_node(fv, EnumFieldValue, node);
  8999. str = write_expr_to_string(str, fv->name, shorthand);
  9000. if (fv->value) {
  9001. str = gb_string_appendc(str, " = ");
  9002. str = write_expr_to_string(str, fv->value, shorthand);
  9003. }
  9004. case_end;
  9005. case_ast_node(ht, HelperType, node);
  9006. str = gb_string_appendc(str, "#type ");
  9007. str = write_expr_to_string(str, ht->type, shorthand);
  9008. case_end;
  9009. case_ast_node(ht, DistinctType, node);
  9010. str = gb_string_appendc(str, "distinct ");
  9011. str = write_expr_to_string(str, ht->type, shorthand);
  9012. case_end;
  9013. case_ast_node(pt, PolyType, node);
  9014. str = gb_string_append_rune(str, '$');
  9015. str = write_expr_to_string(str, pt->type, shorthand);
  9016. if (pt->specialization != nullptr) {
  9017. str = gb_string_append_rune(str, '/');
  9018. str = write_expr_to_string(str, pt->specialization, shorthand);
  9019. }
  9020. case_end;
  9021. case_ast_node(pt, PointerType, node);
  9022. str = gb_string_append_rune(str, '^');
  9023. str = write_expr_to_string(str, pt->type, shorthand);
  9024. case_end;
  9025. case_ast_node(pt, MultiPointerType, node);
  9026. str = gb_string_appendc(str, "[^]");
  9027. str = write_expr_to_string(str, pt->type, shorthand);
  9028. case_end;
  9029. case_ast_node(at, ArrayType, node);
  9030. str = gb_string_append_rune(str, '[');
  9031. if (at->count != nullptr &&
  9032. at->count->kind == Ast_UnaryExpr &&
  9033. at->count->UnaryExpr.op.kind == Token_Question) {
  9034. str = gb_string_appendc(str, "?");
  9035. } else {
  9036. str = write_expr_to_string(str, at->count, shorthand);
  9037. }
  9038. str = gb_string_append_rune(str, ']');
  9039. str = write_expr_to_string(str, at->elem, shorthand);
  9040. case_end;
  9041. case_ast_node(at, DynamicArrayType, node);
  9042. str = gb_string_appendc(str, "[dynamic]");
  9043. str = write_expr_to_string(str, at->elem, shorthand);
  9044. case_end;
  9045. case_ast_node(bs, BitSetType, node);
  9046. str = gb_string_appendc(str, "bit_set[");
  9047. str = write_expr_to_string(str, bs->elem, shorthand);
  9048. str = gb_string_appendc(str, "]");
  9049. case_end;
  9050. case_ast_node(mt, MapType, node);
  9051. str = gb_string_appendc(str, "map[");
  9052. str = write_expr_to_string(str, mt->key, shorthand);
  9053. str = gb_string_append_rune(str, ']');
  9054. str = write_expr_to_string(str, mt->value, shorthand);
  9055. case_end;
  9056. case_ast_node(mt, MatrixType, node);
  9057. str = gb_string_appendc(str, "matrix[");
  9058. str = write_expr_to_string(str, mt->row_count, shorthand);
  9059. str = gb_string_appendc(str, ", ");
  9060. str = write_expr_to_string(str, mt->column_count, shorthand);
  9061. str = gb_string_append_rune(str, ']');
  9062. str = write_expr_to_string(str, mt->elem, shorthand);
  9063. case_end;
  9064. case_ast_node(f, Field, node);
  9065. if (f->flags&FieldFlag_using) {
  9066. str = gb_string_appendc(str, "using ");
  9067. }
  9068. if (f->flags&FieldFlag_no_alias) {
  9069. str = gb_string_appendc(str, "#no_alias ");
  9070. }
  9071. if (f->flags&FieldFlag_c_vararg) {
  9072. str = gb_string_appendc(str, "#c_vararg ");
  9073. }
  9074. if (f->flags&FieldFlag_any_int) {
  9075. str = gb_string_appendc(str, "#any_int ");
  9076. }
  9077. if (f->flags&FieldFlag_const) {
  9078. str = gb_string_appendc(str, "#const ");
  9079. }
  9080. if (f->flags&FieldFlag_subtype) {
  9081. str = gb_string_appendc(str, "#subtype ");
  9082. }
  9083. for_array(i, f->names) {
  9084. Ast *name = f->names[i];
  9085. if (i > 0) str = gb_string_appendc(str, ", ");
  9086. str = write_expr_to_string(str, name, shorthand);
  9087. }
  9088. if (f->names.count > 0) {
  9089. if (f->type == nullptr && f->default_value != nullptr) {
  9090. str = gb_string_append_rune(str, ' ');
  9091. }
  9092. str = gb_string_appendc(str, ":");
  9093. }
  9094. if (f->type != nullptr) {
  9095. str = gb_string_append_rune(str, ' ');
  9096. str = write_expr_to_string(str, f->type, shorthand);
  9097. }
  9098. if (f->default_value != nullptr) {
  9099. if (f->type != nullptr) {
  9100. str = gb_string_append_rune(str, ' ');
  9101. }
  9102. str = gb_string_appendc(str, "= ");
  9103. str = write_expr_to_string(str, f->default_value, shorthand);
  9104. }
  9105. case_end;
  9106. case_ast_node(f, FieldList, node);
  9107. bool has_name = false;
  9108. for_array(i, f->list) {
  9109. ast_node(field, Field, f->list[i]);
  9110. if (field->names.count > 1) {
  9111. has_name = true;
  9112. break;
  9113. }
  9114. if (field->names.count == 0) {
  9115. continue;
  9116. }
  9117. if (!is_blank_ident(field->names[0])) {
  9118. has_name = true;
  9119. break;
  9120. }
  9121. }
  9122. for_array(i, f->list) {
  9123. if (i > 0) str = gb_string_appendc(str, ", ");
  9124. if (has_name) {
  9125. str = write_expr_to_string(str, f->list[i], shorthand);
  9126. } else {
  9127. ast_node(field, Field, f->list[i]);
  9128. if (field->flags&FieldFlag_using) {
  9129. str = gb_string_appendc(str, "using ");
  9130. }
  9131. if (field->flags&FieldFlag_no_alias) {
  9132. str = gb_string_appendc(str, "#no_alias ");
  9133. }
  9134. if (field->flags&FieldFlag_c_vararg) {
  9135. str = gb_string_appendc(str, "#c_vararg ");
  9136. }
  9137. str = write_expr_to_string(str, field->type, shorthand);
  9138. }
  9139. }
  9140. case_end;
  9141. case_ast_node(ce, CallExpr, node);
  9142. switch (ce->inlining) {
  9143. case ProcInlining_inline:
  9144. str = gb_string_appendc(str, "#force_inline ");
  9145. break;
  9146. case ProcInlining_no_inline:
  9147. str = gb_string_appendc(str, "#force_no_inline ");
  9148. break;
  9149. }
  9150. str = write_expr_to_string(str, ce->proc, shorthand);
  9151. str = gb_string_appendc(str, "(");
  9152. isize idx0 = cast(isize)ce->was_selector;
  9153. for (isize i = idx0; i < ce->args.count; i++) {
  9154. Ast *arg = ce->args[i];
  9155. if (i > idx0) {
  9156. str = gb_string_appendc(str, ", ");
  9157. }
  9158. str = write_expr_to_string(str, arg, shorthand);
  9159. }
  9160. str = gb_string_appendc(str, ")");
  9161. case_end;
  9162. case_ast_node(tt, TypeidType, node);
  9163. str = gb_string_appendc(str, "typeid");
  9164. if (tt->specialization) {
  9165. str = gb_string_appendc(str, "/");
  9166. str = write_expr_to_string(str, tt->specialization, shorthand);
  9167. }
  9168. case_end;
  9169. case_ast_node(pt, ProcType, node);
  9170. str = gb_string_appendc(str, "proc(");
  9171. str = write_expr_to_string(str, pt->params, shorthand);
  9172. str = gb_string_appendc(str, ")");
  9173. if (pt->results != nullptr) {
  9174. str = gb_string_appendc(str, " -> ");
  9175. bool parens_needed = false;
  9176. if (pt->results && pt->results->kind == Ast_FieldList) {
  9177. for (Ast *field : pt->results->FieldList.list) {
  9178. ast_node(f, Field, field);
  9179. if (f->names.count != 0) {
  9180. parens_needed = true;
  9181. break;
  9182. }
  9183. }
  9184. }
  9185. if (parens_needed) {
  9186. str = gb_string_append_rune(str, '(');
  9187. }
  9188. str = write_expr_to_string(str, pt->results, shorthand);
  9189. if (parens_needed) {
  9190. str = gb_string_append_rune(str, ')');
  9191. }
  9192. }
  9193. case_end;
  9194. case_ast_node(st, StructType, node);
  9195. str = gb_string_appendc(str, "struct ");
  9196. if (st->polymorphic_params) {
  9197. str = gb_string_append_rune(str, '(');
  9198. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9199. str = gb_string_appendc(str, ") ");
  9200. }
  9201. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9202. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9203. if (st->align) {
  9204. str = gb_string_appendc(str, "#align ");
  9205. str = write_expr_to_string(str, st->align, shorthand);
  9206. str = gb_string_append_rune(str, ' ');
  9207. }
  9208. str = gb_string_append_rune(str, '{');
  9209. if (shorthand) {
  9210. str = gb_string_appendc(str, "...");
  9211. } else {
  9212. str = write_struct_fields_to_string(str, st->fields);
  9213. }
  9214. str = gb_string_append_rune(str, '}');
  9215. case_end;
  9216. case_ast_node(st, UnionType, node);
  9217. str = gb_string_appendc(str, "union ");
  9218. if (st->polymorphic_params) {
  9219. str = gb_string_append_rune(str, '(');
  9220. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9221. str = gb_string_appendc(str, ") ");
  9222. }
  9223. switch (st->kind) {
  9224. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9225. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9226. }
  9227. if (st->align) {
  9228. str = gb_string_appendc(str, "#align ");
  9229. str = write_expr_to_string(str, st->align, shorthand);
  9230. str = gb_string_append_rune(str, ' ');
  9231. }
  9232. str = gb_string_append_rune(str, '{');
  9233. if (shorthand) {
  9234. str = gb_string_appendc(str, "...");
  9235. } else {
  9236. str = write_struct_fields_to_string(str, st->variants);
  9237. }
  9238. str = gb_string_append_rune(str, '}');
  9239. case_end;
  9240. case_ast_node(et, EnumType, node);
  9241. str = gb_string_appendc(str, "enum ");
  9242. if (et->base_type != nullptr) {
  9243. str = write_expr_to_string(str, et->base_type, shorthand);
  9244. str = gb_string_append_rune(str, ' ');
  9245. }
  9246. str = gb_string_append_rune(str, '{');
  9247. if (shorthand) {
  9248. str = gb_string_appendc(str, "...");
  9249. } else {
  9250. for_array(i, et->fields) {
  9251. if (i > 0) {
  9252. str = gb_string_appendc(str, ", ");
  9253. }
  9254. str = write_expr_to_string(str, et->fields[i], shorthand);
  9255. }
  9256. }
  9257. str = gb_string_append_rune(str, '}');
  9258. case_end;
  9259. case_ast_node(rt, RelativeType, node);
  9260. str = write_expr_to_string(str, rt->tag, shorthand);
  9261. str = gb_string_appendc(str, "" );
  9262. str = write_expr_to_string(str, rt->type, shorthand);
  9263. case_end;
  9264. case_ast_node(ia, InlineAsmExpr, node);
  9265. str = gb_string_appendc(str, "asm(");
  9266. for_array(i, ia->param_types) {
  9267. if (i > 0) {
  9268. str = gb_string_appendc(str, ", ");
  9269. }
  9270. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9271. }
  9272. str = gb_string_appendc(str, ")");
  9273. if (ia->return_type != nullptr) {
  9274. str = gb_string_appendc(str, " -> ");
  9275. str = write_expr_to_string(str, ia->return_type, shorthand);
  9276. }
  9277. if (ia->has_side_effects) {
  9278. str = gb_string_appendc(str, " #side_effects");
  9279. }
  9280. if (ia->is_align_stack) {
  9281. str = gb_string_appendc(str, " #stack_align");
  9282. }
  9283. if (ia->dialect) {
  9284. str = gb_string_appendc(str, " #");
  9285. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9286. }
  9287. str = gb_string_appendc(str, " {");
  9288. if (shorthand) {
  9289. str = gb_string_appendc(str, "...");
  9290. } else {
  9291. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9292. str = gb_string_appendc(str, ", ");
  9293. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9294. }
  9295. str = gb_string_appendc(str, "}");
  9296. case_end;
  9297. }
  9298. return str;
  9299. }
  9300. gb_internal gbString expr_to_string(Ast *expression) {
  9301. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9302. }
  9303. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  9304. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  9305. }
  9306. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  9307. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9308. }