check_expr.cpp 299 KB

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