check_expr.cpp 363 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  73. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gb_internal gbString expr_to_string (Ast *expression);
  75. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  76. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. gb_internal bool check_is_terminating (Ast *node, String const &label);
  78. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  84. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  89. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  90. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  91. gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
  96. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  97. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  98. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  99. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal bool is_diverging_expr(Ast *expr);
  101. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  102. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  103. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  104. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  105. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y);
  106. gb_internal bool is_exact_value_zero(ExactValue const &v);
  107. enum LoadDirectiveResult {
  108. LoadDirective_Success = 0,
  109. LoadDirective_Error = 1,
  110. LoadDirective_NotFound = 2,
  111. };
  112. gb_internal bool is_load_directive_call(Ast *call) {
  113. call = unparen_expr(call);
  114. if (call->kind != Ast_CallExpr) {
  115. return false;
  116. }
  117. ast_node(ce, CallExpr, call);
  118. if (ce->proc->kind != Ast_BasicDirective) {
  119. return false;
  120. }
  121. ast_node(bd, BasicDirective, ce->proc);
  122. String name = bd->name.string;
  123. return name == "load";
  124. }
  125. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  126. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  127. auto results = did_you_mean_results(d);
  128. if (results.count != 0) {
  129. error_line("\tSuggestion: Did you mean?\n");
  130. for (auto const &result : results) {
  131. String const &target = result.target;
  132. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  133. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  134. }
  135. }
  136. }
  137. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  138. if (e->kind != Entity_TypeName) {
  139. return;
  140. }
  141. if (e->TypeName.objc_metadata == nullptr) {
  142. return;
  143. }
  144. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  145. Type *t = base_type(e->type);
  146. GB_ASSERT(t->kind == Type_Struct);
  147. if (is_type) {
  148. for (auto const &entry : objc_metadata->type_entries) {
  149. string_set_add(set, entry.name);
  150. }
  151. } else {
  152. for (auto const &entry : objc_metadata->value_entries) {
  153. string_set_add(set, entry.name);
  154. }
  155. }
  156. for (Entity *f : t->Struct.fields) {
  157. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  158. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  159. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  160. }
  161. }
  162. }
  163. }
  164. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  165. if (build_context.terse_errors) { return; }
  166. ERROR_BLOCK();
  167. GB_ASSERT(e->kind == Entity_TypeName);
  168. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  169. auto *objc_metadata = e->TypeName.objc_metadata;
  170. MUTEX_GUARD(objc_metadata->mutex);
  171. StringSet set = {};
  172. defer (string_set_destroy(&set));
  173. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  174. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  175. defer (did_you_mean_destroy(&d));
  176. for (String const &target : set) {
  177. did_you_mean_append(&d, target);
  178. }
  179. check_did_you_mean_print(&d, prefix);
  180. }
  181. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  182. if (build_context.terse_errors) { return; }
  183. ERROR_BLOCK();
  184. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  185. defer (did_you_mean_destroy(&d));
  186. for (Entity *e : fields) {
  187. did_you_mean_append(&d, e->token.string);
  188. }
  189. check_did_you_mean_print(&d, prefix);
  190. }
  191. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  192. if (build_context.terse_errors) { return; }
  193. ERROR_BLOCK();
  194. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  195. defer (did_you_mean_destroy(&d));
  196. for (Entity *e : fields) {
  197. did_you_mean_append(&d, e->token.string);
  198. }
  199. check_did_you_mean_print(&d, prefix);
  200. }
  201. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  202. if (build_context.terse_errors) { return; }
  203. ERROR_BLOCK();
  204. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  205. defer (did_you_mean_destroy(&d));
  206. rw_mutex_shared_lock(&scope->mutex);
  207. for (auto const &entry : scope->elements) {
  208. Entity *e = entry.value;
  209. did_you_mean_append(&d, e->token.string);
  210. }
  211. rw_mutex_shared_unlock(&scope->mutex);
  212. check_did_you_mean_print(&d, prefix);
  213. }
  214. gb_internal Entity *entity_from_expr(Ast *expr) {
  215. expr = unparen_expr(expr);
  216. if (expr == nullptr) {
  217. return nullptr;
  218. }
  219. switch (expr->kind) {
  220. case Ast_Ident:
  221. return expr->Ident.entity;
  222. case Ast_SelectorExpr:
  223. return entity_from_expr(expr->SelectorExpr.selector);
  224. }
  225. return nullptr;
  226. }
  227. gb_internal void error_operand_not_expression(Operand *o) {
  228. if (o->mode == Addressing_Type) {
  229. gbString err = expr_to_string(o->expr);
  230. error(o->expr, "'%s' is not an expression but a type", err);
  231. gb_string_free(err);
  232. o->mode = Addressing_Invalid;
  233. }
  234. }
  235. gb_internal void error_operand_no_value(Operand *o) {
  236. if (o->mode == Addressing_NoValue) {
  237. Ast *x = unparen_expr(o->expr);
  238. if (x != nullptr && x->kind == Ast_CallExpr) {
  239. Ast *p = unparen_expr(x->CallExpr.proc);
  240. if (p->kind == Ast_BasicDirective) {
  241. String tag = p->BasicDirective.name.string;
  242. if (tag == "panic" ||
  243. tag == "assert") {
  244. return;
  245. }
  246. }
  247. }
  248. gbString err = expr_to_string(o->expr);
  249. if (x != nullptr && x->kind == Ast_CallExpr) {
  250. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  251. } else {
  252. error(o->expr, "'%s' used as a value", err);
  253. }
  254. gb_string_free(err);
  255. o->mode = Addressing_Invalid;
  256. }
  257. }
  258. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  259. if (build_context.dynamic_map_calls) {
  260. add_package_dependency(c, "runtime", "__dynamic_map_get");
  261. } else {
  262. add_package_dependency(c, "runtime", "map_desired_position");
  263. add_package_dependency(c, "runtime", "map_probe_distance");
  264. }
  265. }
  266. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  267. init_core_source_code_location(c->checker);
  268. if (t_map_set_proc == nullptr) {
  269. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  270. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  271. }
  272. if (build_context.dynamic_map_calls) {
  273. add_package_dependency(c, "runtime", "__dynamic_map_set");
  274. } else {
  275. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  276. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  277. }
  278. }
  279. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  280. init_core_source_code_location(c->checker);
  281. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  282. }
  283. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  284. Scope *s = c->scope;
  285. check_collect_entities(c, nodes);
  286. for (auto const &entry : s->elements) {
  287. Entity *e = entry.value;\
  288. switch (e->kind) {
  289. case Entity_Constant:
  290. case Entity_TypeName:
  291. case Entity_Procedure:
  292. break;
  293. default:
  294. continue;
  295. }
  296. DeclInfo *d = decl_info_of_entity(e);
  297. if (d != nullptr) {
  298. check_entity_decl(c, e, d, nullptr);
  299. }
  300. }
  301. }
  302. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  303. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  304. ///////////////////////////////////////////////////////////////////////////////
  305. // //
  306. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  307. // //
  308. ///////////////////////////////////////////////////////////////////////////////
  309. CheckerInfo *info = old_c->info;
  310. if (base_entity == nullptr) {
  311. return false;
  312. }
  313. if (!is_type_proc(base_entity->type)) {
  314. return false;
  315. }
  316. if (base_entity->flags & EntityFlag_Disabled) {
  317. return false;
  318. }
  319. String name = base_entity->token.string;
  320. Type *src = base_type(base_entity->type);
  321. Type *dst = nullptr;
  322. if (type != nullptr) {
  323. dst = base_type(type);
  324. }
  325. if (param_operands == nullptr) {
  326. GB_ASSERT(dst != nullptr);
  327. }
  328. if (param_operands != nullptr) {
  329. GB_ASSERT(dst == nullptr);
  330. }
  331. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  332. return false;
  333. }
  334. if (dst != nullptr) {
  335. if (dst->Proc.is_polymorphic) {
  336. return false;
  337. }
  338. if (dst->Proc.param_count != src->Proc.param_count ||
  339. dst->Proc.result_count != src->Proc.result_count) {
  340. return false;
  341. }
  342. }
  343. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  344. if (old_decl == nullptr) {
  345. return false;
  346. }
  347. gbAllocator a = heap_allocator();
  348. Array<Operand> operands = {};
  349. if (param_operands) {
  350. operands = *param_operands;
  351. } else {
  352. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  353. for (isize i = 0; i < dst->Proc.param_count; i++) {
  354. Entity *param = dst->Proc.params->Tuple.variables[i];
  355. Operand o = {Addressing_Value};
  356. o.type = param->type;
  357. array_add(&operands, o);
  358. }
  359. }
  360. defer (if (param_operands == nullptr) {
  361. array_free(&operands);
  362. });
  363. CheckerContext nctx = *old_c;
  364. Scope *scope = create_scope(info, base_entity->scope);
  365. scope->flags |= ScopeFlag_Proc;
  366. nctx.scope = scope;
  367. nctx.allow_polymorphic_types = true;
  368. if (nctx.polymorphic_scope == nullptr) {
  369. nctx.polymorphic_scope = scope;
  370. }
  371. auto *pt = &src->Proc;
  372. // NOTE(bill): This is slightly memory leaking if the type already exists
  373. // Maybe it's better to check with the previous types first?
  374. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  375. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  376. if (!success) {
  377. return false;
  378. }
  379. GenProcsData *gen_procs = nullptr;
  380. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  381. GB_ASSERT(base_entity->kind == Entity_Procedure);
  382. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  383. gen_procs = base_entity->Procedure.gen_procs;
  384. if (gen_procs) {
  385. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  386. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  387. for (Entity *other : gen_procs->procs) {
  388. Type *pt = base_type(other->type);
  389. if (are_types_identical(pt, final_proc_type)) {
  390. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  391. if (poly_proc_data) {
  392. poly_proc_data->gen_entity = other;
  393. }
  394. return true;
  395. }
  396. }
  397. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  398. } else {
  399. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  400. gen_procs->procs.allocator = heap_allocator();
  401. base_entity->Procedure.gen_procs = gen_procs;
  402. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  403. }
  404. {
  405. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  406. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  407. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  408. nctx.no_polymorphic_errors = false;
  409. // NOTE(bill): Reset scope from the failed procedure type
  410. scope->head_child.store(nullptr, std::memory_order_relaxed);
  411. string_map_clear(&scope->elements);
  412. ptr_set_clear(&scope->imported);
  413. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  414. Ast *cloned_proc_type_node = clone_ast(pt->node);
  415. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  416. if (!success) {
  417. return false;
  418. }
  419. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  420. for (Entity *other : gen_procs->procs) {
  421. Type *pt = base_type(other->type);
  422. if (are_types_identical(pt, final_proc_type)) {
  423. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  424. if (poly_proc_data) {
  425. poly_proc_data->gen_entity = other;
  426. }
  427. DeclInfo *decl = other->decl_info;
  428. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  429. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  430. proc_info->file = other->file;
  431. proc_info->token = other->token;
  432. proc_info->decl = decl;
  433. proc_info->type = other->type;
  434. proc_info->body = decl->proc_lit->ProcLit.body;
  435. proc_info->tags = other->Procedure.tags;;
  436. proc_info->generated_from_polymorphic = true;
  437. proc_info->poly_def_node = poly_def_node;
  438. check_procedure_later(nctx.checker, proc_info);
  439. }
  440. return true;
  441. }
  442. }
  443. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  444. }
  445. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  446. ast_node(pl, ProcLit, proc_lit);
  447. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  448. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  449. final_proc_type->Proc.is_poly_specialized = true;
  450. final_proc_type->Proc.is_polymorphic = true;
  451. final_proc_type->Proc.variadic = src->Proc.variadic;
  452. final_proc_type->Proc.require_results = src->Proc.require_results;
  453. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  454. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  455. final_proc_type->Proc.diverging = src->Proc.diverging;
  456. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  457. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  458. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  459. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  460. for (isize i = 0; i < operands.count; i++) {
  461. Operand o = operands[i];
  462. if (final_proc_type == o.type ||
  463. base_entity->type == o.type) {
  464. // NOTE(bill): Cycle
  465. final_proc_type->Proc.is_poly_specialized = false;
  466. break;
  467. }
  468. }
  469. u64 tags = base_entity->Procedure.tags;
  470. Ast *ident = clone_ast(base_entity->identifier);
  471. Token token = ident->Ident.token;
  472. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  473. d->gen_proc_type = final_proc_type;
  474. d->type_expr = pl->type;
  475. d->proc_lit = proc_lit;
  476. d->proc_checked_state = ProcCheckedState_Unchecked;
  477. d->defer_use_checked = false;
  478. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  479. entity->state.store(EntityState_Resolved);
  480. entity->identifier = ident;
  481. add_entity_and_decl_info(&nctx, ident, entity, d);
  482. // NOTE(bill): Set the scope afterwards as this is not real overloading
  483. entity->scope = scope->parent;
  484. entity->file = base_entity->file;
  485. entity->pkg = base_entity->pkg;
  486. entity->flags = 0;
  487. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  488. if (base_entity->flags & EntityFlag_Cold) {
  489. entity->flags |= EntityFlag_Cold;
  490. }
  491. if (base_entity->flags & EntityFlag_Disabled) {
  492. entity->flags |= EntityFlag_Disabled;
  493. }
  494. d->entity = entity;
  495. AstFile *file = nullptr;
  496. {
  497. Scope *s = entity->scope;
  498. while (s != nullptr && s->file == nullptr) {
  499. file = s->file;
  500. s = s->parent;
  501. }
  502. }
  503. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  504. array_add(&gen_procs->procs, entity);
  505. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  506. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  507. proc_info->file = file;
  508. proc_info->token = token;
  509. proc_info->decl = d;
  510. proc_info->type = final_proc_type;
  511. proc_info->body = pl->body;
  512. proc_info->tags = tags;
  513. proc_info->generated_from_polymorphic = true;
  514. proc_info->poly_def_node = poly_def_node;
  515. if (poly_proc_data) {
  516. poly_proc_data->gen_entity = entity;
  517. poly_proc_data->proc_info = proc_info;
  518. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  519. }
  520. // NOTE(bill): Check the newly generated procedure body
  521. check_procedure_later(nctx.checker, proc_info);
  522. return true;
  523. }
  524. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  525. if (operand->expr == nullptr) return false;
  526. Entity *base_entity = entity_from_expr(operand->expr);
  527. if (base_entity == nullptr) return false;
  528. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  529. }
  530. gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> const *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  531. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  532. }
  533. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  534. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  535. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  536. #define MAXIMUM_TYPE_DISTANCE 10
  537. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  538. if (c == nullptr) {
  539. GB_ASSERT(operand->mode == Addressing_Value);
  540. GB_ASSERT(is_type_typed(operand->type));
  541. }
  542. if (operand->mode == Addressing_Invalid ||
  543. type == t_invalid) {
  544. return -1;
  545. }
  546. if (operand->mode == Addressing_Builtin) {
  547. return -1;
  548. }
  549. if (operand->mode == Addressing_Type) {
  550. if (is_type_typeid(type)) {
  551. if (is_type_polymorphic(operand->type)) {
  552. return -1;
  553. }
  554. add_type_info_type(c, operand->type);
  555. return 4;
  556. }
  557. return -1;
  558. }
  559. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  560. return -1;
  561. }
  562. Type *s = operand->type;
  563. if (are_types_identical(s, type)) {
  564. return 0;
  565. }
  566. Type *src = base_type(s);
  567. Type *dst = base_type(type);
  568. if (is_type_untyped_uninit(src)) {
  569. return 1;
  570. }
  571. if (is_type_untyped_nil(src)) {
  572. if (type_has_nil(dst)) {
  573. return 1;
  574. }
  575. return -1;
  576. }
  577. if (is_type_untyped(src)) {
  578. if (is_type_any(dst)) {
  579. // NOTE(bill): Anything can cast to 'Any'
  580. add_type_info_type(c, s);
  581. return MAXIMUM_TYPE_DISTANCE;
  582. }
  583. if (dst->kind == Type_Basic) {
  584. if (operand->mode == Addressing_Constant) {
  585. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  586. if (is_type_typed(dst) && src->kind == Type_Basic) {
  587. switch (src->Basic.kind) {
  588. case Basic_UntypedBool:
  589. if (is_type_boolean(dst)) {
  590. return 1;
  591. }
  592. break;
  593. case Basic_UntypedRune:
  594. if (is_type_integer(dst) || is_type_rune(dst)) {
  595. return 1;
  596. }
  597. break;
  598. case Basic_UntypedInteger:
  599. if (is_type_integer(dst) || is_type_rune(dst)) {
  600. return 1;
  601. }
  602. break;
  603. case Basic_UntypedString:
  604. if (is_type_string(dst)) {
  605. return 1;
  606. }
  607. break;
  608. case Basic_UntypedFloat:
  609. if (is_type_float(dst)) {
  610. return 1;
  611. }
  612. break;
  613. case Basic_UntypedComplex:
  614. if (is_type_complex(dst)) {
  615. return 1;
  616. }
  617. if (is_type_quaternion(dst)) {
  618. return 2;
  619. }
  620. break;
  621. case Basic_UntypedQuaternion:
  622. if (is_type_quaternion(dst)) {
  623. return 1;
  624. }
  625. break;
  626. }
  627. }
  628. return 2;
  629. }
  630. return -1;
  631. }
  632. if (src->kind == Type_Basic) {
  633. Type *d = base_array_type(dst);
  634. i64 score = -1;
  635. switch (src->Basic.kind) {
  636. case Basic_UntypedBool:
  637. if (is_type_boolean(d)) {
  638. score = 1;
  639. }
  640. break;
  641. case Basic_UntypedRune:
  642. if (is_type_integer(d) || is_type_rune(d)) {
  643. score = 1;
  644. }
  645. break;
  646. case Basic_UntypedInteger:
  647. if (is_type_integer(d) || is_type_rune(d)) {
  648. score = 1;
  649. }
  650. break;
  651. case Basic_UntypedString:
  652. if (is_type_string(d)) {
  653. score = 1;
  654. }
  655. break;
  656. case Basic_UntypedFloat:
  657. if (is_type_float(d)) {
  658. score = 1;
  659. }
  660. break;
  661. case Basic_UntypedComplex:
  662. if (is_type_complex(d)) {
  663. score = 1;
  664. }
  665. if (is_type_quaternion(d)) {
  666. score = 2;
  667. }
  668. break;
  669. case Basic_UntypedQuaternion:
  670. if (is_type_quaternion(d)) {
  671. score = 1;
  672. }
  673. break;
  674. }
  675. if (score > 0) {
  676. if (is_type_typed(d)) {
  677. score += 1;
  678. }
  679. if (d != dst) {
  680. score += 6;
  681. }
  682. }
  683. return score;
  684. }
  685. }
  686. }
  687. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  688. if (c->in_enum_type) {
  689. return 3;
  690. }
  691. }
  692. {
  693. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  694. if (subtype_level > 0) {
  695. return 4 + subtype_level;
  696. }
  697. }
  698. // rawptr <- ^T
  699. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  700. return 5;
  701. }
  702. // rawptr <- [^]T
  703. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  704. return 5;
  705. }
  706. // ^T <- [^]T
  707. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  708. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  709. return 4;
  710. }
  711. }
  712. // [^]T <- ^T
  713. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  714. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  715. return 4;
  716. }
  717. }
  718. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  719. bool modify_type = !c->no_polymorphic_errors;
  720. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  721. return 2;
  722. }
  723. }
  724. if (is_type_union(dst)) {
  725. for (Type *vt : dst->Union.variants) {
  726. if (are_types_identical(vt, s)) {
  727. return 1;
  728. }
  729. if (is_type_proc(vt)) {
  730. if (are_types_identical(base_type(vt), src)) {
  731. return 1;
  732. }
  733. }
  734. }
  735. if (dst->Union.variants.count == 1) {
  736. Type *vt = dst->Union.variants[0];
  737. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  738. if (score >= 0) {
  739. return score+2;
  740. }
  741. } else if (is_type_untyped(src)) {
  742. i64 prev_lowest_score = -1;
  743. i64 lowest_score = -1;
  744. for (Type *vt : dst->Union.variants) {
  745. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  746. if (score >= 0) {
  747. if (lowest_score < 0) {
  748. lowest_score = score;
  749. } else {
  750. if (prev_lowest_score < 0) {
  751. prev_lowest_score = lowest_score;
  752. } else {
  753. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  754. }
  755. lowest_score = gb_min(lowest_score, score);
  756. }
  757. }
  758. }
  759. if (lowest_score >= 0) {
  760. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  761. return lowest_score+2;
  762. }
  763. }
  764. }
  765. }
  766. if (is_type_proc(dst)) {
  767. if (are_types_identical(src, dst)) {
  768. return 3;
  769. }
  770. PolyProcData poly_proc_data = {};
  771. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  772. Entity *e = poly_proc_data.gen_entity;
  773. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  774. add_entity_use(c, operand->expr, e);
  775. return 4;
  776. }
  777. }
  778. if (is_type_complex_or_quaternion(dst)) {
  779. Type *elem = base_complex_elem_type(dst);
  780. if (are_types_identical(elem, base_type(src))) {
  781. return 5;
  782. }
  783. }
  784. if (allow_array_programming) {
  785. if (is_type_array(dst)) {
  786. Type *elem = base_array_type(dst);
  787. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  788. if (distance >= 0) {
  789. return distance + 6;
  790. }
  791. }
  792. if (is_type_simd_vector(dst)) {
  793. Type *dst_elem = base_array_type(dst);
  794. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  795. if (distance >= 0) {
  796. return distance + 6;
  797. }
  798. }
  799. }
  800. if (is_type_matrix(dst)) {
  801. if (are_types_identical(src, dst)) {
  802. return 5;
  803. }
  804. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  805. Type *dst_elem = base_array_type(dst);
  806. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  807. if (distance >= 0) {
  808. return distance + 7;
  809. }
  810. }
  811. }
  812. if (is_type_any(dst)) {
  813. if (!is_type_polymorphic(src)) {
  814. if (operand->mode == Addressing_Context && operand->type == t_context) {
  815. return -1;
  816. } else {
  817. // NOTE(bill): Anything can cast to 'Any'
  818. add_type_info_type(c, s);
  819. return MAXIMUM_TYPE_DISTANCE;
  820. }
  821. }
  822. }
  823. Ast *expr = unparen_expr(operand->expr);
  824. if (expr != nullptr) {
  825. if (expr->kind == Ast_AutoCast) {
  826. Operand x = *operand;
  827. x.expr = expr->AutoCast.expr;
  828. if (check_cast_internal(c, &x, type)) {
  829. return MAXIMUM_TYPE_DISTANCE;
  830. }
  831. }
  832. }
  833. return -1;
  834. }
  835. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  836. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  837. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  838. // TODO(bill): A decent score function
  839. i64 d = distance*distance; // x^2
  840. if (is_variadic && d >= 0) {
  841. d += distance + 1; // x^2 + x + 1
  842. }
  843. return gb_max(c - d, 0);
  844. }
  845. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false, bool allow_array_programming=true) {
  846. if (c == nullptr) {
  847. GB_ASSERT(operand->mode == Addressing_Value);
  848. GB_ASSERT(is_type_typed(operand->type));
  849. }
  850. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  851. if (score_) *score_ = 0;
  852. return false;
  853. }
  854. // Handle polymorphic procedure used as default parameter
  855. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  856. Entity *e = entity_from_expr(operand->expr);
  857. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  858. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  859. // during the initial check. It will be properly instantiated when actually used.
  860. if (score_) *score_ = assign_score_function(1);
  861. return true;
  862. }
  863. }
  864. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  865. if (score >= 0) {
  866. if (score_) *score_ = assign_score_function(score, is_variadic);
  867. return true;
  868. }
  869. if (score_) *score_ = 0;
  870. return false;
  871. }
  872. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  873. i64 score = 0;
  874. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  875. }
  876. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  877. Operand x = {};
  878. x.type = src;
  879. x.mode = Addressing_Value;
  880. return check_is_assignable_to(nullptr, &x, dst);
  881. }
  882. gb_internal AstPackage *get_package_of_type(Type *type) {
  883. for (;;) {
  884. if (type == nullptr) {
  885. return nullptr;
  886. }
  887. switch (type->kind) {
  888. case Type_Basic:
  889. return builtin_pkg;
  890. case Type_Named:
  891. if (type->Named.type_name != nullptr) {
  892. return type->Named.type_name->pkg;
  893. }
  894. return nullptr;
  895. case Type_Pointer:
  896. type = type->Pointer.elem;
  897. continue;
  898. case Type_Array:
  899. type = type->Array.elem;
  900. continue;
  901. case Type_Slice:
  902. type = type->Slice.elem;
  903. continue;
  904. case Type_DynamicArray:
  905. type = type->DynamicArray.elem;
  906. continue;
  907. }
  908. return nullptr;
  909. }
  910. }
  911. // NOTE(bill): 'context_name' is for debugging and error messages
  912. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  913. check_not_tuple(c, operand);
  914. if (operand->mode == Addressing_Invalid) {
  915. return;
  916. }
  917. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  918. String article = error_article(context_name);
  919. if (is_type_untyped(operand->type)) {
  920. Type *target_type = type;
  921. if (type == nullptr || is_type_any(type)) {
  922. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  923. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  924. operand->mode = Addressing_Invalid;
  925. return;
  926. }
  927. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  928. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  929. operand->mode = Addressing_Invalid;
  930. return;
  931. }
  932. target_type = default_type(operand->type);
  933. if (type != nullptr && !is_type_any(type)) {
  934. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  935. }
  936. add_type_info_type(c, type);
  937. add_type_info_type(c, target_type);
  938. }
  939. convert_to_typed(c, operand, target_type);
  940. if (operand->mode == Addressing_Invalid) {
  941. return;
  942. }
  943. }
  944. if (type == nullptr) {
  945. return;
  946. }
  947. if (operand->mode == Addressing_ProcGroup) {
  948. bool good = false;
  949. if (type != nullptr && is_type_proc(type)) {
  950. Array<Entity *> procs = proc_group_entities(c, *operand);
  951. // NOTE(bill): These should be done
  952. for (Entity *e : procs) {
  953. Type *t = base_type(e->type);
  954. if (t == t_invalid) {
  955. continue;
  956. }
  957. Operand x = {};
  958. x.mode = Addressing_Value;
  959. x.type = t;
  960. if (check_is_assignable_to(c, &x, type)) {
  961. add_entity_use(c, operand->expr, e);
  962. good = true;
  963. break;
  964. }
  965. }
  966. }
  967. if (!good) {
  968. gbString expr_str = expr_to_string(operand->expr);
  969. gbString op_type_str = type_to_string(operand->type);
  970. gbString type_str = type_to_string(type);
  971. defer (gb_string_free(type_str));
  972. defer (gb_string_free(op_type_str));
  973. defer (gb_string_free(expr_str));
  974. // TODO(bill): is this a good enough error message?
  975. error(operand->expr,
  976. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  977. expr_str,
  978. op_type_str,
  979. LIT(article),
  980. LIT(context_name));
  981. operand->mode = Addressing_Invalid;
  982. }
  983. convert_to_typed(c, operand, type);
  984. return;
  985. }
  986. if (check_is_assignable_to(c, operand, type)) {
  987. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  988. add_type_info_type(c, operand->type);
  989. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  990. }
  991. } else {
  992. gbString expr_str = expr_to_string(operand->expr);
  993. gbString op_type_str = type_to_string(operand->type);
  994. gbString type_str = type_to_string(type);
  995. defer (gb_string_free(type_str));
  996. defer (gb_string_free(op_type_str));
  997. defer (gb_string_free(expr_str));
  998. switch (operand->mode) {
  999. case Addressing_Builtin:
  1000. error(operand->expr,
  1001. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1002. expr_str,
  1003. LIT(article),
  1004. LIT(context_name));
  1005. break;
  1006. case Addressing_Type:
  1007. if (is_type_polymorphic(operand->type)) {
  1008. error(operand->expr,
  1009. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1010. op_type_str,
  1011. LIT(article),
  1012. LIT(context_name));
  1013. } else {
  1014. ERROR_BLOCK();
  1015. error(operand->expr,
  1016. "Cannot assign '%s', a type, to %.*s%.*s",
  1017. op_type_str,
  1018. LIT(article),
  1019. LIT(context_name));
  1020. if (type && are_types_identical(type, t_any)) {
  1021. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1022. }
  1023. }
  1024. break;
  1025. default:
  1026. // TODO(bill): is this a good enough error message?
  1027. {
  1028. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1029. gbString type_extra = gb_string_make(heap_allocator(), "");
  1030. defer (gb_string_free(op_type_extra));
  1031. defer (gb_string_free(type_extra));
  1032. isize on = gb_string_length(op_type_str);
  1033. isize tn = gb_string_length(type_str);
  1034. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1035. AstPackage *op_pkg = get_package_of_type(operand->type);
  1036. AstPackage *type_pkg = get_package_of_type(type);
  1037. if (op_pkg != nullptr) {
  1038. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1039. }
  1040. if (type_pkg != nullptr) {
  1041. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1042. }
  1043. }
  1044. ERROR_BLOCK();
  1045. error(operand->expr,
  1046. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1047. expr_str,
  1048. op_type_str, op_type_extra,
  1049. type_str, type_extra,
  1050. LIT(article),
  1051. LIT(context_name));
  1052. check_assignment_error_suggestion(c, operand, type);
  1053. Type *src = base_type(operand->type);
  1054. Type *dst = base_type(type);
  1055. if (context_name == "procedure argument") {
  1056. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1057. gbString a = expr_to_string(operand->expr);
  1058. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1059. gb_string_free(a);
  1060. }
  1061. }
  1062. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1063. Type *x = src;
  1064. Type *y = dst;
  1065. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1066. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1067. if (same_inputs && same_outputs &&
  1068. x->Proc.calling_convention != y->Proc.calling_convention) {
  1069. gbString s_expected = type_to_string(y);
  1070. gbString s_got = type_to_string(x);
  1071. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1072. error_line("\t Expected \"%s\", got \"%s\"\n",
  1073. proc_calling_convention_strings[y->Proc.calling_convention],
  1074. proc_calling_convention_strings[x->Proc.calling_convention]);
  1075. error_line("\t Expected: %s\n", s_expected);
  1076. error_line("\t Got: %s\n", s_got);
  1077. gb_string_free(s_got);
  1078. gb_string_free(s_expected);
  1079. } else if (same_inputs && same_outputs &&
  1080. x->Proc.diverging != y->Proc.diverging) {
  1081. gbString s_expected = type_to_string(y);
  1082. if (y->Proc.diverging) {
  1083. s_expected = gb_string_appendc(s_expected, " -> !");
  1084. }
  1085. gbString s_got = type_to_string(x);
  1086. if (x->Proc.diverging) {
  1087. s_got = gb_string_appendc(s_got, " -> !");
  1088. }
  1089. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1090. error_line("\t Expected: %s\n", s_expected);
  1091. error_line("\t Got: %s\n", s_got);
  1092. gb_string_free(s_got);
  1093. gb_string_free(s_expected);
  1094. } else if (same_inputs && !same_outputs) {
  1095. gbString s_expected = type_to_string(y->Proc.results);
  1096. gbString s_got = type_to_string(x->Proc.results);
  1097. error_line("\tNote: The return types differ between the procedure signature types\n");
  1098. error_line("\t Expected: %s\n", s_expected);
  1099. error_line("\t Got: %s\n", s_got);
  1100. gb_string_free(s_got);
  1101. gb_string_free(s_expected);
  1102. } else if (!same_inputs && same_outputs) {
  1103. gbString s_expected = type_to_string(y->Proc.params);
  1104. gbString s_got = type_to_string(x->Proc.params);
  1105. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1106. error_line("\t Expected: %s\n", s_expected);
  1107. error_line("\t Got: %s\n", s_got);
  1108. gb_string_free(s_got);
  1109. gb_string_free(s_expected);
  1110. } else {
  1111. gbString s_expected = type_to_string(y);
  1112. gbString s_got = type_to_string(x);
  1113. error_line("\tNote: The signature type do not match whatsoever\n");
  1114. error_line("\t Expected: %s\n", s_expected);
  1115. error_line("\t Got: %s\n", s_got);
  1116. gb_string_free(s_got);
  1117. gb_string_free(s_expected);
  1118. }
  1119. }
  1120. }
  1121. break;
  1122. }
  1123. operand->mode = Addressing_Invalid;
  1124. return;
  1125. }
  1126. }
  1127. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1128. Type *gt = *gt_;
  1129. GB_ASSERT(gt->kind == Type_Generic);
  1130. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1131. GB_ASSERT(e != nullptr);
  1132. if (e->kind == Entity_TypeName) {
  1133. *gt_ = nullptr;
  1134. *dst_count = source_count;
  1135. e->kind = Entity_Constant;
  1136. e->Constant.value = exact_value_i64(source_count);
  1137. e->type = t_untyped_integer;
  1138. return true;
  1139. } else if (e->kind == Entity_Constant) {
  1140. *gt_ = nullptr;
  1141. if (e->Constant.value.kind != ExactValue_Integer) {
  1142. return false;
  1143. }
  1144. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1145. if (count != source_count) {
  1146. return false;
  1147. }
  1148. *dst_count = source_count;
  1149. return true;
  1150. }
  1151. return false;
  1152. }
  1153. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1154. Operand o = {Addressing_Value};
  1155. o.type = source;
  1156. switch (poly->kind) {
  1157. case Type_Basic:
  1158. if (compound) return are_types_identical(poly, source);
  1159. return check_is_assignable_to(c, &o, poly);
  1160. case Type_Named: {
  1161. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1162. return true;
  1163. }
  1164. if (compound || !is_type_generic(poly)) {
  1165. return are_types_identical(poly, source);
  1166. }
  1167. return check_is_assignable_to(c, &o, poly);
  1168. }
  1169. case Type_Generic: {
  1170. if (poly->Generic.specialized != nullptr) {
  1171. Type *s = poly->Generic.specialized;
  1172. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1173. return false;
  1174. }
  1175. }
  1176. if (modify_type) {
  1177. Type *ds = default_type(source);
  1178. gb_memmove(poly, ds, gb_size_of(Type));
  1179. }
  1180. return true;
  1181. }
  1182. case Type_Pointer:
  1183. if (source->kind == Type_Pointer) {
  1184. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1185. if (level > 0) {
  1186. return true;
  1187. }
  1188. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1189. } else if (source->kind == Type_MultiPointer) {
  1190. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1191. if (level > 0) {
  1192. return true;
  1193. }
  1194. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1195. }
  1196. return false;
  1197. case Type_MultiPointer:
  1198. if (source->kind == Type_MultiPointer) {
  1199. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1200. if (level > 0) {
  1201. return true;
  1202. }
  1203. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1204. } else if (source->kind == Type_Pointer) {
  1205. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1206. if (level > 0) {
  1207. return true;
  1208. }
  1209. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1210. }
  1211. return false;
  1212. case Type_Array:
  1213. if (source->kind == Type_Array) {
  1214. if (poly->Array.generic_count != nullptr) {
  1215. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1216. return false;
  1217. }
  1218. }
  1219. if (poly->Array.count == source->Array.count) {
  1220. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1221. }
  1222. } else if (source->kind == Type_EnumeratedArray) {
  1223. if (poly->Array.generic_count != nullptr) {
  1224. Type *gt = poly->Array.generic_count;
  1225. GB_ASSERT(gt->kind == Type_Generic);
  1226. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1227. GB_ASSERT(e != nullptr);
  1228. if (e->kind == Entity_TypeName) {
  1229. Type *index = source->EnumeratedArray.index;
  1230. Type *it = base_type(index);
  1231. if (it->kind != Type_Enum) {
  1232. return false;
  1233. }
  1234. poly->kind = Type_EnumeratedArray;
  1235. poly->cached_size = -1;
  1236. poly->cached_align = -1;
  1237. poly->flags.exchange(source->flags);
  1238. poly->failure = false;
  1239. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1240. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1241. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1242. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1243. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1244. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1245. e->kind = Entity_TypeName;
  1246. e->TypeName.is_type_alias = true;
  1247. e->type = index;
  1248. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1249. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return false;
  1255. case Type_EnumeratedArray:
  1256. if (source->kind == Type_EnumeratedArray) {
  1257. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1258. return false;
  1259. }
  1260. if (poly->EnumeratedArray.op) {
  1261. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1262. return false;
  1263. }
  1264. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1265. return false;
  1266. }
  1267. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1268. return false;
  1269. }
  1270. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1271. }
  1272. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1273. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1274. return index || elem;
  1275. }
  1276. return false;
  1277. case Type_DynamicArray:
  1278. if (source->kind == Type_DynamicArray) {
  1279. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1280. }
  1281. return false;
  1282. case Type_Slice:
  1283. if (source->kind == Type_Slice) {
  1284. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1285. }
  1286. return false;
  1287. case Type_Enum:
  1288. return false;
  1289. case Type_BitSet:
  1290. if (source->kind == Type_BitSet) {
  1291. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1292. return false;
  1293. }
  1294. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1295. // it could not figure that stuff out when the poly type was created.
  1296. if (poly->BitSet.upper == 0 && modify_type) {
  1297. poly->BitSet.upper = source->BitSet.upper;
  1298. }
  1299. if (poly->BitSet.lower == 0 && modify_type) {
  1300. poly->BitSet.lower = source->BitSet.lower;
  1301. }
  1302. if (poly->BitSet.underlying == nullptr) {
  1303. if (modify_type) {
  1304. poly->BitSet.underlying = source->BitSet.underlying;
  1305. }
  1306. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1307. return false;
  1308. }
  1309. return true;
  1310. }
  1311. return false;
  1312. case Type_Union:
  1313. if (source->kind == Type_Union) {
  1314. TypeUnion *x = &poly->Union;
  1315. TypeUnion *y = &source->Union;
  1316. if (x->variants.count != y->variants.count) {
  1317. return false;
  1318. }
  1319. for_array(i, x->variants) {
  1320. Type *a = x->variants[i];
  1321. Type *b = y->variants[i];
  1322. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1323. if (!ok) return false;
  1324. }
  1325. return true;
  1326. }
  1327. return false;
  1328. case Type_Struct:
  1329. if (source->kind == Type_Struct) {
  1330. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1331. poly->Struct.soa_kind != StructSoa_None) {
  1332. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1333. if (ok) switch (source->Struct.soa_kind) {
  1334. case StructSoa_None:
  1335. default:
  1336. GB_PANIC("Unhandled SOA Kind");
  1337. break;
  1338. case StructSoa_Fixed:
  1339. if (modify_type) {
  1340. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1341. gb_memmove(poly, type, gb_size_of(*type));
  1342. }
  1343. break;
  1344. case StructSoa_Slice:
  1345. if (modify_type) {
  1346. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1347. gb_memmove(poly, type, gb_size_of(*type));
  1348. }
  1349. break;
  1350. case StructSoa_Dynamic:
  1351. if (modify_type) {
  1352. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1353. gb_memmove(poly, type, gb_size_of(*type));
  1354. }
  1355. break;
  1356. }
  1357. return ok;
  1358. }
  1359. // NOTE(bill): Check for subtypes of
  1360. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1361. }
  1362. return false;
  1363. case Type_BitField:
  1364. if (source->kind == Type_BitField) {
  1365. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1366. }
  1367. return false;
  1368. case Type_Tuple:
  1369. GB_PANIC("This should never happen");
  1370. return false;
  1371. case Type_Proc:
  1372. if (source->kind == Type_Proc) {
  1373. TypeProc *x = &poly->Proc;
  1374. TypeProc *y = &source->Proc;
  1375. if (x->calling_convention != y->calling_convention) {
  1376. return false;
  1377. }
  1378. if (x->c_vararg != y->c_vararg) {
  1379. return false;
  1380. }
  1381. if (x->variadic != y->variadic) {
  1382. return false;
  1383. }
  1384. if (x->param_count != y->param_count) {
  1385. return false;
  1386. }
  1387. if (x->result_count != y->result_count) {
  1388. return false;
  1389. }
  1390. for (isize i = 0; i < x->param_count; i++) {
  1391. Entity *a = x->params->Tuple.variables[i];
  1392. Entity *b = y->params->Tuple.variables[i];
  1393. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1394. if (!ok) return false;
  1395. }
  1396. for (isize i = 0; i < x->result_count; i++) {
  1397. Entity *a = x->results->Tuple.variables[i];
  1398. Entity *b = y->results->Tuple.variables[i];
  1399. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1400. if (!ok) return false;
  1401. }
  1402. return true;
  1403. }
  1404. return false;
  1405. case Type_Map:
  1406. if (source->kind == Type_Map) {
  1407. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1408. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1409. if (key || value) {
  1410. poly->Map.lookup_result_type = nullptr;
  1411. init_map_internal_types(poly);
  1412. return true;
  1413. }
  1414. }
  1415. return false;
  1416. case Type_Matrix:
  1417. if (source->kind == Type_Matrix) {
  1418. if (poly->Matrix.generic_row_count != nullptr) {
  1419. poly->Matrix.stride_in_bytes = 0;
  1420. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1421. return false;
  1422. }
  1423. }
  1424. if (poly->Matrix.generic_column_count != nullptr) {
  1425. poly->Matrix.stride_in_bytes = 0;
  1426. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1427. return false;
  1428. }
  1429. }
  1430. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1431. poly->Matrix.column_count == source->Matrix.column_count) {
  1432. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1433. }
  1434. }
  1435. return false;
  1436. case Type_SimdVector:
  1437. if (source->kind == Type_SimdVector) {
  1438. if (poly->SimdVector.generic_count != nullptr) {
  1439. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1440. return false;
  1441. }
  1442. }
  1443. if (poly->SimdVector.count == source->SimdVector.count) {
  1444. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1445. }
  1446. }
  1447. return false;
  1448. }
  1449. return false;
  1450. }
  1451. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1452. if (curr->state != EntityState_InProgress) {
  1453. return false;
  1454. }
  1455. for_array(i, *c->type_path) {
  1456. Entity *prev = c->type_path->data[i];
  1457. if (prev == curr) {
  1458. if (report) {
  1459. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1460. for (isize j = i; j < c->type_path->count; j++) {
  1461. Entity *curr = (*c->type_path)[j];
  1462. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1463. }
  1464. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1465. curr->type = t_invalid;
  1466. }
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. struct CIdentSuggestion {
  1473. String name;
  1474. String msg;
  1475. };
  1476. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1477. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1478. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1479. {str_lit("sizeof"), str_lit("'size_of'?")},
  1480. {str_lit("alignof"), str_lit("'align_of'?")},
  1481. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1482. {str_lit("_Bool"), str_lit("'bool'?")},
  1483. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1484. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1485. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1486. {str_lit("float"), str_lit("'f32'?")},
  1487. {str_lit("double"), str_lit("'f64'?")},
  1488. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1489. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1490. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1491. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1492. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1493. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1494. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1495. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1496. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1497. {str_lit("uint8_t"), str_lit("'u8'?")},
  1498. {str_lit("int8_t"), str_lit("'i8'?")},
  1499. {str_lit("uint16_t"), str_lit("'u16'?")},
  1500. {str_lit("int16_t"), str_lit("'i16'?")},
  1501. {str_lit("uint32_t"), str_lit("'u32'?")},
  1502. {str_lit("int32_t"), str_lit("'i32'?")},
  1503. {str_lit("uint64_t"), str_lit("'u64'?")},
  1504. {str_lit("int64_t"), str_lit("'i64'?")},
  1505. {str_lit("uint128_t"), str_lit("'u128'?")},
  1506. {str_lit("int128_t"), str_lit("'i128'?")},
  1507. {str_lit("float32"), str_lit("'f32'?")},
  1508. {str_lit("float64"), str_lit("'f64'?")},
  1509. {str_lit("float32_t"), str_lit("'f32'?")},
  1510. {str_lit("float64_t"), str_lit("'f64'?")},
  1511. };
  1512. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1513. GB_ASSERT(n->kind == Ast_Ident);
  1514. o->mode = Addressing_Invalid;
  1515. o->expr = n;
  1516. String name = n->Ident.token.string;
  1517. Entity *e = scope_lookup(c->scope, name);
  1518. if (e == nullptr) {
  1519. if (is_blank_ident(name)) {
  1520. error(n, "'_' cannot be used as a value");
  1521. } else {
  1522. ERROR_BLOCK();
  1523. error(n, "Undeclared name: %.*s", LIT(name));
  1524. // NOTE(bill): Loads of checks for C programmers
  1525. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1526. if (name == suggestion.name) {
  1527. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1528. }
  1529. }
  1530. }
  1531. o->type = t_invalid;
  1532. o->mode = Addressing_Invalid;
  1533. if (named_type != nullptr) {
  1534. set_base_type(named_type, t_invalid);
  1535. }
  1536. return nullptr;
  1537. }
  1538. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1539. if (e->parent_proc_decl != nullptr &&
  1540. e->parent_proc_decl != c->curr_proc_decl) {
  1541. if (e->kind == Entity_Variable) {
  1542. if ((e->flags & EntityFlag_Static) == 0) {
  1543. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1544. return nullptr;
  1545. }
  1546. } else if (e->kind == Entity_Label) {
  1547. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1548. return nullptr;
  1549. }
  1550. }
  1551. if (e->kind == Entity_ProcGroup) {
  1552. auto *pge = &e->ProcGroup;
  1553. DeclInfo *d = decl_info_of_entity(e);
  1554. check_entity_decl(c, e, d, nullptr);
  1555. Array<Entity *> procs = pge->entities;
  1556. bool skip = false;
  1557. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1558. // NOTE(bill): These should be done
  1559. for (Entity *proc : procs) {
  1560. Type *t = base_type(proc->type);
  1561. if (t == t_invalid) {
  1562. continue;
  1563. }
  1564. Operand x = {};
  1565. x.mode = Addressing_Value;
  1566. x.type = t;
  1567. if (check_is_assignable_to(c, &x, type_hint)) {
  1568. e = proc;
  1569. add_entity_use(c, n, e);
  1570. skip = true;
  1571. break;
  1572. }
  1573. }
  1574. }
  1575. if (!skip) {
  1576. o->mode = Addressing_ProcGroup;
  1577. o->type = t_invalid;
  1578. o->proc_group = e;
  1579. return nullptr;
  1580. }
  1581. }
  1582. add_entity_use(c, n, e);
  1583. if (e->state == EntityState_Unresolved) {
  1584. check_entity_decl(c, e, nullptr, named_type);
  1585. }
  1586. if (e->type == nullptr) {
  1587. // TODO(bill): Which is correct? return or compiler_error?
  1588. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1589. return nullptr;
  1590. }
  1591. e->flags |= EntityFlag_Used;
  1592. Type *type = e->type;
  1593. o->type = type;
  1594. switch (e->kind) {
  1595. case Entity_Constant:
  1596. if (type == t_invalid) {
  1597. o->type = t_invalid;
  1598. return e;
  1599. }
  1600. o->value = e->Constant.value;
  1601. if (o->value.kind == ExactValue_Invalid) {
  1602. return e;
  1603. }
  1604. if (o->value.kind == ExactValue_Procedure) {
  1605. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1606. if (proc != nullptr) {
  1607. o->mode = Addressing_Value;
  1608. o->type = proc->type;
  1609. return proc;
  1610. }
  1611. }
  1612. o->mode = Addressing_Constant;
  1613. break;
  1614. case Entity_Variable:
  1615. e->flags |= EntityFlag_Used;
  1616. if (type == t_invalid) {
  1617. o->type = t_invalid;
  1618. return e;
  1619. }
  1620. o->mode = Addressing_Variable;
  1621. if (e->flags & EntityFlag_Value) {
  1622. o->mode = Addressing_Value;
  1623. }
  1624. break;
  1625. case Entity_Procedure:
  1626. o->mode = Addressing_Value;
  1627. o->value = exact_value_procedure(n);
  1628. break;
  1629. case Entity_Builtin:
  1630. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1631. o->mode = Addressing_Builtin;
  1632. break;
  1633. case Entity_TypeName:
  1634. o->mode = Addressing_Type;
  1635. if (check_cycle(c, e, true)) {
  1636. o->type = t_invalid;
  1637. }
  1638. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1639. Type *bt = base_type(o->type);
  1640. if (bt != nullptr) {
  1641. o->type = bt;
  1642. }
  1643. }
  1644. break;
  1645. case Entity_ImportName:
  1646. if (!allow_import_name) {
  1647. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1648. }
  1649. return e;
  1650. case Entity_LibraryName:
  1651. if (!allow_import_name) {
  1652. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1653. }
  1654. return e;
  1655. case Entity_Label:
  1656. o->mode = Addressing_NoValue;
  1657. break;
  1658. case Entity_Nil:
  1659. o->mode = Addressing_Value;
  1660. break;
  1661. default:
  1662. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1663. break;
  1664. }
  1665. return e;
  1666. }
  1667. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1668. if (o->type == nullptr) {
  1669. gbString str = expr_to_string(o->expr);
  1670. error(o->expr, "Expression has no value '%s'", str);
  1671. gb_string_free(str);
  1672. return false;
  1673. }
  1674. if (o->mode == Addressing_Type) {
  1675. gbString str = type_to_string(o->type);
  1676. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1677. gb_string_free(str);
  1678. return false;
  1679. }
  1680. Type *type = base_type(core_array_type(o->type));
  1681. gbString str = nullptr;
  1682. switch (op.kind) {
  1683. case Token_Add:
  1684. case Token_Sub:
  1685. if (!is_type_numeric(type)) {
  1686. str = expr_to_string(o->expr);
  1687. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1688. gb_string_free(str);
  1689. }
  1690. break;
  1691. case Token_Xor:
  1692. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1693. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1694. }
  1695. break;
  1696. case Token_Not:
  1697. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1698. ERROR_BLOCK();
  1699. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1700. if (is_type_integer(type)) {
  1701. str = expr_to_string(o->expr);
  1702. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1703. error_line("\t\t'%s == 0'?\n", str);
  1704. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1705. gb_string_free(str);
  1706. }
  1707. } else {
  1708. o->type = t_untyped_bool;
  1709. }
  1710. break;
  1711. case Token_Mul:
  1712. {
  1713. ERROR_BLOCK();
  1714. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1715. if (is_type_pointer(o->type)) {
  1716. str = expr_to_string(o->expr);
  1717. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1718. o->type = type_deref(o->type);
  1719. } else if (is_type_multi_pointer(o->type)) {
  1720. str = expr_to_string(o->expr);
  1721. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1722. o->type = type_deref(o->type, true);
  1723. }
  1724. }
  1725. break;
  1726. default:
  1727. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1728. return false;
  1729. }
  1730. return true;
  1731. }
  1732. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1733. Type *main_type = o->type;
  1734. Type *type = base_type(core_array_type(main_type));
  1735. Type *ct = core_type(type);
  1736. switch (op.kind) {
  1737. case Token_Sub:
  1738. case Token_SubEq:
  1739. if (is_type_bit_set(type)) {
  1740. return true;
  1741. } else if (!is_type_numeric(type)) {
  1742. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1743. return false;
  1744. }
  1745. break;
  1746. case Token_Quo:
  1747. case Token_QuoEq:
  1748. if (is_type_matrix(main_type)) {
  1749. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1750. return false;
  1751. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1752. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1753. return false;
  1754. }
  1755. /*fallthrough*/
  1756. case Token_Mul:
  1757. case Token_MulEq:
  1758. case Token_AddEq:
  1759. if (is_type_bit_set(type)) {
  1760. return true;
  1761. } else if (!is_type_numeric(type)) {
  1762. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1763. return false;
  1764. }
  1765. break;
  1766. case Token_Add:
  1767. if (is_type_string(type)) {
  1768. if (o->mode == Addressing_Constant) {
  1769. return true;
  1770. }
  1771. error(op, "String concatenation is only allowed with constant strings");
  1772. return false;
  1773. } else if (is_type_bit_set(type)) {
  1774. return true;
  1775. } else if (!is_type_numeric(type)) {
  1776. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1777. return false;
  1778. }
  1779. break;
  1780. case Token_And:
  1781. case Token_Or:
  1782. case Token_AndEq:
  1783. case Token_OrEq:
  1784. case Token_Xor:
  1785. case Token_XorEq:
  1786. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1787. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1788. return false;
  1789. }
  1790. break;
  1791. case Token_Mod:
  1792. case Token_ModMod:
  1793. case Token_ModEq:
  1794. case Token_ModModEq:
  1795. if (is_type_matrix(main_type)) {
  1796. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1797. return false;
  1798. }
  1799. if (!is_type_integer(type)) {
  1800. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1801. return false;
  1802. } else if (is_type_simd_vector(main_type)) {
  1803. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1804. return false;
  1805. }
  1806. break;
  1807. case Token_AndNot:
  1808. case Token_AndNotEq:
  1809. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1810. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1811. return false;
  1812. }
  1813. break;
  1814. case Token_CmpAnd:
  1815. case Token_CmpOr:
  1816. case Token_CmpAndEq:
  1817. case Token_CmpOrEq:
  1818. if (!is_type_boolean(type)) {
  1819. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1820. return false;
  1821. }
  1822. break;
  1823. default:
  1824. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1830. if (in_value.kind == ExactValue_Invalid) {
  1831. // NOTE(bill): There's already been an error
  1832. return true;
  1833. }
  1834. type = core_type(type);
  1835. if (type == t_invalid) {
  1836. return false;
  1837. } else if (is_type_boolean(type)) {
  1838. return in_value.kind == ExactValue_Bool;
  1839. } else if (is_type_string(type)) {
  1840. if (in_value.kind == ExactValue_String16) {
  1841. return is_type_string16(type) || is_type_cstring16(type);
  1842. }
  1843. return in_value.kind == ExactValue_String;
  1844. } else if (is_type_integer(type) || is_type_rune(type)) {
  1845. if (in_value.kind == ExactValue_Bool) {
  1846. return false;
  1847. }
  1848. ExactValue v = exact_value_to_integer(in_value);
  1849. if (v.kind != ExactValue_Integer) {
  1850. return false;
  1851. }
  1852. if (out_value) *out_value = v;
  1853. if (is_type_untyped(type)) {
  1854. return true;
  1855. }
  1856. BigInt i = v.value_integer;
  1857. i64 byte_size = type_size_of(type);
  1858. BigInt umax = {};
  1859. BigInt imin = {};
  1860. BigInt imax = {};
  1861. if (c->bit_field_bit_size > 0) {
  1862. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1863. big_int_from_u64(&umax, 1);
  1864. big_int_from_i64(&imin, 1);
  1865. big_int_from_i64(&imax, 1);
  1866. BigInt bu = {};
  1867. BigInt bi = {};
  1868. big_int_from_i64(&bu, bit_size);
  1869. big_int_from_i64(&bi, bit_size-1);
  1870. big_int_shl_eq(&umax, &bu);
  1871. mp_decr(&umax);
  1872. big_int_shl_eq(&imin, &bi);
  1873. big_int_neg(&imin, &imin);
  1874. big_int_shl_eq(&imax, &bi);
  1875. mp_decr(&imax);
  1876. } else {
  1877. if (byte_size < 16) {
  1878. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1879. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1880. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1881. } else {
  1882. big_int_from_u64(&umax, 1);
  1883. big_int_from_i64(&imin, 1);
  1884. big_int_from_i64(&imax, 1);
  1885. BigInt bi128 = {};
  1886. BigInt bi127 = {};
  1887. big_int_from_i64(&bi128, 128);
  1888. big_int_from_i64(&bi127, 127);
  1889. big_int_shl_eq(&umax, &bi128);
  1890. mp_decr(&umax);
  1891. big_int_shl_eq(&imin, &bi127);
  1892. big_int_neg(&imin, &imin);
  1893. big_int_shl_eq(&imax, &bi127);
  1894. mp_decr(&imax);
  1895. }
  1896. }
  1897. switch (type->Basic.kind) {
  1898. case Basic_rune:
  1899. case Basic_i8:
  1900. case Basic_i16:
  1901. case Basic_i32:
  1902. case Basic_i64:
  1903. case Basic_i128:
  1904. case Basic_int:
  1905. case Basic_i16le:
  1906. case Basic_i32le:
  1907. case Basic_i64le:
  1908. case Basic_i128le:
  1909. case Basic_i16be:
  1910. case Basic_i32be:
  1911. case Basic_i64be:
  1912. case Basic_i128be:
  1913. {
  1914. // return imin <= i && i <= imax;
  1915. int a = big_int_cmp(&imin, &i);
  1916. int b = big_int_cmp(&i, &imax);
  1917. return (a <= 0) && (b <= 0);
  1918. }
  1919. case Basic_u8:
  1920. case Basic_u16:
  1921. case Basic_u32:
  1922. case Basic_u64:
  1923. case Basic_u128:
  1924. case Basic_uint:
  1925. case Basic_uintptr:
  1926. case Basic_u16le:
  1927. case Basic_u32le:
  1928. case Basic_u64le:
  1929. case Basic_u128le:
  1930. case Basic_u16be:
  1931. case Basic_u32be:
  1932. case Basic_u64be:
  1933. case Basic_u128be:
  1934. {
  1935. // return 0ull <= i && i <= umax;
  1936. int b = big_int_cmp(&i, &umax);
  1937. return !i.sign && (b <= 0);
  1938. }
  1939. case Basic_UntypedInteger:
  1940. return true;
  1941. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1942. }
  1943. } else if (is_type_float(type)) {
  1944. ExactValue v = exact_value_to_float(in_value);
  1945. if (v.kind != ExactValue_Float) {
  1946. return false;
  1947. }
  1948. if (out_value) *out_value = v;
  1949. switch (type->Basic.kind) {
  1950. case Basic_f16:
  1951. case Basic_f32:
  1952. case Basic_f64:
  1953. return true;
  1954. case Basic_f16le:
  1955. case Basic_f16be:
  1956. case Basic_f32le:
  1957. case Basic_f32be:
  1958. case Basic_f64le:
  1959. case Basic_f64be:
  1960. return true;
  1961. case Basic_UntypedFloat:
  1962. return true;
  1963. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1964. }
  1965. } else if (is_type_complex(type)) {
  1966. ExactValue v = exact_value_to_complex(in_value);
  1967. if (v.kind != ExactValue_Complex) {
  1968. return false;
  1969. }
  1970. switch (type->Basic.kind) {
  1971. case Basic_complex32:
  1972. case Basic_complex64:
  1973. case Basic_complex128: {
  1974. ExactValue real = exact_value_real(v);
  1975. ExactValue imag = exact_value_imag(v);
  1976. if (real.kind != ExactValue_Invalid &&
  1977. imag.kind != ExactValue_Invalid) {
  1978. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1979. return true;
  1980. }
  1981. break;
  1982. }
  1983. case Basic_UntypedComplex:
  1984. return true;
  1985. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1986. }
  1987. return false;
  1988. } else if (is_type_quaternion(type)) {
  1989. ExactValue v = exact_value_to_quaternion(in_value);
  1990. if (v.kind != ExactValue_Quaternion) {
  1991. return false;
  1992. }
  1993. switch (type->Basic.kind) {
  1994. case Basic_quaternion64:
  1995. case Basic_quaternion128:
  1996. case Basic_quaternion256: {
  1997. ExactValue real = exact_value_real(v);
  1998. ExactValue imag = exact_value_imag(v);
  1999. ExactValue jmag = exact_value_jmag(v);
  2000. ExactValue kmag = exact_value_kmag(v);
  2001. if (real.kind != ExactValue_Invalid &&
  2002. imag.kind != ExactValue_Invalid) {
  2003. 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));
  2004. return true;
  2005. }
  2006. break;
  2007. }
  2008. case Basic_UntypedComplex:
  2009. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2010. return true;
  2011. case Basic_UntypedQuaternion:
  2012. return true;
  2013. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2014. }
  2015. return false;
  2016. } else if (is_type_pointer(type)) {
  2017. if (in_value.kind == ExactValue_Pointer) {
  2018. return true;
  2019. }
  2020. if (in_value.kind == ExactValue_Integer) {
  2021. return false;
  2022. // return true;
  2023. }
  2024. if (in_value.kind == ExactValue_String) {
  2025. return false;
  2026. }
  2027. if (in_value.kind == ExactValue_String16) {
  2028. return false;
  2029. }
  2030. if (out_value) *out_value = in_value;
  2031. } else if (is_type_bit_set(type)) {
  2032. if (in_value.kind == ExactValue_Integer) {
  2033. return true;
  2034. }
  2035. }
  2036. return false;
  2037. }
  2038. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2039. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2040. gbString b = type_to_string(type);
  2041. defer (gb_string_free(b));
  2042. if (is_type_enum(o->type)) {
  2043. if (check_is_castable_to(c, o, type)) {
  2044. gbString ot = type_to_string(o->type);
  2045. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2046. gb_string_free(ot);
  2047. }
  2048. return true;
  2049. }
  2050. i64 sz = type_size_of(type);
  2051. i64 bit_size = 8*sz;
  2052. bool size_changed = false;
  2053. if (max_bit_size > 0) {
  2054. size_changed = (bit_size != max_bit_size);
  2055. bit_size = gb_min(bit_size, max_bit_size);
  2056. }
  2057. BigInt *bi = &o->value.value_integer;
  2058. if (is_type_unsigned(type)) {
  2059. BigInt one = big_int_make_u64(1);
  2060. BigInt max_size = big_int_make_u64(1);
  2061. BigInt bits = big_int_make_i64(bit_size);
  2062. big_int_shl_eq(&max_size, &bits);
  2063. big_int_sub_eq(&max_size, &one);
  2064. if (big_int_is_neg(bi)) {
  2065. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2066. BigInt dst = {};
  2067. big_int_neg(&dst, bi);
  2068. if (big_int_cmp(&dst, &max_size) < 0) {
  2069. big_int_sub_eq(&dst, &one);
  2070. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2071. gbString t = type_to_string(type);
  2072. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2073. gb_string_free(t);
  2074. }
  2075. } else {
  2076. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2077. if (size_changed) {
  2078. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2079. } else {
  2080. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2081. }
  2082. }
  2083. } else {
  2084. BigInt zero = big_int_make_u64(0);
  2085. BigInt one = big_int_make_u64(1);
  2086. BigInt max_size = big_int_make_u64(1);
  2087. BigInt bits = big_int_make_i64(bit_size - 1);
  2088. big_int_shl_eq(&max_size, &bits);
  2089. String max_size_str = {};
  2090. if (big_int_is_neg(bi)) {
  2091. big_int_neg(&max_size, &max_size);
  2092. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2093. } else {
  2094. big_int_sub_eq(&max_size, &one);
  2095. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2096. }
  2097. if (size_changed) {
  2098. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2099. } else {
  2100. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2101. }
  2102. }
  2103. return true;
  2104. }
  2105. return false;
  2106. }
  2107. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2108. gbString a = expr_to_string(o->expr);
  2109. gbString b = type_to_string(type);
  2110. defer(
  2111. gb_string_free(b);
  2112. gb_string_free(a);
  2113. );
  2114. Type *src = base_type(o->type);
  2115. Type *dst = base_type(type);
  2116. if (is_type_array(src) && is_type_slice(dst)) {
  2117. Type *s = src->Array.elem;
  2118. Type *d = dst->Slice.elem;
  2119. if (are_types_identical(s, d)) {
  2120. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2121. }
  2122. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2123. Type *s = src->DynamicArray.elem;
  2124. Type *d = dst->Slice.elem;
  2125. if (are_types_identical(s, d)) {
  2126. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2127. }
  2128. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2129. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2130. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2131. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2132. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2133. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2134. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2135. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2136. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2137. return;
  2138. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2139. gbString s = expr_to_string(c->type_hint_expr);
  2140. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2141. gb_string_free(s);
  2142. } else if (is_type_pointer(type) &&
  2143. o->mode == Addressing_Variable &&
  2144. are_types_identical(type_deref(type), o->type)) {
  2145. gbString s = expr_to_string(o->expr);
  2146. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2147. gb_string_free(s);
  2148. } else if (is_type_pointer(o->type) &&
  2149. are_types_identical(type_deref(o->type), type)) {
  2150. gbString s = expr_to_string(o->expr);
  2151. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2152. gb_string_free(s);
  2153. }
  2154. }
  2155. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2156. gbString a = expr_to_string(o->expr);
  2157. gbString b = type_to_string(type);
  2158. defer(
  2159. gb_string_free(b);
  2160. gb_string_free(a);
  2161. );
  2162. Type *src = base_type(o->type);
  2163. Type *dst = base_type(type);
  2164. if (is_type_array(src) && is_type_slice(dst)) {
  2165. Type *s = src->Array.elem;
  2166. Type *d = dst->Slice.elem;
  2167. if (are_types_identical(s, d)) {
  2168. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2169. }
  2170. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2171. if (is_type_uintptr(type)) {
  2172. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2173. } else {
  2174. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2175. i64 x = type_size_of(o->type);
  2176. i64 y = type_size_of(type);
  2177. if (x != y) {
  2178. 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);
  2179. }
  2180. }
  2181. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2182. if (is_type_uintptr(o->type)) {
  2183. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2184. } else {
  2185. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2186. }
  2187. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2188. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2189. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2190. return;
  2191. }
  2192. }
  2193. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2194. GB_ASSERT(o->mode == Addressing_Constant);
  2195. ExactValue out_value = o->value;
  2196. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2197. o->value = out_value;
  2198. return true;
  2199. } else {
  2200. o->value = out_value;
  2201. gbString a = expr_to_string(o->expr);
  2202. gbString b = type_to_string(type);
  2203. gbString c = type_to_string(o->type);
  2204. gbString s = exact_value_to_string(o->value);
  2205. defer(
  2206. gb_string_free(s);
  2207. gb_string_free(c);
  2208. gb_string_free(b);
  2209. gb_string_free(a);
  2210. o->mode = Addressing_Invalid;
  2211. );
  2212. ERROR_BLOCK();
  2213. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2214. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2215. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2216. } else {
  2217. i64 max_bit_size = 0;
  2218. if (ctx->bit_field_bit_size) {
  2219. max_bit_size = ctx->bit_field_bit_size;
  2220. }
  2221. if (are_types_identical(o->type, type)) {
  2222. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2223. } else {
  2224. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2225. }
  2226. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2227. }
  2228. } else {
  2229. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2230. check_assignment_error_suggestion(ctx, o, type);
  2231. }
  2232. return false;
  2233. }
  2234. }
  2235. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2236. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2237. if (o->expr->SelectorExpr.is_bit_field) {
  2238. return true;
  2239. }
  2240. }
  2241. if (o->mode == Addressing_OptionalOk) {
  2242. Ast *expr = unselector_expr(o->expr);
  2243. if (expr->kind != Ast_TypeAssertion) {
  2244. return true;
  2245. }
  2246. ast_node(ta, TypeAssertion, expr);
  2247. TypeAndValue tv = ta->expr->tav;
  2248. if (is_type_pointer(tv.type)) {
  2249. return false;
  2250. }
  2251. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2252. return false;
  2253. }
  2254. if (is_type_any(tv.type)) {
  2255. return false;
  2256. }
  2257. return true;
  2258. }
  2259. if (o->mode == Addressing_MapIndex) {
  2260. return false;
  2261. }
  2262. Ast *expr = unparen_expr(o->expr);
  2263. if (expr->kind == Ast_CompoundLit) {
  2264. return false;
  2265. }
  2266. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2267. }
  2268. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2269. type = base_type(type);
  2270. GB_ASSERT(type->kind == Type_BitSet);
  2271. i64 lower = type->BitSet.lower;
  2272. i64 upper = type->BitSet.upper;
  2273. Type *elem = type->BitSet.elem;
  2274. Type *underlying = type->BitSet.underlying;
  2275. bool is_backed = underlying != nullptr;
  2276. gb_unused(is_backed);
  2277. BigInt b_lower = {};
  2278. BigInt b_upper = {};
  2279. big_int_from_i64(&b_lower, lower);
  2280. big_int_from_i64(&b_upper, upper);
  2281. BigInt one = {};
  2282. big_int_from_u64(&one, 1);
  2283. BigInt mask = {};
  2284. if (elem == nullptr) {
  2285. big_int_from_i64(&mask, -1);
  2286. } else if (is_type_enum(elem)) {
  2287. Type *e = base_type(elem);
  2288. GB_ASSERT(e->kind == Type_Enum);
  2289. gb_unused(e);
  2290. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2291. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2292. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2293. BigInt b_lower_base = {};
  2294. big_int_from_i64(&b_lower_base, lower_base);
  2295. for (Entity *f : e->Enum.fields) {
  2296. if (f->kind != Entity_Constant) {
  2297. continue;
  2298. }
  2299. if (f->Constant.value.kind != ExactValue_Integer) {
  2300. continue;
  2301. }
  2302. BigInt shift_amount = {};
  2303. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2304. BigInt value = {};
  2305. big_int_shl(&value, &one, &shift_amount);
  2306. big_int_or(&mask, &mask, &value);
  2307. }
  2308. } else {
  2309. // TODO(bill): enum range based");
  2310. big_int_from_i64(&mask, -1);
  2311. }
  2312. } else {
  2313. i64 lower_base = lower;
  2314. for (i64 x = lower; x <= upper; x++) {
  2315. BigInt shift_amount = {};
  2316. big_int_from_i64(&shift_amount, x - lower_base);
  2317. BigInt value = {};
  2318. big_int_shl(&value, &one, &shift_amount);
  2319. big_int_or(&mask, &mask, &value);
  2320. }
  2321. }
  2322. ExactValue res = {};
  2323. res.kind = ExactValue_Integer;
  2324. res.value_integer = mask;
  2325. return res;
  2326. }
  2327. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2328. switch (op.kind) {
  2329. case Token_And: { // Pointer address
  2330. if (check_is_not_addressable(c, o)) {
  2331. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2332. ast_node(ue, UnaryExpr, node);
  2333. gbString str = expr_to_string(ue->expr);
  2334. defer (gb_string_free(str));
  2335. Entity *e = entity_of_node(ue->expr);
  2336. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2337. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2338. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2339. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2340. } else {
  2341. switch (o->mode) {
  2342. case Addressing_Constant:
  2343. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2344. break;
  2345. case Addressing_SwizzleValue:
  2346. case Addressing_SwizzleVariable:
  2347. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2348. break;
  2349. default:
  2350. {
  2351. ERROR_BLOCK();
  2352. error(op, "Cannot take the pointer address of '%s'", str);
  2353. if (e == nullptr) {
  2354. break;
  2355. }
  2356. if ((e->flags & EntityFlag_ForValue) != 0) {
  2357. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2358. if (parent_type != nullptr && is_type_string(parent_type)) {
  2359. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2360. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2361. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2362. } else {
  2363. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2364. }
  2365. if (parent_type != nullptr && is_type_map(parent_type)) {
  2366. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2367. } else {
  2368. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2369. }
  2370. }
  2371. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2372. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2373. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2374. }
  2375. }
  2376. break;
  2377. }
  2378. }
  2379. }
  2380. o->mode = Addressing_Invalid;
  2381. return;
  2382. }
  2383. if (o->mode == Addressing_SoaVariable) {
  2384. ast_node(ue, UnaryExpr, node);
  2385. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2386. ast_node(ie, IndexExpr, ue->expr);
  2387. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2388. GB_ASSERT(is_type_soa_struct(soa_type));
  2389. o->type = alloc_type_soa_pointer(soa_type);
  2390. } else {
  2391. o->type = alloc_type_pointer(o->type);
  2392. }
  2393. } else {
  2394. o->type = alloc_type_pointer(o->type);
  2395. }
  2396. switch (o->mode) {
  2397. case Addressing_OptionalOk:
  2398. case Addressing_MapIndex:
  2399. o->mode = Addressing_OptionalOkPtr;
  2400. break;
  2401. default:
  2402. o->mode = Addressing_Value;
  2403. break;
  2404. }
  2405. return;
  2406. }
  2407. }
  2408. if (!check_unary_op(c, o, op)) {
  2409. o->mode = Addressing_Invalid;
  2410. return;
  2411. }
  2412. if (o->mode == Addressing_Constant) {
  2413. Type *type = base_type(o->type);
  2414. if (!is_type_constant_type(o->type)) {
  2415. if (is_type_array_like(o->type)) {
  2416. o->mode = Addressing_Value;
  2417. return;
  2418. }
  2419. gbString xt = type_to_string(o->type);
  2420. gbString err_str = expr_to_string(node);
  2421. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2422. gb_string_free(err_str);
  2423. gb_string_free(xt);
  2424. o->mode = Addressing_Invalid;
  2425. return;
  2426. }
  2427. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2428. gbString err_str = expr_to_string(node);
  2429. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2430. gb_string_free(err_str);
  2431. o->mode = Addressing_Invalid;
  2432. return;
  2433. }
  2434. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2435. gbString err_str = expr_to_string(node);
  2436. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2437. gb_string_free(err_str);
  2438. o->mode = Addressing_Invalid;
  2439. return;
  2440. }
  2441. i32 precision = 0;
  2442. if (is_type_typed(type)) {
  2443. precision = cast(i32)(8 * type_size_of(type));
  2444. }
  2445. bool is_unsigned = is_type_unsigned(type);
  2446. if (is_type_rune(type)) {
  2447. GB_ASSERT(!is_unsigned);
  2448. }
  2449. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2450. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2451. ExactValue mask = exact_bit_set_all_set_mask(type);
  2452. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2453. }
  2454. if (is_type_typed(type)) {
  2455. if (node != nullptr) {
  2456. o->expr = node;
  2457. }
  2458. check_is_expressible(c, o, type);
  2459. }
  2460. return;
  2461. }
  2462. o->mode = Addressing_Value;
  2463. }
  2464. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2465. if (t == nullptr) {
  2466. return;
  2467. }
  2468. t = base_type(t);
  2469. if (!is_type_comparable(t)) {
  2470. return;
  2471. }
  2472. switch (t->kind) {
  2473. case Type_Basic:
  2474. switch (t->Basic.kind) {
  2475. case Basic_complex32:
  2476. add_package_dependency(c, "runtime", "complex32_eq");
  2477. add_package_dependency(c, "runtime", "complex32_ne");
  2478. break;
  2479. case Basic_complex64:
  2480. add_package_dependency(c, "runtime", "complex64_eq");
  2481. add_package_dependency(c, "runtime", "complex64_ne");
  2482. break;
  2483. case Basic_complex128:
  2484. add_package_dependency(c, "runtime", "complex128_eq");
  2485. add_package_dependency(c, "runtime", "complex128_ne");
  2486. break;
  2487. case Basic_quaternion64:
  2488. add_package_dependency(c, "runtime", "quaternion64_eq");
  2489. add_package_dependency(c, "runtime", "quaternion64_ne");
  2490. break;
  2491. case Basic_quaternion128:
  2492. add_package_dependency(c, "runtime", "quaternion128_eq");
  2493. add_package_dependency(c, "runtime", "quaternion128_ne");
  2494. break;
  2495. case Basic_quaternion256:
  2496. add_package_dependency(c, "runtime", "quaternion256_eq");
  2497. add_package_dependency(c, "runtime", "quaternion256_ne");
  2498. break;
  2499. case Basic_cstring:
  2500. add_package_dependency(c, "runtime", "cstring_eq");
  2501. add_package_dependency(c, "runtime", "cstring_ne");
  2502. break;
  2503. case Basic_string:
  2504. add_package_dependency(c, "runtime", "string_eq");
  2505. add_package_dependency(c, "runtime", "string_ne");
  2506. break;
  2507. case Basic_cstring16:
  2508. add_package_dependency(c, "runtime", "cstring16_eq");
  2509. add_package_dependency(c, "runtime", "cstring16_ne");
  2510. break;
  2511. case Basic_string16:
  2512. add_package_dependency(c, "runtime", "string16_eq");
  2513. add_package_dependency(c, "runtime", "string16_ne");
  2514. break;
  2515. }
  2516. break;
  2517. case Type_Struct:
  2518. for (Entity *field : t->Struct.fields) {
  2519. add_comparison_procedures_for_fields(c, field->type);
  2520. }
  2521. break;
  2522. }
  2523. }
  2524. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2525. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2526. bool comp = are_types_identical(x->type, y->type);
  2527. switch (op) {
  2528. case Token_CmpEq: /* comp = comp; */ break;
  2529. case Token_NotEq: comp = !comp; break;
  2530. }
  2531. x->mode = Addressing_Constant;
  2532. x->type = t_untyped_bool;
  2533. x->value = exact_value_bool(comp);
  2534. return;
  2535. }
  2536. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2537. add_type_info_type(c, x->type);
  2538. add_type_info_type(c, y->type);
  2539. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2540. x->mode = Addressing_Value;
  2541. x->type = t_untyped_bool;
  2542. return;
  2543. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2544. add_type_info_type(c, x->type);
  2545. add_type_info_type(c, y->type);
  2546. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2547. x->mode = Addressing_Value;
  2548. x->type = t_untyped_bool;
  2549. return;
  2550. }
  2551. TEMPORARY_ALLOCATOR_GUARD();
  2552. gbString err_str = nullptr;
  2553. if (check_is_assignable_to(c, x, y->type) ||
  2554. check_is_assignable_to(c, y, x->type)) {
  2555. Type *err_type = x->type;
  2556. bool defined = false;
  2557. switch (op) {
  2558. case Token_CmpEq:
  2559. case Token_NotEq:
  2560. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2561. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2562. (is_operand_nil(*y) && type_has_nil(x->type));
  2563. break;
  2564. case Token_Lt:
  2565. case Token_Gt:
  2566. case Token_LtEq:
  2567. case Token_GtEq:
  2568. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2569. defined = true;
  2570. } else {
  2571. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2572. }
  2573. break;
  2574. }
  2575. if (!defined) {
  2576. gbString xs = type_to_string(x->type, temporary_allocator());
  2577. gbString ys = type_to_string(y->type, temporary_allocator());
  2578. if (!is_type_comparable(x->type)) {
  2579. err_str = gb_string_make(temporary_allocator(),
  2580. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2581. );
  2582. } else if (!is_type_comparable(y->type)) {
  2583. err_str = gb_string_make(temporary_allocator(),
  2584. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2585. );
  2586. } else {
  2587. err_str = gb_string_make(temporary_allocator(),
  2588. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2589. );
  2590. }
  2591. } else {
  2592. Type *comparison_type = x->type;
  2593. if (x->type == err_type && is_operand_nil(*x)) {
  2594. comparison_type = y->type;
  2595. }
  2596. add_comparison_procedures_for_fields(c, comparison_type);
  2597. }
  2598. } else {
  2599. gbString xt, yt;
  2600. if (x->mode == Addressing_ProcGroup) {
  2601. xt = gb_string_make(temporary_allocator(), "procedure group");
  2602. } else {
  2603. xt = type_to_string(x->type);
  2604. }
  2605. if (y->mode == Addressing_ProcGroup) {
  2606. yt = gb_string_make(temporary_allocator(), "procedure group");
  2607. } else {
  2608. yt = type_to_string(y->type);
  2609. }
  2610. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2611. }
  2612. if (err_str != nullptr) {
  2613. error(node, "Cannot compare expression. %s.", err_str);
  2614. x->type = t_untyped_bool;
  2615. } else {
  2616. if (x->mode == Addressing_Constant &&
  2617. y->mode == Addressing_Constant) {
  2618. if (is_type_constant_type(x->type)) {
  2619. if (is_type_bit_set(x->type)) {
  2620. switch (op) {
  2621. case Token_CmpEq:
  2622. case Token_NotEq:
  2623. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2624. break;
  2625. case Token_Lt:
  2626. case Token_LtEq:
  2627. {
  2628. ExactValue lhs = x->value;
  2629. ExactValue rhs = y->value;
  2630. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2631. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2632. if (op == Token_Lt) {
  2633. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2634. }
  2635. x->value = res;
  2636. break;
  2637. }
  2638. case Token_Gt:
  2639. case Token_GtEq:
  2640. {
  2641. ExactValue lhs = x->value;
  2642. ExactValue rhs = y->value;
  2643. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2644. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2645. if (op == Token_Gt) {
  2646. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2647. }
  2648. x->value = res;
  2649. break;
  2650. }
  2651. }
  2652. } else {
  2653. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2654. }
  2655. } else {
  2656. x->mode = Addressing_Value;
  2657. }
  2658. } else {
  2659. x->mode = Addressing_Value;
  2660. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2661. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2662. i64 size = 0;
  2663. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2664. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2665. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2666. switch (op) {
  2667. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2668. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2669. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2670. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2671. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2672. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2673. }
  2674. } else if (is_type_cstring16(x->type) && is_type_cstring16(y->type)) {
  2675. switch (op) {
  2676. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring16_eq"); break;
  2677. case Token_NotEq: add_package_dependency(c, "runtime", "cstring16_ne"); break;
  2678. case Token_Lt: add_package_dependency(c, "runtime", "cstring16_lt"); break;
  2679. case Token_Gt: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2680. case Token_LtEq: add_package_dependency(c, "runtime", "cstring16_le"); break;
  2681. case Token_GtEq: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2682. }
  2683. } else if (is_type_string16(x->type) || is_type_string16(y->type)) {
  2684. switch (op) {
  2685. case Token_CmpEq: add_package_dependency(c, "runtime", "string16_eq"); break;
  2686. case Token_NotEq: add_package_dependency(c, "runtime", "string16_ne"); break;
  2687. case Token_Lt: add_package_dependency(c, "runtime", "string16_lt"); break;
  2688. case Token_Gt: add_package_dependency(c, "runtime", "string16_gt"); break;
  2689. case Token_LtEq: add_package_dependency(c, "runtime", "string16_le"); break;
  2690. case Token_GtEq: add_package_dependency(c, "runtime", "string16_gt"); break;
  2691. }
  2692. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2693. switch (op) {
  2694. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2695. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2696. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2697. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2698. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2699. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2700. }
  2701. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2702. switch (op) {
  2703. case Token_CmpEq:
  2704. switch (8*size) {
  2705. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2706. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2707. }
  2708. break;
  2709. case Token_NotEq:
  2710. switch (8*size) {
  2711. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2712. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2713. }
  2714. break;
  2715. }
  2716. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2717. switch (op) {
  2718. case Token_CmpEq:
  2719. switch (8*size) {
  2720. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2721. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2722. }
  2723. break;
  2724. case Token_NotEq:
  2725. switch (8*size) {
  2726. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2727. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2728. }
  2729. break;
  2730. }
  2731. }
  2732. }
  2733. x->type = t_untyped_bool;
  2734. }
  2735. }
  2736. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2737. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2738. ast_node(be, BinaryExpr, node);
  2739. bool y_is_untyped = is_type_untyped(y->type);
  2740. if (y_is_untyped) {
  2741. convert_to_typed(c, y, t_untyped_integer);
  2742. if (y->mode == Addressing_Invalid) {
  2743. x->mode = Addressing_Invalid;
  2744. return;
  2745. }
  2746. } else if (!is_type_unsigned(y->type)) {
  2747. gbString y_str = expr_to_string(y->expr);
  2748. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2749. gb_string_free(y_str);
  2750. x->mode = Addressing_Invalid;
  2751. return;
  2752. }
  2753. bool x_is_untyped = is_type_untyped(x->type);
  2754. if (!(x_is_untyped || is_type_integer(x->type))) {
  2755. gbString x_str = expr_to_string(x->expr);
  2756. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2757. gb_string_free(x_str);
  2758. x->mode = Addressing_Invalid;
  2759. return;
  2760. }
  2761. if (y->mode == Addressing_Constant) {
  2762. if (big_int_is_neg(&y->value.value_integer)) {
  2763. gbString y_str = expr_to_string(y->expr);
  2764. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2765. gb_string_free(y_str);
  2766. x->mode = Addressing_Invalid;
  2767. return;
  2768. }
  2769. BigInt max_shift = {};
  2770. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2771. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2772. gbString y_str = expr_to_string(y->expr);
  2773. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2774. gb_string_free(y_str);
  2775. x->mode = Addressing_Invalid;
  2776. return;
  2777. }
  2778. if (x->mode == Addressing_Constant) {
  2779. if (x_is_untyped) {
  2780. convert_to_typed(c, x, t_untyped_integer);
  2781. if (x->mode == Addressing_Invalid) {
  2782. return;
  2783. }
  2784. x->expr = node;
  2785. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2786. return;
  2787. }
  2788. x->expr = node;
  2789. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2790. check_is_expressible(c, x, x->type);
  2791. return;
  2792. }
  2793. if (y_is_untyped) {
  2794. convert_to_typed(c, y, t_uint);
  2795. }
  2796. return;
  2797. }
  2798. if (x->mode == Addressing_Constant) {
  2799. if (x_is_untyped) {
  2800. if (type_hint) {
  2801. if (is_type_integer(type_hint)) {
  2802. convert_to_typed(c, x, type_hint);
  2803. } else if (is_type_any(type_hint)) {
  2804. convert_to_typed(c, x, default_type(t_untyped_integer));
  2805. } else {
  2806. gbString x_str = expr_to_string(x->expr);
  2807. gbString type_str = type_to_string(type_hint);
  2808. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2809. gb_string_free(x_str);
  2810. gb_string_free(type_str);
  2811. x->mode = Addressing_Invalid;
  2812. return;
  2813. }
  2814. } else {
  2815. check_is_expressible(c, x, default_type(t_untyped_integer));
  2816. }
  2817. if (x->mode == Addressing_Invalid) {
  2818. return;
  2819. }
  2820. }
  2821. x->mode = Addressing_Value;
  2822. }
  2823. }
  2824. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2825. if (check_is_assignable_to(c, operand, y)) {
  2826. return true;
  2827. }
  2828. bool is_constant = operand->mode == Addressing_Constant;
  2829. Type *x = operand->type;
  2830. Type *src = core_type(x);
  2831. Type *dst = core_type(y);
  2832. if (are_types_identical(src, dst)) {
  2833. return true;
  2834. }
  2835. // if (is_type_tuple(src)) {
  2836. // Ast *expr = unparen_expr(operand->expr);
  2837. // if (expr && expr->kind == Ast_CallExpr) {
  2838. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2839. // ast_node(ce, CallExpr, expr);
  2840. // Type *pt = base_type(type_of_expr(ce->proc));
  2841. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2842. // if (pt->Proc.result_count > 0) {
  2843. // Operand op = *operand;
  2844. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2845. // bool ok = check_is_castable_to(c, &op, y);
  2846. // if (ok) {
  2847. // ce->optional_ok_one = true;
  2848. // }
  2849. // return ok;
  2850. // }
  2851. // }
  2852. // }
  2853. // }
  2854. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2855. if (is_type_u8_array(dst)) {
  2856. String s = operand->value.value_string;
  2857. return s.len == dst->Array.count;
  2858. }
  2859. if (is_type_rune_array(dst)) {
  2860. String s = operand->value.value_string;
  2861. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2862. }
  2863. }
  2864. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2865. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2866. return dst->Array.count == src->Array.count;
  2867. }
  2868. }
  2869. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2870. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2871. }
  2872. // Cast between booleans and integers
  2873. if (is_type_boolean(src) || is_type_integer(src)) {
  2874. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2875. return true;
  2876. }
  2877. }
  2878. // Cast between numbers
  2879. if (is_type_integer(src) || is_type_float(src)) {
  2880. if (is_type_integer(dst) || is_type_float(dst)) {
  2881. return true;
  2882. }
  2883. }
  2884. if (is_type_bit_field(src)) {
  2885. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2886. }
  2887. if (is_type_bit_field(dst)) {
  2888. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2889. }
  2890. if (is_type_integer(src) && is_type_rune(dst)) {
  2891. return true;
  2892. }
  2893. if (is_type_rune(src) && is_type_integer(dst)) {
  2894. return true;
  2895. }
  2896. if (is_type_complex(src) && is_type_complex(dst)) {
  2897. return true;
  2898. }
  2899. if (is_type_float(src) && is_type_complex(dst)) {
  2900. return true;
  2901. }
  2902. if (is_type_float(src) && is_type_quaternion(dst)) {
  2903. return true;
  2904. }
  2905. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2906. return true;
  2907. }
  2908. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2909. return true;
  2910. }
  2911. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2912. GB_ASSERT(src->kind == Type_Matrix);
  2913. GB_ASSERT(dst->kind == Type_Matrix);
  2914. Operand op = *operand;
  2915. op.type = src->Matrix.elem;
  2916. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2917. return false;
  2918. }
  2919. if (src->Matrix.row_count != src->Matrix.column_count) {
  2920. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2921. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2922. return src_count == dst_count;
  2923. }
  2924. return is_matrix_square(dst) && is_matrix_square(src);
  2925. }
  2926. // Cast between pointers
  2927. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2928. return true;
  2929. }
  2930. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2931. return true;
  2932. }
  2933. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2934. return true;
  2935. }
  2936. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2937. return true;
  2938. }
  2939. // uintptr <-> pointer
  2940. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2941. return true;
  2942. }
  2943. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2944. return true;
  2945. }
  2946. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2947. return true;
  2948. }
  2949. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2950. return true;
  2951. }
  2952. // []byte/[]u8 <-> string (not cstring)
  2953. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2954. return true;
  2955. }
  2956. // []u16 <-> string16 (not cstring16)
  2957. if (is_type_u16_slice(src) && (is_type_string16(dst) && !is_type_cstring16(dst))) {
  2958. return true;
  2959. }
  2960. // cstring -> string
  2961. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2962. if (operand->mode != Addressing_Constant) {
  2963. add_package_dependency(c, "runtime", "cstring_to_string");
  2964. }
  2965. return true;
  2966. }
  2967. // cstring16 -> string16
  2968. if (are_types_identical(src, t_cstring16) && are_types_identical(dst, t_string16)) {
  2969. if (operand->mode != Addressing_Constant) {
  2970. add_package_dependency(c, "runtime", "cstring16_to_string16");
  2971. }
  2972. return true;
  2973. }
  2974. // cstring -> ^u8
  2975. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2976. return !is_constant;
  2977. }
  2978. // cstring -> [^]u8
  2979. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2980. return !is_constant;
  2981. }
  2982. // cstring -> rawptr
  2983. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2984. return !is_constant;
  2985. }
  2986. // ^u8 -> cstring
  2987. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2988. return !is_constant;
  2989. }
  2990. // [^]u8 -> cstring
  2991. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2992. return !is_constant;
  2993. }
  2994. // rawptr -> cstring
  2995. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2996. return !is_constant;
  2997. }
  2998. // cstring -> ^u16
  2999. if (are_types_identical(src, t_cstring16) && is_type_u16_ptr(dst)) {
  3000. return !is_constant;
  3001. }
  3002. // cstring -> [^]u16
  3003. if (are_types_identical(src, t_cstring16) && is_type_u16_multi_ptr(dst)) {
  3004. return !is_constant;
  3005. }
  3006. // cstring -> rawptr
  3007. if (are_types_identical(src, t_cstring16) && is_type_rawptr(dst)) {
  3008. return !is_constant;
  3009. }
  3010. // ^u16 -> cstring16
  3011. if (is_type_u16_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3012. return !is_constant;
  3013. }
  3014. // [^]u16 -> cstring
  3015. if (is_type_u16_multi_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3016. return !is_constant;
  3017. }
  3018. // rawptr -> cstring16
  3019. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring16)) {
  3020. return !is_constant;
  3021. }
  3022. // proc <-> proc
  3023. if (is_type_proc(src) && is_type_proc(dst)) {
  3024. if (is_type_polymorphic(dst)) {
  3025. if (is_type_polymorphic(src) &&
  3026. operand->mode == Addressing_Variable) {
  3027. return true;
  3028. }
  3029. return false;
  3030. }
  3031. return true;
  3032. }
  3033. // proc -> rawptr
  3034. if (is_type_proc(src) && is_type_rawptr(dst)) {
  3035. return true;
  3036. }
  3037. // rawptr -> proc
  3038. if (is_type_rawptr(src) && is_type_proc(dst)) {
  3039. return true;
  3040. }
  3041. if (is_type_array(dst)) {
  3042. Type *elem = base_array_type(dst);
  3043. if (check_is_castable_to(c, operand, elem)) {
  3044. return true;
  3045. }
  3046. }
  3047. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  3048. if (src->SimdVector.count != dst->SimdVector.count) {
  3049. return false;
  3050. }
  3051. Type *elem_src = base_array_type(src);
  3052. Type *elem_dst = base_array_type(dst);
  3053. Operand x = {};
  3054. x.type = elem_src;
  3055. x.mode = Addressing_Value;
  3056. return check_is_castable_to(c, &x, elem_dst);
  3057. }
  3058. if (is_type_simd_vector(dst)) {
  3059. Type *elem = base_array_type(dst);
  3060. if (check_is_castable_to(c, operand, elem)) {
  3061. return true;
  3062. }
  3063. }
  3064. return false;
  3065. }
  3066. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3067. bool is_const_expr = x->mode == Addressing_Constant;
  3068. Type *bt = base_type(type);
  3069. if (is_const_expr && is_type_constant_type(bt)) {
  3070. if (core_type(bt)->kind == Type_Basic) {
  3071. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3072. return true;
  3073. } else if (check_is_castable_to(c, x, type)) {
  3074. if (is_type_pointer(type)) {
  3075. return true;
  3076. }
  3077. }
  3078. } else if (check_is_castable_to(c, x, type)) {
  3079. x->value = {};
  3080. x->mode = Addressing_Value;
  3081. return true;
  3082. }
  3083. } else if (check_is_castable_to(c, x, type)) {
  3084. if (x->mode != Addressing_Constant) {
  3085. x->mode = Addressing_Value;
  3086. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3087. x->mode = Addressing_Value;
  3088. } else if (is_type_union(type)) {
  3089. x->mode = Addressing_Value;
  3090. }
  3091. if (x->mode == Addressing_Value) {
  3092. x->value = {};
  3093. }
  3094. return true;
  3095. }
  3096. return false;
  3097. }
  3098. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3099. if (!is_operand_value(*x)) {
  3100. error(x->expr, "Only values can be casted");
  3101. x->mode = Addressing_Invalid;
  3102. return;
  3103. }
  3104. bool is_const_expr = x->mode == Addressing_Constant;
  3105. bool can_convert = check_cast_internal(c, x, type);
  3106. if (!can_convert) {
  3107. TEMPORARY_ALLOCATOR_GUARD();
  3108. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3109. gbString to_type = type_to_string(type, temporary_allocator());
  3110. gbString from_type = type_to_string(x->type, temporary_allocator());
  3111. x->mode = Addressing_Invalid;
  3112. ERROR_BLOCK();
  3113. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3114. if (is_const_expr) {
  3115. gbString val_str = exact_value_to_string(x->value);
  3116. if (is_type_float(x->type) && is_type_integer(type)) {
  3117. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3118. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3119. x->mode = Addressing_Constant;
  3120. x->type = type;
  3121. } else {
  3122. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3123. if (is_type_numeric(type)) {
  3124. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3125. x->mode = Addressing_Constant;
  3126. x->type = type;
  3127. }
  3128. }
  3129. gb_string_free(val_str);
  3130. }
  3131. check_cast_error_suggestion(c, x, type);
  3132. return;
  3133. }
  3134. if (is_type_untyped(x->type)) {
  3135. Type *final_type = type;
  3136. if (is_const_expr && !is_type_constant_type(type)) {
  3137. if (is_type_union(type)) {
  3138. convert_to_typed(c, x, type);
  3139. }
  3140. final_type = default_type(x->type);
  3141. }
  3142. update_untyped_expr_type(c, x->expr, final_type, true);
  3143. } else {
  3144. Type *src = core_type(x->type);
  3145. Type *dst = core_type(type);
  3146. if (src != dst) {
  3147. bool const REQUIRE = true;
  3148. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3149. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3150. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3151. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3152. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3153. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3154. } else if (src == t_f16 && is_type_float(dst)) {
  3155. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3156. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3157. } else if (is_type_float(dst) && dst == t_f16) {
  3158. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3159. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3160. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3161. }
  3162. }
  3163. // If we check polymorphic procedures, we risk erring on
  3164. // identical casts that cannot be foreseen or otherwise
  3165. // forbidden, so just skip them.
  3166. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3167. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3168. Type *src_exact = x->type;
  3169. Type *dst_exact = type;
  3170. if (src_exact != nullptr &&
  3171. dst_exact != nullptr &&
  3172. are_types_identical(src_exact, dst_exact)
  3173. ) {
  3174. gbString oper_str = expr_to_string(x->expr);
  3175. gbString to_type = type_to_string(dst_exact);
  3176. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3177. gb_string_free(oper_str);
  3178. gb_string_free(to_type);
  3179. }
  3180. }
  3181. }
  3182. x->type = type;
  3183. }
  3184. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3185. if (!is_operand_value(*o)) {
  3186. error(o->expr, "'transmute' can only be applied to values");
  3187. o->mode = Addressing_Invalid;
  3188. return false;
  3189. }
  3190. Operand src = *o;
  3191. Type *src_t = o->type;
  3192. Type *dst_t = t;
  3193. Type *src_bt = base_type(src_t);
  3194. Type *dst_bt = base_type(dst_t);
  3195. if (is_type_untyped(src_t)) {
  3196. gbString expr_str = expr_to_string(o->expr);
  3197. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3198. gb_string_free(expr_str);
  3199. o->mode = Addressing_Invalid;
  3200. o->expr = node;
  3201. return false;
  3202. }
  3203. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3204. GB_ASSERT(global_error_collector.count != 0);
  3205. o->mode = Addressing_Invalid;
  3206. o->expr = node;
  3207. return false;
  3208. }
  3209. if (src_bt == nullptr || src_bt == t_invalid) {
  3210. // NOTE(bill): this should be an error
  3211. GB_ASSERT(global_error_collector.count != 0);
  3212. o->mode = Addressing_Value;
  3213. o->expr = node;
  3214. o->type = dst_t;
  3215. return true;
  3216. }
  3217. i64 srcz = type_size_of(src_t);
  3218. i64 dstz = type_size_of(dst_t);
  3219. if (srcz != dstz) {
  3220. gbString expr_str = expr_to_string(o->expr);
  3221. gbString type_str = type_to_string(dst_t);
  3222. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3223. gb_string_free(type_str);
  3224. gb_string_free(expr_str);
  3225. o->mode = Addressing_Invalid;
  3226. o->expr = node;
  3227. return false;
  3228. }
  3229. o->expr = node;
  3230. o->type = dst_t;
  3231. if (o->mode == Addressing_Constant) {
  3232. if (are_types_identical(src_bt, dst_bt)) {
  3233. return true;
  3234. }
  3235. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3236. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3237. if (types_have_same_internal_endian(src_t, dst_t)) {
  3238. ExactValue src_v = exact_value_to_integer(o->value);
  3239. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3240. BigInt v = src_v.value_integer;
  3241. BigInt smax = {};
  3242. BigInt umax = {};
  3243. big_int_from_u64(&smax, 0);
  3244. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3245. big_int_from_u64(&umax, 1);
  3246. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3247. big_int_shl_eq(&umax, &sz_in_bits);
  3248. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3249. if (big_int_cmp(&v, &smax) >= 0) {
  3250. big_int_sub_eq(&v, &umax);
  3251. }
  3252. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3253. if (big_int_is_neg(&v)) {
  3254. big_int_add_eq(&v, &umax);
  3255. }
  3256. }
  3257. o->value.kind = ExactValue_Integer;
  3258. o->value.value_integer = v;
  3259. return true;
  3260. }
  3261. }
  3262. } else {
  3263. // If we check polymorphic procedures, we risk erring on
  3264. // identical casts that cannot be foreseen or otherwise
  3265. // forbidden, so just skip them.
  3266. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3267. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3268. check_is_castable_to(c, &src, dst_t)) {
  3269. if (are_types_identical(src_t, dst_t)) {
  3270. gbString oper_str = expr_to_string(o->expr);
  3271. gbString to_type = type_to_string(dst_t);
  3272. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3273. gb_string_free(oper_str);
  3274. gb_string_free(to_type);
  3275. } else if (is_type_internally_pointer_like(src_t) &&
  3276. is_type_internally_pointer_like(dst_t)) {
  3277. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3278. } else if (are_types_identical(src_bt, dst_bt)) {
  3279. gbString oper_str = expr_to_string(o->expr);
  3280. gbString to_type = type_to_string(dst_t);
  3281. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3282. gb_string_free(oper_str);
  3283. gb_string_free(to_type);
  3284. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3285. types_have_same_internal_endian(src_t, dst_t) &&
  3286. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3287. gbString oper_type = type_to_string(src_t);
  3288. gbString to_type = type_to_string(dst_t);
  3289. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since both are integers of the same endianness, from '%s' to '%s'", oper_type, to_type);
  3290. gb_string_free(to_type);
  3291. gb_string_free(oper_type);
  3292. }
  3293. }
  3294. }
  3295. o->mode = Addressing_Value;
  3296. o->value = {};
  3297. return true;
  3298. }
  3299. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3300. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3301. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3302. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3303. }
  3304. }
  3305. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3306. if (check_is_assignable_to(c, y, x->type)) {
  3307. if (check_binary_op(c, x, op)) {
  3308. return true;
  3309. }
  3310. }
  3311. }
  3312. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3313. if (check_is_assignable_to(c, y, x->type)) {
  3314. if (check_binary_op(c, x, op)) {
  3315. return true;
  3316. }
  3317. }
  3318. }
  3319. return false;
  3320. }
  3321. gb_internal bool is_ise_expr(Ast *node) {
  3322. node = unparen_expr(node);
  3323. return node->kind == Ast_ImplicitSelectorExpr;
  3324. }
  3325. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3326. if (use_lhs_as_type_hint) { // RHS in this case
  3327. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3328. }
  3329. return false;
  3330. }
  3331. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3332. Type *xt = base_type(matrix);
  3333. if (type_hint != nullptr) {
  3334. Type *th = base_type(type_hint);
  3335. if (are_types_identical(th, xt)) {
  3336. return type_hint;
  3337. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3338. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3339. // ignore
  3340. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3341. xt->Matrix.column_count == th->Matrix.column_count) {
  3342. return type_hint;
  3343. }
  3344. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3345. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3346. // ignore
  3347. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3348. return type_hint;
  3349. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3350. return type_hint;
  3351. }
  3352. }
  3353. }
  3354. return matrix;
  3355. }
  3356. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3357. if (!check_binary_op(c, x, op)) {
  3358. x->mode = Addressing_Invalid;
  3359. return;
  3360. }
  3361. Type *xt = base_type(x->type);
  3362. Type *yt = base_type(y->type);
  3363. if (is_type_matrix(x->type)) {
  3364. GB_ASSERT(xt->kind == Type_Matrix);
  3365. if (op.kind == Token_Mul) {
  3366. if (yt->kind == Type_Matrix) {
  3367. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3368. goto matrix_error;
  3369. }
  3370. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3371. goto matrix_error;
  3372. }
  3373. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3374. goto matrix_error;
  3375. }
  3376. x->mode = Addressing_Value;
  3377. if (are_types_identical(xt, yt)) {
  3378. if (are_types_identical(x->type, y->type)) {
  3379. return;
  3380. }
  3381. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3382. // prefer the named type
  3383. x->type = y->type;
  3384. }
  3385. } else {
  3386. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3387. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3388. }
  3389. goto matrix_success;
  3390. } else if (yt->kind == Type_Array) {
  3391. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3392. goto matrix_error;
  3393. }
  3394. if (xt->Matrix.column_count != yt->Array.count) {
  3395. goto matrix_error;
  3396. }
  3397. // Treat arrays as column vectors
  3398. x->mode = Addressing_Value;
  3399. if (xt->Matrix.row_count == yt->Array.count) {
  3400. x->type = y->type;
  3401. } else {
  3402. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3403. }
  3404. goto matrix_success;
  3405. }
  3406. }
  3407. if (!are_types_identical(xt, yt)) {
  3408. goto matrix_error;
  3409. }
  3410. x->mode = Addressing_Value;
  3411. x->type = xt;
  3412. goto matrix_success;
  3413. } else {
  3414. GB_ASSERT(!is_type_matrix(xt));
  3415. GB_ASSERT(is_type_matrix(yt));
  3416. if (op.kind == Token_Mul) {
  3417. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3418. if (xt->kind == Type_Array) {
  3419. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3420. goto matrix_error;
  3421. }
  3422. if (xt->Array.count != yt->Matrix.row_count) {
  3423. goto matrix_error;
  3424. }
  3425. // Treat arrays as row vectors
  3426. x->mode = Addressing_Value;
  3427. if (yt->Matrix.column_count == xt->Array.count) {
  3428. x->type = x->type;
  3429. } else {
  3430. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3431. }
  3432. goto matrix_success;
  3433. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3434. x->type = check_matrix_type_hint(y->type, type_hint);
  3435. return;
  3436. }
  3437. }
  3438. if (!are_types_identical(xt, yt)) {
  3439. goto matrix_error;
  3440. }
  3441. x->mode = Addressing_Value;
  3442. x->type = xt;
  3443. goto matrix_success;
  3444. }
  3445. matrix_success:
  3446. x->type = check_matrix_type_hint(x->type, type_hint);
  3447. return;
  3448. matrix_error:
  3449. gbString xts = type_to_string(x->type);
  3450. gbString yts = type_to_string(y->type);
  3451. gbString expr_str = expr_to_string(x->expr);
  3452. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3453. gb_string_free(expr_str);
  3454. gb_string_free(yts);
  3455. gb_string_free(xts);
  3456. x->type = t_invalid;
  3457. x->mode = Addressing_Invalid;
  3458. return;
  3459. }
  3460. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3461. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3462. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3463. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3464. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3465. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3466. }
  3467. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3468. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3469. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3470. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3471. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3472. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3473. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3474. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3475. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3476. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3477. }
  3478. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3479. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3480. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3481. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3482. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3483. case Basic_u128:
  3484. case Basic_i128:
  3485. if (is_arch_wasm()) {
  3486. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3487. }
  3488. break;
  3489. }
  3490. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3491. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3492. case Basic_u128:
  3493. case Basic_i128:
  3494. if (is_arch_wasm()) {
  3495. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3496. }
  3497. break;
  3498. }
  3499. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3500. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3501. case Basic_u128:
  3502. case Basic_i128:
  3503. if (is_arch_wasm()) {
  3504. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3505. }
  3506. break;
  3507. }
  3508. }
  3509. }
  3510. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3511. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3512. Operand y_ = {}, *y = &y_;
  3513. ast_node(be, BinaryExpr, node);
  3514. defer({
  3515. node->viral_state_flags |= be->left->viral_state_flags;
  3516. node->viral_state_flags |= be->right->viral_state_flags;
  3517. });
  3518. Token op = be->op;
  3519. switch (op.kind) {
  3520. case Token_CmpEq:
  3521. case Token_NotEq: {
  3522. // NOTE(bill): Allow comparisons between types
  3523. if (is_ise_expr(be->left)) {
  3524. // Evalute the right before the left for an '.X' expression
  3525. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3526. check_expr_or_type(c, x, be->left, y->type);
  3527. } else {
  3528. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3529. check_expr_or_type(c, y, be->right, x->type);
  3530. }
  3531. bool xt = x->mode == Addressing_Type;
  3532. bool yt = y->mode == Addressing_Type;
  3533. // If only one is a type, this is an error
  3534. if (xt ^ yt) {
  3535. GB_ASSERT(xt != yt);
  3536. if (xt) {
  3537. if (!is_type_typeid(y->type)) {
  3538. error_operand_not_expression(x);
  3539. }
  3540. }
  3541. if (yt) {
  3542. if (!is_type_typeid(x->type)) {
  3543. error_operand_not_expression(y);
  3544. }
  3545. }
  3546. }
  3547. break;
  3548. }
  3549. case Token_in:
  3550. case Token_not_in:
  3551. {
  3552. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3553. check_expr(c, y, be->right);
  3554. Type *rhs_type = type_deref(y->type);
  3555. if (rhs_type == nullptr) {
  3556. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3557. x->mode = Addressing_Invalid;
  3558. x->expr = node;
  3559. return;
  3560. }
  3561. if (is_type_bit_set(rhs_type)) {
  3562. Type *elem = base_type(rhs_type)->BitSet.elem;
  3563. check_expr_with_type_hint(c, x, be->left, elem);
  3564. } else if (is_type_map(rhs_type)) {
  3565. Type *key = base_type(rhs_type)->Map.key;
  3566. check_expr_with_type_hint(c, x, be->left, key);
  3567. } else {
  3568. check_expr(c, x, be->left);
  3569. }
  3570. if (x->mode == Addressing_Invalid) {
  3571. return;
  3572. }
  3573. if (y->mode == Addressing_Invalid) {
  3574. x->mode = Addressing_Invalid;
  3575. x->expr = y->expr;
  3576. return;
  3577. }
  3578. if (is_type_map(rhs_type)) {
  3579. Type *yt = base_type(rhs_type);
  3580. if (op.kind == Token_in) {
  3581. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3582. } else {
  3583. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3584. }
  3585. add_map_get_dependencies(c);
  3586. } else if (is_type_bit_set(rhs_type)) {
  3587. Type *yt = base_type(rhs_type);
  3588. if (op.kind == Token_in) {
  3589. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3590. } else {
  3591. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3592. }
  3593. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3594. ExactValue k = exact_value_to_integer(x->value);
  3595. ExactValue v = exact_value_to_integer(y->value);
  3596. GB_ASSERT(k.kind == ExactValue_Integer);
  3597. GB_ASSERT(v.kind == ExactValue_Integer);
  3598. i64 key = big_int_to_i64(&k.value_integer);
  3599. i64 lower = yt->BitSet.lower;
  3600. i64 upper = yt->BitSet.upper;
  3601. if (lower <= key && key <= upper) {
  3602. i64 bit = 1ll<<key;
  3603. i64 bits = big_int_to_i64(&v.value_integer);
  3604. x->mode = Addressing_Constant;
  3605. x->type = t_untyped_bool;
  3606. if (op.kind == Token_in) {
  3607. x->value = exact_value_bool((bit & bits) != 0);
  3608. } else {
  3609. x->value = exact_value_bool((bit & bits) == 0);
  3610. }
  3611. x->expr = node;
  3612. return;
  3613. } else {
  3614. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3615. x->mode = Addressing_Invalid;
  3616. }
  3617. }
  3618. } else {
  3619. gbString t = type_to_string(y->type);
  3620. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3621. gb_string_free(t);
  3622. x->expr = node;
  3623. x->mode = Addressing_Invalid;
  3624. return;
  3625. }
  3626. if (x->mode != Addressing_Invalid) {
  3627. x->mode = Addressing_Value;
  3628. x->type = t_untyped_bool;
  3629. }
  3630. x->expr = node;
  3631. return;
  3632. }
  3633. default:
  3634. if (is_ise_expr(be->left)) {
  3635. // Evalute the right before the left for an '.X' expression
  3636. check_expr_or_type(c, y, be->right, type_hint);
  3637. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3638. check_expr_or_type(c, x, be->left, y->type);
  3639. } else {
  3640. check_expr_with_type_hint(c, x, be->left, type_hint);
  3641. }
  3642. } else {
  3643. check_expr_with_type_hint(c, x, be->left, type_hint);
  3644. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3645. check_expr_with_type_hint(c, y, be->right, x->type);
  3646. } else {
  3647. check_expr_with_type_hint(c, y, be->right, type_hint);
  3648. }
  3649. }
  3650. break;
  3651. }
  3652. if (x->mode == Addressing_Invalid) {
  3653. return;
  3654. }
  3655. if (y->mode == Addressing_Invalid) {
  3656. x->mode = Addressing_Invalid;
  3657. x->expr = y->expr;
  3658. return;
  3659. }
  3660. if (x->mode == Addressing_Builtin) {
  3661. x->mode = Addressing_Invalid;
  3662. error(x->expr, "built-in expression in binary expression");
  3663. return;
  3664. }
  3665. if (y->mode == Addressing_Builtin) {
  3666. x->mode = Addressing_Invalid;
  3667. error(y->expr, "built-in expression in binary expression");
  3668. return;
  3669. }
  3670. if (x->mode == Addressing_ProcGroup) {
  3671. x->mode = Addressing_Invalid;
  3672. if (x->proc_group != nullptr) {
  3673. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3674. } else {
  3675. error(x->expr, "procedure group used in binary expression");
  3676. }
  3677. return;
  3678. }
  3679. if (y->mode == Addressing_ProcGroup) {
  3680. x->mode = Addressing_Invalid;
  3681. if (x->proc_group != nullptr) {
  3682. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3683. } else {
  3684. error(y->expr, "procedure group used in binary expression");
  3685. }
  3686. return;
  3687. }
  3688. bool REQUIRE = true;
  3689. Type *btx = base_type(x->type);
  3690. Type *bty = base_type(y->type);
  3691. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3692. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3693. if (token_is_shift(op.kind)) {
  3694. check_shift(c, x, y, node, type_hint);
  3695. return;
  3696. }
  3697. switch (op.kind) {
  3698. case Token_Quo:
  3699. case Token_Mod:
  3700. case Token_ModMod:
  3701. case Token_QuoEq:
  3702. case Token_ModEq:
  3703. case Token_ModModEq:
  3704. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3705. is_type_float(x->type) && is_type_untyped(x->type)) {
  3706. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3707. gbString t = type_to_string(y->type);
  3708. if (x->value.kind != ExactValue_Invalid) {
  3709. gbString s = exact_value_to_string(x->value);
  3710. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3711. gb_string_free(s);
  3712. } else {
  3713. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3714. }
  3715. gb_string_free(t);
  3716. }
  3717. break;
  3718. }
  3719. convert_to_typed(c, x, y->type);
  3720. if (x->mode == Addressing_Invalid) {
  3721. return;
  3722. }
  3723. convert_to_typed(c, y, x->type);
  3724. if (y->mode == Addressing_Invalid) {
  3725. x->mode = Addressing_Invalid;
  3726. return;
  3727. }
  3728. if (token_is_comparison(op.kind)) {
  3729. check_comparison(c, node, x, y, op.kind);
  3730. return;
  3731. }
  3732. if (check_binary_array_expr(c, op, x, y)) {
  3733. x->mode = Addressing_Value;
  3734. x->type = x->type;
  3735. return;
  3736. }
  3737. if (check_binary_array_expr(c, op, y, x)) {
  3738. x->mode = Addressing_Value;
  3739. x->type = y->type;
  3740. return;
  3741. }
  3742. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3743. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3744. x->expr = node;
  3745. return;
  3746. }
  3747. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3748. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3749. // NOTE(bill, 2022-06-26)
  3750. // Allow any boolean types within `&&` and `||`
  3751. // This is an exception to all other binary expressions since the result
  3752. // of a comparison will always be an untyped boolean, and allowing
  3753. // any boolean between these two simplifies a lot of expressions
  3754. } else if (!are_types_identical(x->type, y->type)) {
  3755. if (x->type != t_invalid &&
  3756. y->type != t_invalid) {
  3757. gbString xt = type_to_string(x->type);
  3758. gbString yt = type_to_string(y->type);
  3759. gbString expr_str = expr_to_string(node);
  3760. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3761. gb_string_free(expr_str);
  3762. gb_string_free(yt);
  3763. gb_string_free(xt);
  3764. }
  3765. x->mode = Addressing_Invalid;
  3766. return;
  3767. }
  3768. if (!check_binary_op(c, x, op)) {
  3769. x->mode = Addressing_Invalid;
  3770. return;
  3771. }
  3772. switch (op.kind) {
  3773. case Token_Quo:
  3774. case Token_Mod:
  3775. case Token_ModMod:
  3776. case Token_QuoEq:
  3777. case Token_ModEq:
  3778. case Token_ModModEq:
  3779. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3780. y->mode == Addressing_Constant) {
  3781. bool fail = false;
  3782. switch (y->value.kind) {
  3783. case ExactValue_Integer:
  3784. if (big_int_is_zero(&y->value.value_integer)) {
  3785. fail = true;
  3786. }
  3787. break;
  3788. case ExactValue_Float:
  3789. if (y->value.value_float == 0.0) {
  3790. fail = true;
  3791. }
  3792. break;
  3793. }
  3794. if (fail) {
  3795. error(y->expr, "Division by zero not allowed");
  3796. x->mode = Addressing_Invalid;
  3797. return;
  3798. }
  3799. }
  3800. break;
  3801. case Token_CmpAnd:
  3802. case Token_CmpOr:
  3803. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3804. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3805. }
  3806. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3807. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3808. }
  3809. break;
  3810. }
  3811. if (x->mode == Addressing_Constant &&
  3812. y->mode == Addressing_Constant) {
  3813. ExactValue a = x->value;
  3814. ExactValue b = y->value;
  3815. if (!is_type_constant_type(x->type)) {
  3816. x->mode = Addressing_Value;
  3817. return;
  3818. }
  3819. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3820. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3821. }
  3822. if (is_type_bit_set(x->type)) {
  3823. switch (op.kind) {
  3824. case Token_Add: op.kind = Token_Or; break;
  3825. case Token_Sub: op.kind = Token_AndNot; break;
  3826. }
  3827. }
  3828. x->value = exact_binary_operator_value(op.kind, a, b);
  3829. if (is_type_typed(x->type)) {
  3830. if (node != nullptr) {
  3831. x->expr = node;
  3832. }
  3833. check_is_expressible(c, x, x->type);
  3834. }
  3835. return;
  3836. } else if (is_type_string(x->type)) {
  3837. error(node, "String concatenation is only allowed with constant strings");
  3838. x->mode = Addressing_Invalid;
  3839. return;
  3840. }
  3841. x->mode = Addressing_Value;
  3842. }
  3843. gb_internal Operand make_operand_from_node(Ast *node) {
  3844. GB_ASSERT(node != nullptr);
  3845. Operand x = {};
  3846. x.expr = node;
  3847. x.mode = node->tav.mode;
  3848. x.type = node->tav.type;
  3849. x.value = node->tav.value;
  3850. return x;
  3851. }
  3852. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3853. GB_ASSERT(e != nullptr);
  3854. ExprInfo *old = check_get_expr_info(c, e);
  3855. if (old == nullptr) {
  3856. if (type != nullptr && type != t_invalid) {
  3857. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3858. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3859. if (e->kind == Ast_TernaryIfExpr) {
  3860. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3861. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3862. }
  3863. }
  3864. }
  3865. return;
  3866. }
  3867. switch (e->kind) {
  3868. case_ast_node(ue, UnaryExpr, e);
  3869. if (old->value.kind != ExactValue_Invalid) {
  3870. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3871. // They don't need to be updated as they will be updated later and
  3872. // checked at the end of general checking stage.
  3873. break;
  3874. }
  3875. update_untyped_expr_type(c, ue->expr, type, final);
  3876. case_end;
  3877. case_ast_node(be, BinaryExpr, e);
  3878. if (old->value.kind != ExactValue_Invalid) {
  3879. // See above note in UnaryExpr case
  3880. break;
  3881. }
  3882. if (token_is_comparison(be->op.kind)) {
  3883. // NOTE(bill): Do nothing as the types are fine
  3884. } else if (token_is_shift(be->op.kind)) {
  3885. update_untyped_expr_type(c, be->left, type, final);
  3886. } else {
  3887. update_untyped_expr_type(c, be->left, type, final);
  3888. update_untyped_expr_type(c, be->right, type, final);
  3889. }
  3890. case_end;
  3891. case_ast_node(te, TernaryIfExpr, e);
  3892. if (old->value.kind != ExactValue_Invalid) {
  3893. // See above note in UnaryExpr case
  3894. break;
  3895. }
  3896. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3897. // having an untyped value
  3898. Operand x = make_operand_from_node(te->x);
  3899. Operand y = make_operand_from_node(te->y);
  3900. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3901. update_untyped_expr_type(c, te->x, type, final);
  3902. }
  3903. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3904. update_untyped_expr_type(c, te->y, type, final);
  3905. }
  3906. case_end;
  3907. case_ast_node(te, TernaryWhenExpr, e);
  3908. if (old->value.kind != ExactValue_Invalid) {
  3909. // See above note in UnaryExpr case
  3910. break;
  3911. }
  3912. update_untyped_expr_type(c, te->x, type, final);
  3913. update_untyped_expr_type(c, te->y, type, final);
  3914. case_end;
  3915. case_ast_node(ore, OrReturnExpr, e);
  3916. if (old->value.kind != ExactValue_Invalid) {
  3917. // See above note in UnaryExpr case
  3918. break;
  3919. }
  3920. update_untyped_expr_type(c, ore->expr, type, final);
  3921. case_end;
  3922. case_ast_node(obe, OrBranchExpr, e);
  3923. if (old->value.kind != ExactValue_Invalid) {
  3924. // See above note in UnaryExpr case
  3925. break;
  3926. }
  3927. update_untyped_expr_type(c, obe->expr, type, final);
  3928. case_end;
  3929. case_ast_node(oee, OrElseExpr, e);
  3930. if (old->value.kind != ExactValue_Invalid) {
  3931. // See above note in UnaryExpr case
  3932. break;
  3933. }
  3934. update_untyped_expr_type(c, oee->x, type, final);
  3935. update_untyped_expr_type(c, oee->y, type, final);
  3936. case_end;
  3937. case_ast_node(pe, ParenExpr, e);
  3938. update_untyped_expr_type(c, pe->expr, type, final);
  3939. case_end;
  3940. }
  3941. if (!final && is_type_untyped(type)) {
  3942. old->type = base_type(type);
  3943. return;
  3944. }
  3945. // We need to remove it and then give it a new one
  3946. check_remove_expr_info(c, e);
  3947. if (old->is_lhs && !is_type_integer(type)) {
  3948. gbString expr_str = expr_to_string(e);
  3949. gbString type_str = type_to_string(type);
  3950. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3951. gb_string_free(type_str);
  3952. gb_string_free(expr_str);
  3953. return;
  3954. }
  3955. add_type_and_value(c, e, old->mode, type, old->value);
  3956. }
  3957. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3958. GB_ASSERT(e != nullptr);
  3959. ExprInfo *found = check_get_expr_info(c, e);
  3960. if (found) {
  3961. found->value = value;
  3962. }
  3963. }
  3964. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3965. gbString expr_str = expr_to_string(operand->expr);
  3966. gbString type_str = type_to_string(target_type);
  3967. gbString from_type_str = type_to_string(operand->type);
  3968. char const *extra_text = "";
  3969. if (operand->mode == Addressing_Constant) {
  3970. if (big_int_is_zero(&operand->value.value_integer)) {
  3971. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3972. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3973. extra_text = " - Did you want 'nil'?";
  3974. }
  3975. }
  3976. }
  3977. if (!ignore_error_block) {
  3978. begin_error_block();
  3979. }
  3980. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3981. if (operand->value.kind == ExactValue_String) {
  3982. String key = operand->value.value_string;
  3983. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3984. Type *et = base_type(target_type);
  3985. check_did_you_mean_type(key, et->Enum.fields, ".");
  3986. }
  3987. }
  3988. gb_string_free(from_type_str);
  3989. gb_string_free(type_str);
  3990. gb_string_free(expr_str);
  3991. operand->mode = Addressing_Invalid;
  3992. if (!ignore_error_block) {
  3993. end_error_block();
  3994. }
  3995. }
  3996. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3997. Type *t = core_type(type);
  3998. if (is_type_boolean(t)) {
  3999. // v = exact_value_to_boolean(v);
  4000. } else if (is_type_float(t)) {
  4001. v = exact_value_to_float(v);
  4002. } else if (is_type_integer(t)) {
  4003. v = exact_value_to_integer(v);
  4004. } else if (is_type_pointer(t)) {
  4005. v = exact_value_to_integer(v);
  4006. } else if (is_type_complex(t)) {
  4007. v = exact_value_to_complex(v);
  4008. } else if (is_type_quaternion(t)) {
  4009. v = exact_value_to_quaternion(v);
  4010. }
  4011. return v;
  4012. }
  4013. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  4014. // GB_ASSERT_NOT_NULL(target_type);
  4015. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  4016. operand->mode == Addressing_Type ||
  4017. is_type_typed(operand->type) ||
  4018. target_type == t_invalid) {
  4019. return;
  4020. }
  4021. if (is_type_untyped(target_type)) {
  4022. GB_ASSERT(operand->type->kind == Type_Basic);
  4023. GB_ASSERT(target_type->kind == Type_Basic);
  4024. BasicKind x_kind = operand->type->Basic.kind;
  4025. BasicKind y_kind = target_type->Basic.kind;
  4026. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  4027. if (x_kind < y_kind) {
  4028. operand->type = target_type;
  4029. update_untyped_expr_type(c, operand->expr, target_type, false);
  4030. }
  4031. } else if (x_kind != y_kind) {
  4032. operand->mode = Addressing_Invalid;
  4033. convert_untyped_error(c, operand, target_type);
  4034. return;
  4035. }
  4036. return;
  4037. }
  4038. Type *t = base_type(target_type);
  4039. if (c->in_enum_type) {
  4040. t = core_type(target_type);
  4041. }
  4042. switch (t->kind) {
  4043. case Type_Basic:
  4044. if (operand->mode == Addressing_Constant) {
  4045. check_is_expressible(c, operand, t);
  4046. if (operand->mode == Addressing_Invalid) {
  4047. return;
  4048. }
  4049. update_untyped_expr_value(c, operand->expr, operand->value);
  4050. } else {
  4051. switch (operand->type->Basic.kind) {
  4052. case Basic_UntypedBool:
  4053. if (!is_type_boolean(target_type)) {
  4054. operand->mode = Addressing_Invalid;
  4055. convert_untyped_error(c, operand, target_type);
  4056. return;
  4057. }
  4058. break;
  4059. case Basic_UntypedInteger:
  4060. case Basic_UntypedFloat:
  4061. case Basic_UntypedComplex:
  4062. case Basic_UntypedQuaternion:
  4063. case Basic_UntypedRune:
  4064. if (!is_type_numeric(target_type)) {
  4065. operand->mode = Addressing_Invalid;
  4066. convert_untyped_error(c, operand, target_type);
  4067. return;
  4068. }
  4069. break;
  4070. case Basic_UntypedNil:
  4071. if (is_type_any(target_type)) {
  4072. // target_type = t_untyped_nil;
  4073. } else if (is_type_cstring(target_type)) {
  4074. // target_type = t_untyped_nil;
  4075. } else if (is_type_cstring16(target_type)) {
  4076. // target_type = t_untyped_nil;
  4077. } else if (!type_has_nil(target_type)) {
  4078. operand->mode = Addressing_Invalid;
  4079. convert_untyped_error(c, operand, target_type);
  4080. return;
  4081. }
  4082. break;
  4083. }
  4084. }
  4085. break;
  4086. case Type_Array: {
  4087. Type *elem = base_array_type(t);
  4088. if (check_is_assignable_to(c, operand, elem)) {
  4089. operand->mode = Addressing_Value;
  4090. } else {
  4091. if (operand->value.kind == ExactValue_String) {
  4092. String s = operand->value.value_string;
  4093. if (is_type_u8_array(t)) {
  4094. if (s.len == t->Array.count) {
  4095. break;
  4096. }
  4097. } else if (is_type_rune_array(t)) {
  4098. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4099. if (rune_count == t->Array.count) {
  4100. break;
  4101. }
  4102. }
  4103. } else if (operand->value.kind == ExactValue_String16) {
  4104. String16 s = operand->value.value_string16;
  4105. if (is_type_u16_array(t)) {
  4106. if (s.len == t->Array.count) {
  4107. break;
  4108. }
  4109. }
  4110. }
  4111. operand->mode = Addressing_Invalid;
  4112. convert_untyped_error(c, operand, target_type);
  4113. return;
  4114. }
  4115. break;
  4116. }
  4117. case Type_SimdVector: {
  4118. Type *elem = base_array_type(t);
  4119. if (check_is_assignable_to(c, operand, elem)) {
  4120. operand->mode = Addressing_Value;
  4121. } else {
  4122. operand->mode = Addressing_Invalid;
  4123. convert_untyped_error(c, operand, target_type);
  4124. return;
  4125. }
  4126. break;
  4127. }
  4128. case Type_Matrix: {
  4129. Type *elem = base_array_type(t);
  4130. if (check_is_assignable_to(c, operand, elem)) {
  4131. if (t->Matrix.row_count != t->Matrix.column_count) {
  4132. operand->mode = Addressing_Invalid;
  4133. ERROR_BLOCK();
  4134. convert_untyped_error(c, operand, target_type, true);
  4135. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4136. return;
  4137. } else {
  4138. operand->mode = Addressing_Value;
  4139. }
  4140. } else {
  4141. operand->mode = Addressing_Invalid;
  4142. convert_untyped_error(c, operand, target_type);
  4143. return;
  4144. }
  4145. break;
  4146. }
  4147. case Type_Union:
  4148. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4149. // as a kind of transition period
  4150. if (!build_context.strict_style &&
  4151. operand->mode == Addressing_Constant &&
  4152. target_type->kind == Type_Named &&
  4153. (c->pkg == nullptr || c->pkg->name != "os") &&
  4154. target_type->Named.name == "Error") {
  4155. Entity *e = target_type->Named.type_name;
  4156. if (e->pkg && e->pkg->name == "os") {
  4157. if (is_exact_value_zero(operand->value) &&
  4158. (operand->value.kind == ExactValue_Integer ||
  4159. operand->value.kind == ExactValue_Float)) {
  4160. operand->mode = Addressing_Value;
  4161. // target_type = t_untyped_nil;
  4162. operand->value = empty_exact_value;
  4163. update_untyped_expr_value(c, operand->expr, operand->value);
  4164. break;
  4165. }
  4166. }
  4167. }
  4168. // "fallthrough"
  4169. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4170. TEMPORARY_ALLOCATOR_GUARD();
  4171. isize count = t->Union.variants.count;
  4172. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4173. isize valid_count = 0;
  4174. isize first_success_index = -1;
  4175. for_array(i, t->Union.variants) {
  4176. Type *vt = t->Union.variants[i];
  4177. i64 score = 0;
  4178. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4179. valids[valid_count].index = i;
  4180. valids[valid_count].score = score;
  4181. valid_count += 1;
  4182. if (first_success_index < 0) {
  4183. first_success_index = i;
  4184. }
  4185. }
  4186. }
  4187. if (valid_count > 1) {
  4188. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4189. i64 best_score = valids[0].score;
  4190. for (isize i = 1; i < valid_count; i++) {
  4191. auto v = valids[i];
  4192. if (best_score > v.score) {
  4193. valid_count = i;
  4194. break;
  4195. }
  4196. best_score = v.score;
  4197. }
  4198. first_success_index = valids[0].index;
  4199. }
  4200. gbString type_str = type_to_string(target_type);
  4201. defer (gb_string_free(type_str));
  4202. if (valid_count == 1) {
  4203. Type *new_type = t->Union.variants[first_success_index];
  4204. target_type = new_type;
  4205. if (is_type_union(new_type)) {
  4206. convert_to_typed(c, operand, new_type);
  4207. break;
  4208. }
  4209. operand->type = new_type;
  4210. operand->mode = Addressing_Value;
  4211. break;
  4212. } else if (valid_count > 1) {
  4213. ERROR_BLOCK();
  4214. GB_ASSERT(first_success_index >= 0);
  4215. operand->mode = Addressing_Invalid;
  4216. convert_untyped_error(c, operand, target_type, true);
  4217. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4218. i32 j = 0;
  4219. for (i32 i = 0; i < valid_count; i++) {
  4220. ValidIndexAndScore valid = valids[i];
  4221. if (j > 0 && valid_count > 2) error_line(", ");
  4222. if (j == valid_count-1) {
  4223. if (valid_count == 2) error_line(" ");
  4224. error_line("or ");
  4225. }
  4226. gbString str = type_to_string(t->Union.variants[valid.index]);
  4227. error_line("'%s'", str);
  4228. gb_string_free(str);
  4229. j++;
  4230. }
  4231. error_line("\n\n");
  4232. return;
  4233. } else if (is_type_untyped_uninit(operand->type)) {
  4234. target_type = t_untyped_uninit;
  4235. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4236. ERROR_BLOCK();
  4237. operand->mode = Addressing_Invalid;
  4238. convert_untyped_error(c, operand, target_type, true);
  4239. if (count > 0) {
  4240. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4241. error_line("\t");
  4242. for (i32 i = 0; i < count; i++) {
  4243. Type *v = t->Union.variants[i];
  4244. if (i > 0 && count > 2) error_line(", ");
  4245. if (i == count-1) {
  4246. if (count == 2) error_line(" ");
  4247. if (count > 1) {
  4248. error_line("or ");
  4249. }
  4250. }
  4251. gbString str = type_to_string(v);
  4252. error_line("'%s'", str);
  4253. gb_string_free(str);
  4254. }
  4255. error_line("\n\n");
  4256. }
  4257. return;
  4258. }
  4259. }
  4260. /* fallthrough */
  4261. default:
  4262. if (is_type_untyped_uninit(operand->type)) {
  4263. target_type = t_untyped_uninit;
  4264. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4265. target_type = t_untyped_nil;
  4266. } else {
  4267. operand->mode = Addressing_Invalid;
  4268. convert_untyped_error(c, operand, target_type);
  4269. return;
  4270. }
  4271. break;
  4272. }
  4273. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4274. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4275. } else {
  4276. target_type = default_type(operand->type);
  4277. }
  4278. }
  4279. update_untyped_expr_type(c, operand->expr, target_type, true);
  4280. operand->type = target_type;
  4281. }
  4282. 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) {
  4283. Operand operand = {Addressing_Invalid};
  4284. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4285. if (operand.mode == Addressing_Invalid) {
  4286. if (value) *value = 0;
  4287. // NOTE(bill): return true here to propagate the errors better
  4288. return true;
  4289. }
  4290. Type *index_type = t_int;
  4291. if (type_hint != nullptr) {
  4292. index_type = type_hint;
  4293. }
  4294. convert_to_typed(c, &operand, index_type);
  4295. if (operand.mode == Addressing_Invalid) {
  4296. if (value) *value = 0;
  4297. return false;
  4298. }
  4299. if (type_hint != nullptr) {
  4300. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4301. gbString expr_str = expr_to_string(operand.expr);
  4302. gbString index_type_str = type_to_string(type_hint);
  4303. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4304. gb_string_free(index_type_str);
  4305. gb_string_free(expr_str);
  4306. if (value) *value = 0;
  4307. return false;
  4308. }
  4309. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4310. gbString expr_str = expr_to_string(operand.expr);
  4311. gbString type_str = type_to_string(operand.type);
  4312. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4313. gb_string_free(type_str);
  4314. gb_string_free(expr_str);
  4315. if (value) *value = 0;
  4316. return false;
  4317. }
  4318. if (operand.mode == Addressing_Constant &&
  4319. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4320. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4321. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4322. TEMPORARY_ALLOCATOR_GUARD();
  4323. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4324. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4325. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4326. if (value) *value = 0;
  4327. return false;
  4328. }
  4329. if (max_count >= 0) {
  4330. if (is_type_enum(index_type)) {
  4331. Type *bt = base_type(index_type);
  4332. GB_ASSERT(bt->kind == Type_Enum);
  4333. ExactValue const &lo = *bt->Enum.min_value;
  4334. ExactValue const &hi = *bt->Enum.max_value;
  4335. String lo_str = {};
  4336. String hi_str = {};
  4337. if (bt->Enum.fields.count > 0) {
  4338. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4339. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4340. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4341. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4342. }
  4343. bool out_of_bounds = false;
  4344. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4345. out_of_bounds = true;
  4346. }
  4347. if (out_of_bounds) {
  4348. gbString expr_str = expr_to_string(operand.expr);
  4349. if (lo_str.len > 0) {
  4350. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4351. } else {
  4352. gbString index_type_str = type_to_string(index_type);
  4353. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4354. gb_string_free(index_type_str);
  4355. }
  4356. gb_string_free(expr_str);
  4357. return false;
  4358. }
  4359. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4360. return true;
  4361. } else { // NOTE(bill): Do array bound checking
  4362. i64 v = -1;
  4363. if (i.used <= 1) {
  4364. v = big_int_to_i64(&i);
  4365. }
  4366. if (value) *value = v;
  4367. bool out_of_bounds = false;
  4368. if (v < 0) {
  4369. out_of_bounds = true;
  4370. } else if (open_range) {
  4371. out_of_bounds = v > max_count;
  4372. } else {
  4373. out_of_bounds = v >= max_count;
  4374. }
  4375. if (out_of_bounds) {
  4376. TEMPORARY_ALLOCATOR_GUARD();
  4377. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4378. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4379. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4380. return false;
  4381. }
  4382. return true;
  4383. }
  4384. } else {
  4385. if (value) *value = exact_value_to_i64(operand.value);
  4386. return true;
  4387. }
  4388. }
  4389. // NOTE(bill): It's alright :D
  4390. if (value) *value = -1;
  4391. return true;
  4392. }
  4393. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4394. if (value.kind == ExactValue_String) {
  4395. GB_ASSERT(0 <= index && index < value.value_string.len);
  4396. u8 val = value.value_string[index];
  4397. if (success_) *success_ = true;
  4398. if (finish_) *finish_ = true;
  4399. return exact_value_u64(val);
  4400. } else if (value.kind == ExactValue_String16) {
  4401. GB_ASSERT(0 <= index && index < value.value_string.len);
  4402. u16 val = value.value_string16[index];
  4403. if (success_) *success_ = true;
  4404. if (finish_) *finish_ = true;
  4405. return exact_value_u64(val);
  4406. }
  4407. if (value.kind != ExactValue_Compound) {
  4408. if (success_) *success_ = true;
  4409. if (finish_) *finish_ = true;
  4410. return value;
  4411. }
  4412. Ast *node = value.value_compound;
  4413. switch (node->kind) {
  4414. case_ast_node(cl, CompoundLit, node);
  4415. if (cl->elems.count == 0) {
  4416. if (success_) *success_ = true;
  4417. if (finish_) *finish_ = true;
  4418. return empty_exact_value;
  4419. }
  4420. if (cl->elems[0]->kind == Ast_FieldValue) {
  4421. if (is_type_struct(node->tav.type)) {
  4422. bool found = false;
  4423. for (Ast *elem : cl->elems) {
  4424. if (elem->kind != Ast_FieldValue) {
  4425. continue;
  4426. }
  4427. ast_node(fv, FieldValue, elem);
  4428. String name = fv->field->Ident.token.string;
  4429. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4430. defer (array_free(&sub_sel.index));
  4431. if (sub_sel.index.count > 0 &&
  4432. sub_sel.index[0] == index) {
  4433. value = fv->value->tav.value;
  4434. found = true;
  4435. break;
  4436. }
  4437. }
  4438. if (!found) {
  4439. // Use the zero value if it is not found
  4440. value = {};
  4441. }
  4442. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4443. for (Ast *elem : cl->elems) {
  4444. if (elem->kind != Ast_FieldValue) {
  4445. continue;
  4446. }
  4447. ast_node(fv, FieldValue, elem);
  4448. if (is_ast_range(fv->field)) {
  4449. ast_node(ie, BinaryExpr, fv->field);
  4450. TypeAndValue lo_tav = ie->left->tav;
  4451. TypeAndValue hi_tav = ie->right->tav;
  4452. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4453. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4454. TokenKind op = ie->op.kind;
  4455. i64 lo = exact_value_to_i64(lo_tav.value);
  4456. i64 hi = exact_value_to_i64(hi_tav.value);
  4457. i64 corrected_index = index;
  4458. if (is_type_enumerated_array(node->tav.type)) {
  4459. Type *bt = base_type(node->tav.type);
  4460. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4461. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4462. }
  4463. if (op != Token_RangeHalf) {
  4464. if (lo <= corrected_index && corrected_index <= hi) {
  4465. TypeAndValue tav = fv->value->tav;
  4466. if (success_) *success_ = true;
  4467. if (finish_) *finish_ = false;
  4468. return tav.value;
  4469. }
  4470. } else {
  4471. if (lo <= corrected_index && corrected_index < hi) {
  4472. TypeAndValue tav = fv->value->tav;
  4473. if (success_) *success_ = true;
  4474. if (finish_) *finish_ = false;
  4475. return tav.value;
  4476. }
  4477. }
  4478. } else {
  4479. TypeAndValue index_tav = fv->field->tav;
  4480. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4481. ExactValue index_value = index_tav.value;
  4482. if (is_type_enumerated_array(node->tav.type)) {
  4483. Type *bt = base_type(node->tav.type);
  4484. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4485. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4486. }
  4487. i64 field_index = exact_value_to_i64(index_value);
  4488. if (index == field_index) {
  4489. TypeAndValue tav = fv->value->tav;
  4490. if (success_) *success_ = true;
  4491. if (finish_) *finish_ = false;
  4492. return tav.value;
  4493. }
  4494. }
  4495. }
  4496. }
  4497. } else {
  4498. i32 count = (i32)cl->elems.count;
  4499. if (count < index) {
  4500. if (success_) *success_ = false;
  4501. if (finish_) *finish_ = true;
  4502. return empty_exact_value;
  4503. }
  4504. if (cl->elems.count <= index) {
  4505. if (success_) *success_ = false;
  4506. if (finish_) *finish_ = false;
  4507. return value;
  4508. }
  4509. TypeAndValue tav = cl->elems[index]->tav;
  4510. if (tav.mode == Addressing_Constant) {
  4511. if (success_) *success_ = true;
  4512. if (finish_) *finish_ = false;
  4513. return tav.value;
  4514. } else if (is_type_proc(tav.type)) {
  4515. if (success_) *success_ = true;
  4516. if (finish_) *finish_ = false;
  4517. return tav.value;
  4518. } else {
  4519. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4520. if (success_) *success_ = true;
  4521. if (finish_) *finish_ = false;
  4522. return tav.value;
  4523. }
  4524. }
  4525. case_end;
  4526. default:
  4527. if (success_) *success_ = true;
  4528. if (finish_) *finish_ = true;
  4529. return empty_exact_value;
  4530. }
  4531. if (finish_) *finish_ = false;
  4532. return value;
  4533. }
  4534. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4535. if (operand->mode != Addressing_Constant) {
  4536. if (success_) *success_ = false;
  4537. return empty_exact_value;
  4538. }
  4539. if (sel.indirect) {
  4540. if (success_) *success_ = false;
  4541. return empty_exact_value;
  4542. }
  4543. if (sel.index.count == 0) {
  4544. if (success_) *success_ = false;
  4545. return empty_exact_value;
  4546. }
  4547. ExactValue value = operand->value;
  4548. if (value.kind == ExactValue_Compound) {
  4549. while (sel.index.count > 0) {
  4550. i32 index = sel.index[0];
  4551. sel = sub_selection(sel, 1);
  4552. bool finish = false;
  4553. value = get_constant_field_single(c, value, index, success_, &finish);
  4554. if (finish) {
  4555. return value;
  4556. }
  4557. }
  4558. if (success_) *success_ = true;
  4559. return value;
  4560. } else if (value.kind == ExactValue_Quaternion) {
  4561. // @QuaternionLayout
  4562. Quaternion256 q = *value.value_quaternion;
  4563. GB_ASSERT(sel.index.count == 1);
  4564. switch (sel.index[0]) {
  4565. case 3: // w
  4566. if (success_) *success_ = true;
  4567. return exact_value_float(q.real);
  4568. case 0: // x
  4569. if (success_) *success_ = true;
  4570. return exact_value_float(q.imag);
  4571. case 1: // y
  4572. if (success_) *success_ = true;
  4573. return exact_value_float(q.jmag);
  4574. case 2: // z
  4575. if (success_) *success_ = true;
  4576. return exact_value_float(q.kmag);
  4577. }
  4578. if (success_) *success_ = false;
  4579. return empty_exact_value;
  4580. } else if (value.kind == ExactValue_Complex) {
  4581. // @QuaternionLayout
  4582. Complex128 c = *value.value_complex;
  4583. GB_ASSERT(sel.index.count == 1);
  4584. switch (sel.index[0]) {
  4585. case 0: // real
  4586. if (success_) *success_ = true;
  4587. return exact_value_float(c.real);
  4588. case 1: // imag
  4589. if (success_) *success_ = true;
  4590. return exact_value_float(c.imag);
  4591. }
  4592. if (success_) *success_ = false;
  4593. return empty_exact_value;
  4594. }
  4595. if (success_) *success_ = true;
  4596. return empty_exact_value;
  4597. }
  4598. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4599. Type *array_type = base_type(type_deref(original_type));
  4600. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4601. if (array_type->kind == Type_SimdVector) {
  4602. Type *elem_type = array_type->SimdVector.elem;
  4603. return alloc_type_simd_vector(new_count, elem_type);
  4604. }
  4605. Type *elem_type = array_type->Array.elem;
  4606. Type *swizzle_array_type = nullptr;
  4607. Type *bth = base_type(type_deref(type_hint));
  4608. if (bth != nullptr && bth->kind == Type_Array &&
  4609. bth->Array.count == new_count &&
  4610. are_types_identical(bth->Array.elem, elem_type)) {
  4611. swizzle_array_type = type_hint;
  4612. } else {
  4613. i64 max_count = array_type->Array.count;
  4614. if (new_count == max_count) {
  4615. swizzle_array_type = original_type;
  4616. } else {
  4617. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4618. }
  4619. }
  4620. return swizzle_array_type;
  4621. }
  4622. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4623. bool is_declared = entity != nullptr;
  4624. if (is_declared) {
  4625. if (entity->kind == Entity_Builtin) {
  4626. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4627. // This means that we should just ignore the found result through it
  4628. *allow_builtin = entity->scope == import_scope ||
  4629. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4630. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4631. is_declared = false;
  4632. }
  4633. }
  4634. return is_declared;
  4635. }
  4636. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4637. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4638. if (node == nullptr) {
  4639. return nullptr;
  4640. }
  4641. /*if (node->kind == Ast_TernaryWhenExpr) {
  4642. ast_node(we, TernaryWhenExpr, node);
  4643. if (we->cond == nullptr) {
  4644. return nullptr;
  4645. }
  4646. if (we->cond->tav.mode != Addressing_Constant) {
  4647. return nullptr;
  4648. }
  4649. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4650. return nullptr;
  4651. }
  4652. if (we->cond->tav.value.value_bool) {
  4653. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4654. } else {
  4655. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4656. return e;
  4657. }
  4658. } else */if (node->kind == Ast_Ident) {
  4659. String name = node->Ident.token.string;
  4660. return scope_lookup(c->scope, name);
  4661. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4662. ast_node(se, SelectorExpr, node);
  4663. if (se->token.kind == Token_ArrowRight) {
  4664. return nullptr;
  4665. }
  4666. Ast *op_expr = se->expr;
  4667. Ast *selector = unparen_expr(se->selector);
  4668. if (selector == nullptr) {
  4669. return nullptr;
  4670. }
  4671. if (selector->kind != Ast_Ident) {
  4672. return nullptr;
  4673. }
  4674. Entity *entity = nullptr;
  4675. Entity *expr_entity = nullptr;
  4676. bool check_op_expr = true;
  4677. if (op_expr->kind == Ast_Ident) {
  4678. String op_name = op_expr->Ident.token.string;
  4679. Entity *e = scope_lookup(c->scope, op_name);
  4680. if (e == nullptr) {
  4681. return nullptr;
  4682. }
  4683. add_entity_use(c, op_expr, e);
  4684. expr_entity = e;
  4685. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4686. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4687. // It pretty much needs to be in this order and this way
  4688. // If you can clean this up, please do but be really careful
  4689. String import_name = op_name;
  4690. Scope *import_scope = e->ImportName.scope;
  4691. String entity_name = selector->Ident.token.string;
  4692. check_op_expr = false;
  4693. entity = scope_lookup_current(import_scope, entity_name);
  4694. bool allow_builtin = false;
  4695. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4696. return nullptr;
  4697. }
  4698. check_entity_decl(c, entity, nullptr, nullptr);
  4699. if (entity->kind == Entity_ProcGroup) {
  4700. return entity;
  4701. }
  4702. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4703. }
  4704. }
  4705. Operand operand = {};
  4706. if (check_op_expr) {
  4707. check_expr_base(c, &operand, op_expr, nullptr);
  4708. if (operand.mode == Addressing_Invalid) {
  4709. return nullptr;
  4710. }
  4711. }
  4712. if (entity == nullptr && selector->kind == Ast_Ident) {
  4713. String field_name = selector->Ident.token.string;
  4714. if (is_type_dynamic_array(type_deref(operand.type))) {
  4715. init_mem_allocator(c->checker);
  4716. }
  4717. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4718. entity = sel.entity;
  4719. }
  4720. if (entity != nullptr) {
  4721. return entity;
  4722. }
  4723. }
  4724. return nullptr;
  4725. }
  4726. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4727. ast_node(se, SelectorExpr, node);
  4728. bool check_op_expr = true;
  4729. Entity *expr_entity = nullptr;
  4730. Entity *entity = nullptr;
  4731. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4732. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4733. ERROR_BLOCK();
  4734. error(node, "Illegal use of -> selector shorthand outside of a call");
  4735. gbString x = expr_to_string(se->expr);
  4736. gbString y = expr_to_string(se->selector);
  4737. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4738. gb_string_free(y);
  4739. gb_string_free(x);
  4740. // TODO(bill): Should this terminate here or propagate onwards?
  4741. // operand->mode = Addressing_Invalid;
  4742. // operand->expr = node;
  4743. // return nullptr;
  4744. }
  4745. operand->expr = node;
  4746. Ast *op_expr = se->expr;
  4747. Ast *selector = unparen_expr(se->selector);
  4748. if (selector == nullptr) {
  4749. operand->mode = Addressing_Invalid;
  4750. operand->expr = node;
  4751. return nullptr;
  4752. }
  4753. if (selector->kind != Ast_Ident) {
  4754. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4755. operand->mode = Addressing_Invalid;
  4756. operand->expr = node;
  4757. return nullptr;
  4758. }
  4759. if (op_expr->kind == Ast_Ident) {
  4760. String op_name = op_expr->Ident.token.string;
  4761. Entity *e = scope_lookup(c->scope, op_name);
  4762. add_entity_use(c, op_expr, e);
  4763. expr_entity = e;
  4764. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4765. gbString sel_str = expr_to_string(selector);
  4766. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4767. gb_string_free(sel_str);
  4768. operand->mode = Addressing_Invalid;
  4769. operand->expr = node;
  4770. return nullptr;
  4771. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4772. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4773. // It pretty much needs to be in this order and this way
  4774. // If you can clean this up, please do but be really careful
  4775. String import_name = op_name;
  4776. Scope *import_scope = e->ImportName.scope;
  4777. String entity_name = selector->Ident.token.string;
  4778. if (import_scope == nullptr) {
  4779. ERROR_BLOCK();
  4780. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4781. operand->mode = Addressing_Invalid;
  4782. operand->expr = node;
  4783. return nullptr;
  4784. }
  4785. check_op_expr = false;
  4786. entity = scope_lookup_current(import_scope, entity_name);
  4787. bool allow_builtin = false;
  4788. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4789. ERROR_BLOCK();
  4790. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4791. operand->mode = Addressing_Invalid;
  4792. operand->expr = node;
  4793. check_did_you_mean_scope(entity_name, import_scope);
  4794. return nullptr;
  4795. }
  4796. if (!is_entity_exported(entity, allow_builtin)) {
  4797. gbString sel_str = expr_to_string(selector);
  4798. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4799. gb_string_free(sel_str);
  4800. // NOTE(bill): make the state valid still, even if it's "invalid"
  4801. // operand->mode = Addressing_Invalid;
  4802. // operand->expr = node;
  4803. // return nullptr;
  4804. }
  4805. check_entity_decl(c, entity, nullptr, nullptr);
  4806. if (entity->kind == Entity_ProcGroup) {
  4807. operand->mode = Addressing_ProcGroup;
  4808. operand->proc_group = entity;
  4809. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4810. return entity;
  4811. }
  4812. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4813. }
  4814. }
  4815. if (check_op_expr) {
  4816. check_expr_base(c, operand, op_expr, nullptr);
  4817. if (operand->mode == Addressing_Invalid) {
  4818. operand->mode = Addressing_Invalid;
  4819. operand->expr = node;
  4820. return nullptr;
  4821. }
  4822. }
  4823. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4824. complete_soa_type(c->checker, type_deref(operand->type), false);
  4825. }
  4826. if (entity == nullptr && selector->kind == Ast_Ident) {
  4827. String field_name = selector->Ident.token.string;
  4828. Type *t = type_deref(operand->type);
  4829. if (t == nullptr) {
  4830. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4831. } else {
  4832. if (is_type_dynamic_array(t)) {
  4833. init_mem_allocator(c->checker);
  4834. }
  4835. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4836. entity = sel.entity;
  4837. // NOTE(bill): Add type info needed for fields like 'names'
  4838. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4839. add_type_info_type(c, operand->type);
  4840. }
  4841. if (is_type_enum(operand->type)) {
  4842. add_type_info_type(c, operand->type);
  4843. }
  4844. }
  4845. }
  4846. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4847. String field_name = selector->Ident.token.string;
  4848. if (field_name.len == 1) {
  4849. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4850. } else {
  4851. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4852. }
  4853. return nullptr;
  4854. }
  4855. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4856. (is_type_array(type_deref(operand->type)))) {
  4857. String field_name = selector->Ident.token.string;
  4858. if (1 < field_name.len && field_name.len <= 4) {
  4859. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4860. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4861. bool found_xyzw = false;
  4862. bool found_rgba = false;
  4863. for (isize i = 0; i < field_name.len; i++) {
  4864. bool valid = false;
  4865. for (isize j = 0; j < 4; j++) {
  4866. if (field_name.text[i] == swizzles_xyzw[j]) {
  4867. found_xyzw = true;
  4868. valid = true;
  4869. break;
  4870. }
  4871. if (field_name.text[i] == swizzles_rgba[j]) {
  4872. found_rgba = true;
  4873. valid = true;
  4874. break;
  4875. }
  4876. }
  4877. if (!valid) {
  4878. goto end_of_array_selector_swizzle;
  4879. }
  4880. }
  4881. u8 *swizzles = nullptr;
  4882. u8 index_count = cast(u8)field_name.len;
  4883. if (found_xyzw && found_rgba) {
  4884. gbString op_str = expr_to_string(op_expr);
  4885. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4886. gb_string_free(op_str);
  4887. operand->mode = Addressing_Invalid;
  4888. operand->expr = node;
  4889. return nullptr;
  4890. }
  4891. u8 indices = 0;
  4892. if (found_xyzw) {
  4893. swizzles = swizzles_xyzw;
  4894. } else if (found_rgba) {
  4895. swizzles = swizzles_rgba;
  4896. }
  4897. for (isize i = 0; i < field_name.len; i++) {
  4898. for (isize j = 0; j < 4; j++) {
  4899. if (field_name.text[i] == swizzles[j]) {
  4900. indices |= cast(u8)(j)<<(i*2);
  4901. break;
  4902. }
  4903. }
  4904. }
  4905. Type *original_type = operand->type;
  4906. Type *array_type = base_type(type_deref(original_type));
  4907. GB_ASSERT(array_type->kind == Type_Array);
  4908. i64 array_count = get_array_type_count(array_type);
  4909. for (u8 i = 0; i < index_count; i++) {
  4910. u8 idx = indices>>(i*2) & 3;
  4911. if (idx >= array_count) {
  4912. char c = 0;
  4913. if (found_xyzw) {
  4914. c = swizzles_xyzw[idx];
  4915. } else if (found_rgba) {
  4916. c = swizzles_rgba[idx];
  4917. } else {
  4918. GB_PANIC("unknown swizzle kind");
  4919. }
  4920. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4921. break;
  4922. }
  4923. }
  4924. se->swizzle_count = index_count;
  4925. se->swizzle_indices = indices;
  4926. AddressingMode prev_mode = operand->mode;
  4927. operand->mode = Addressing_SwizzleValue;
  4928. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4929. operand->expr = node;
  4930. switch (prev_mode) {
  4931. case Addressing_Variable:
  4932. case Addressing_SoaVariable:
  4933. case Addressing_SwizzleVariable:
  4934. operand->mode = Addressing_SwizzleVariable;
  4935. break;
  4936. case Addressing_Value:
  4937. if (is_type_pointer(original_type)) {
  4938. operand->mode = Addressing_SwizzleVariable;
  4939. }
  4940. break;
  4941. }
  4942. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4943. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4944. return swizzle_entity;
  4945. }
  4946. end_of_array_selector_swizzle:;
  4947. }
  4948. if (entity == nullptr) {
  4949. gbString op_str = expr_to_string(op_expr);
  4950. gbString type_str = type_to_string_shorthand(operand->type);
  4951. gbString sel_str = expr_to_string(selector);
  4952. if (operand->mode == Addressing_Type) {
  4953. if (is_type_polymorphic(operand->type, true)) {
  4954. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4955. } else {
  4956. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4957. }
  4958. } else {
  4959. ERROR_BLOCK();
  4960. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4961. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4962. String const &name = selector->Ident.token.string;
  4963. Type *bt = base_type(operand->type);
  4964. if (operand->type->kind == Type_Named &&
  4965. operand->type->Named.type_name &&
  4966. operand->type->Named.type_name->kind == Entity_TypeName &&
  4967. operand->type->Named.type_name->TypeName.objc_metadata) {
  4968. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4969. } else if (bt->kind == Type_Struct) {
  4970. check_did_you_mean_type(name, bt->Struct.fields);
  4971. } else if (bt->kind == Type_Enum) {
  4972. check_did_you_mean_type(name, bt->Enum.fields);
  4973. }
  4974. }
  4975. }
  4976. gb_string_free(sel_str);
  4977. gb_string_free(type_str);
  4978. gb_string_free(op_str);
  4979. operand->mode = Addressing_Invalid;
  4980. operand->expr = node;
  4981. return nullptr;
  4982. }
  4983. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4984. bool success = false;
  4985. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4986. if (success) {
  4987. operand->mode = Addressing_Constant;
  4988. operand->expr = node;
  4989. operand->value = field_value;
  4990. operand->type = entity->type;
  4991. add_entity_use(c, selector, entity);
  4992. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4993. return entity;
  4994. }
  4995. gbString op_str = expr_to_string(op_expr);
  4996. gbString type_str = type_to_string_shorthand(operand->type);
  4997. gbString sel_str = expr_to_string(selector);
  4998. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4999. gb_string_free(sel_str);
  5000. gb_string_free(type_str);
  5001. gb_string_free(op_str);
  5002. operand->mode = Addressing_Invalid;
  5003. operand->expr = node;
  5004. return nullptr;
  5005. }
  5006. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  5007. bool success = false;
  5008. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5009. if (success) {
  5010. operand->mode = Addressing_Constant;
  5011. operand->expr = node;
  5012. operand->value = field_value;
  5013. operand->type = entity->type;
  5014. add_entity_use(c, selector, entity);
  5015. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5016. return entity;
  5017. }
  5018. gbString op_str = expr_to_string(op_expr);
  5019. gbString type_str = type_to_string_shorthand(operand->type);
  5020. gbString sel_str = expr_to_string(selector);
  5021. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5022. gb_string_free(sel_str);
  5023. gb_string_free(type_str);
  5024. gb_string_free(op_str);
  5025. operand->mode = Addressing_Invalid;
  5026. operand->expr = node;
  5027. return nullptr;
  5028. }
  5029. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  5030. gbString op_str = expr_to_string(op_expr);
  5031. gbString type_str = type_to_string_shorthand(operand->type);
  5032. gbString sel_str = expr_to_string(selector);
  5033. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  5034. gb_string_free(sel_str);
  5035. gb_string_free(type_str);
  5036. gb_string_free(op_str);
  5037. operand->mode = Addressing_Invalid;
  5038. operand->expr = node;
  5039. return nullptr;
  5040. }
  5041. add_entity_use(c, selector, entity);
  5042. operand->type = entity->type;
  5043. operand->expr = node;
  5044. if (entity->flags & EntityFlag_BitFieldField) {
  5045. add_package_dependency(c, "runtime", "__write_bits");
  5046. add_package_dependency(c, "runtime", "__read_bits");
  5047. }
  5048. switch (entity->kind) {
  5049. case Entity_Constant:
  5050. operand->value = entity->Constant.value;
  5051. operand->mode = Addressing_Constant;
  5052. if (operand->value.kind == ExactValue_Procedure) {
  5053. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  5054. if (proc != nullptr) {
  5055. operand->mode = Addressing_Value;
  5056. operand->type = proc->type;
  5057. }
  5058. }
  5059. break;
  5060. case Entity_Variable:
  5061. if (sel.is_bit_field) {
  5062. se->is_bit_field = true;
  5063. }
  5064. if (sel.indirect) {
  5065. operand->mode = Addressing_Variable;
  5066. } else if (operand->mode == Addressing_Context) {
  5067. // Do nothing
  5068. } else if (operand->mode == Addressing_MapIndex) {
  5069. operand->mode = Addressing_Value;
  5070. } else if (entity->flags & EntityFlag_SoaPtrField) {
  5071. operand->mode = Addressing_SoaVariable;
  5072. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  5073. operand->mode = Addressing_Value;
  5074. } else if (operand->mode == Addressing_SoaVariable) {
  5075. operand->mode = Addressing_Variable;
  5076. } else if (operand->mode != Addressing_Value) {
  5077. operand->mode = Addressing_Variable;
  5078. } else {
  5079. operand->mode = Addressing_Value;
  5080. }
  5081. break;
  5082. case Entity_TypeName:
  5083. operand->mode = Addressing_Type;
  5084. break;
  5085. case Entity_Procedure:
  5086. operand->mode = Addressing_Value;
  5087. operand->value = exact_value_procedure(node);
  5088. break;
  5089. case Entity_Builtin:
  5090. operand->mode = Addressing_Builtin;
  5091. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5092. break;
  5093. case Entity_ProcGroup:
  5094. operand->mode = Addressing_ProcGroup;
  5095. operand->proc_group = entity;
  5096. break;
  5097. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5098. case Entity_Nil:
  5099. operand->mode = Addressing_Value;
  5100. break;
  5101. }
  5102. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5103. return entity;
  5104. }
  5105. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5106. ptr = base_type(ptr);
  5107. if (is_type_pointer(ptr)) {
  5108. if (is_type_rawptr(ptr)) {
  5109. return false;
  5110. }
  5111. if (elem) *elem = ptr->Pointer.elem;
  5112. return true;
  5113. }
  5114. return false;
  5115. }
  5116. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5117. elem = core_type(elem);
  5118. if (is_type_internally_pointer_like(elem)) {
  5119. return true;
  5120. }
  5121. if (elem->kind == Type_BitSet) {
  5122. elem = bit_set_to_int(elem);
  5123. }
  5124. if (elem->kind != Type_Basic) {
  5125. return false;
  5126. }
  5127. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5128. }
  5129. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5130. switch (node->kind) {
  5131. case_ast_node(i, Ident, node);
  5132. String name = i->token.string;
  5133. if (nested) {
  5134. Entity *e = scope_lookup_current(s, name);
  5135. if (e != nullptr) {
  5136. if (out_scope) *out_scope = e->scope;
  5137. return true;
  5138. }
  5139. } else {
  5140. Entity *e = scope_lookup(s, name);
  5141. if (e != nullptr) {
  5142. if (out_scope) *out_scope = e->scope;
  5143. return true;
  5144. }
  5145. }
  5146. case_end;
  5147. case_ast_node(se, SelectorExpr, node);
  5148. Ast *lhs = se->expr;
  5149. Ast *rhs = se->selector;
  5150. Scope *lhs_scope = nullptr;
  5151. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5152. return check_identifier_exists(lhs_scope, rhs, true);
  5153. }
  5154. case_end;
  5155. }
  5156. return false;
  5157. }
  5158. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5159. bool optional_ok = false;
  5160. isize tuple_index = 0;
  5161. for (Ast *rhs_expr : rhs) {
  5162. CheckerContext c_ = *ctx;
  5163. CheckerContext *c = &c_;
  5164. Operand o = {};
  5165. Type *type_hint = nullptr;
  5166. if (tuple_index < lhs.count) {
  5167. type_hint = lhs[tuple_index].type;
  5168. }
  5169. check_expr_base(c, &o, rhs_expr, type_hint);
  5170. if (o.mode == Addressing_NoValue) {
  5171. error_operand_no_value(&o);
  5172. o.mode = Addressing_Invalid;
  5173. }
  5174. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5175. if (lhs.count == 2 && rhs.count == 1 &&
  5176. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5177. Ast *expr = unparen_expr(o.expr);
  5178. Operand val0 = o;
  5179. Operand val1 = o;
  5180. val0.mode = Addressing_Value;
  5181. val1.mode = Addressing_Value;
  5182. val1.type = t_untyped_bool;
  5183. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5184. if (expr->kind == Ast_TypeAssertion &&
  5185. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5186. // NOTE(bill): Used only for optimizations in the backend
  5187. if (is_blank_ident(lhs[0].expr)) {
  5188. expr->TypeAssertion.ignores[0] = true;
  5189. }
  5190. if (is_blank_ident(lhs[1].expr)) {
  5191. expr->TypeAssertion.ignores[1] = true;
  5192. }
  5193. }
  5194. array_add(operands, val0);
  5195. array_add(operands, val1);
  5196. optional_ok = true;
  5197. tuple_index += 2;
  5198. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5199. Type *tuple = o.type;
  5200. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5201. Ast *expr = unparen_expr(o.expr);
  5202. if (expr->kind == Ast_CallExpr) {
  5203. expr->CallExpr.optional_ok_one = true;
  5204. }
  5205. Operand val = o;
  5206. val.type = tuple->Tuple.variables[0]->type;
  5207. val.mode = Addressing_Value;
  5208. array_add(operands, val);
  5209. tuple_index += tuple->Tuple.variables.count;
  5210. } else {
  5211. array_add(operands, o);
  5212. tuple_index += 1;
  5213. }
  5214. } else {
  5215. TypeTuple *tuple = &o.type->Tuple;
  5216. for (Entity *e : tuple->variables) {
  5217. o.type = e->type;
  5218. array_add(operands, o);
  5219. }
  5220. tuple_index += tuple->variables.count;
  5221. }
  5222. }
  5223. return optional_ok;
  5224. }
  5225. typedef u32 UnpackFlags;
  5226. enum UnpackFlag : u32 {
  5227. UnpackFlag_None = 0,
  5228. UnpackFlag_AllowOk = 1<<0,
  5229. UnpackFlag_AllowUndef = 1<<1,
  5230. };
  5231. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5232. isize variadic_index = -1) {
  5233. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5234. if (lhs == nullptr || c->decl == nullptr) {
  5235. return tuple_count;
  5236. }
  5237. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5238. Entity *e = lhs[tuple_index + j];
  5239. if (e == nullptr) {
  5240. continue;
  5241. }
  5242. DeclInfo *decl = decl_info_of_entity(e);
  5243. if (decl == nullptr) {
  5244. continue;
  5245. }
  5246. rw_mutex_shared_lock(&decl->deps_mutex);
  5247. rw_mutex_lock(&c->decl->deps_mutex);
  5248. for (Entity *dep : decl->deps) {
  5249. ptr_set_add(&c->decl->deps, dep);
  5250. }
  5251. rw_mutex_unlock(&c->decl->deps_mutex);
  5252. rw_mutex_shared_unlock(&decl->deps_mutex);
  5253. }
  5254. return tuple_count;
  5255. };
  5256. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5257. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5258. bool is_variadic = variadic_index > -1;
  5259. if (!is_variadic) {
  5260. variadic_index = lhs_count;
  5261. }
  5262. bool optional_ok = false;
  5263. isize tuple_index = 0;
  5264. for (Ast *rhs : rhs_arguments) {
  5265. if (rhs->kind == Ast_FieldValue) {
  5266. error(rhs, "Invalid use of 'field = value'");
  5267. rhs = rhs->FieldValue.value;
  5268. }
  5269. CheckerContext c_ = *ctx;
  5270. CheckerContext *c = &c_;
  5271. Operand o = {};
  5272. Type *type_hint = nullptr;
  5273. if (lhs != nullptr) {
  5274. if (tuple_index < variadic_index) {
  5275. // NOTE(bill): override DeclInfo for dependency
  5276. Entity *e = lhs[tuple_index];
  5277. if (e != nullptr) {
  5278. type_hint = e->type;
  5279. }
  5280. } else if (is_variadic) {
  5281. Entity *e = lhs[variadic_index];
  5282. if (e != nullptr) {
  5283. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5284. GB_ASSERT(is_type_slice(e->type));
  5285. type_hint = e->type->Slice.elem;
  5286. }
  5287. }
  5288. }
  5289. Ast *rhs_expr = unparen_expr(rhs);
  5290. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5291. // NOTE(bill): Just handle this very specific logic here
  5292. o.type = t_untyped_uninit;
  5293. o.mode = Addressing_Value;
  5294. o.expr = rhs;
  5295. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5296. } else {
  5297. check_expr_base(c, &o, rhs, type_hint);
  5298. }
  5299. if (o.mode == Addressing_NoValue) {
  5300. error_operand_no_value(&o);
  5301. o.mode = Addressing_Invalid;
  5302. }
  5303. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5304. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5305. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5306. Ast *expr = unparen_expr(o.expr);
  5307. Operand val0 = o;
  5308. Operand val1 = o;
  5309. val0.mode = Addressing_Value;
  5310. val1.mode = Addressing_Value;
  5311. val1.type = t_untyped_bool;
  5312. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5313. if (expr->kind == Ast_TypeAssertion &&
  5314. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5315. // NOTE(bill): Used only for optimizations in the backend
  5316. if (is_blank_ident(lhs[0]->token)) {
  5317. expr->TypeAssertion.ignores[0] = true;
  5318. }
  5319. if (is_blank_ident(lhs[1]->token)) {
  5320. expr->TypeAssertion.ignores[1] = true;
  5321. }
  5322. }
  5323. array_add(operands, val0);
  5324. array_add(operands, val1);
  5325. optional_ok = true;
  5326. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5327. } else {
  5328. array_add(operands, o);
  5329. tuple_index += 1;
  5330. }
  5331. } else {
  5332. TypeTuple *tuple = &o.type->Tuple;
  5333. for (Entity *e : tuple->variables) {
  5334. o.type = e->type;
  5335. array_add(operands, o);
  5336. }
  5337. isize count = tuple->variables.count;
  5338. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5339. }
  5340. }
  5341. return optional_ok;
  5342. }
  5343. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5344. GB_ASSERT(pt != nullptr);
  5345. GB_ASSERT(pt->kind == Type_Proc);
  5346. isize param_count = 0;
  5347. isize param_count_excluding_defaults = 0;
  5348. bool variadic = pt->Proc.variadic;
  5349. TypeTuple *param_tuple = nullptr;
  5350. if (pt->Proc.params != nullptr) {
  5351. param_tuple = &pt->Proc.params->Tuple;
  5352. param_count = param_tuple->variables.count;
  5353. if (variadic) {
  5354. for (isize i = param_count-1; i >= 0; i--) {
  5355. Entity *e = param_tuple->variables[i];
  5356. if (e->kind == Entity_TypeName) {
  5357. break;
  5358. }
  5359. if (e->kind == Entity_Variable) {
  5360. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5361. param_count--;
  5362. continue;
  5363. }
  5364. }
  5365. break;
  5366. }
  5367. param_count--;
  5368. }
  5369. }
  5370. param_count_excluding_defaults = param_count;
  5371. if (param_tuple != nullptr) {
  5372. for (isize i = param_count-1; i >= 0; i--) {
  5373. Entity *e = param_tuple->variables[i];
  5374. if (e->kind == Entity_TypeName) {
  5375. break;
  5376. }
  5377. if (e->kind == Entity_Variable) {
  5378. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5379. param_count_excluding_defaults--;
  5380. continue;
  5381. }
  5382. }
  5383. break;
  5384. }
  5385. }
  5386. if (param_count_) *param_count_ = param_count;
  5387. return param_count_excluding_defaults;
  5388. }
  5389. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5390. isize param_count = pt->param_count;
  5391. for (isize i = 0; i < param_count; i++) {
  5392. Entity *e = pt->params->Tuple.variables[i];
  5393. String name = e->token.string;
  5394. if (is_blank_ident(name)) {
  5395. continue;
  5396. }
  5397. if (name == parameter_name) {
  5398. return i;
  5399. }
  5400. }
  5401. return -1;
  5402. }
  5403. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5404. type = base_type(type);
  5405. GB_ASSERT(type->kind == Type_Proc);
  5406. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5407. }
  5408. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5409. Entity *entity, Type *proc_type,
  5410. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5411. CallArgumentErrorMode show_error_mode,
  5412. CallArgumentData *data) {
  5413. TEMPORARY_ALLOCATOR_GUARD();
  5414. CallArgumentError err = CallArgumentError_None;
  5415. ast_node(ce, CallExpr, call);
  5416. GB_ASSERT(is_type_proc(proc_type));
  5417. proc_type = base_type(proc_type);
  5418. TypeProc *pt = &proc_type->Proc;
  5419. isize param_count = 0;
  5420. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5421. bool variadic = pt->variadic;
  5422. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5423. i64 score = 0;
  5424. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5425. Type *final_proc_type = proc_type;
  5426. Entity *gen_entity = nullptr;
  5427. if (vari_expand && !variadic) {
  5428. if (show_error) {
  5429. error(ce->ellipsis,
  5430. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5431. LIT(ce->proc->Ident.token.string));
  5432. }
  5433. err = CallArgumentError_NonVariadicExpand;
  5434. } else if (vari_expand && pt->c_vararg) {
  5435. if (show_error) {
  5436. error(ce->ellipsis,
  5437. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5438. LIT(ce->proc->Ident.token.string));
  5439. }
  5440. err = CallArgumentError_NonVariadicExpand;
  5441. }
  5442. GB_ASSERT(ce->split_args);
  5443. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5444. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5445. defer ({
  5446. for (Operand const &o : ordered_operands) {
  5447. if (o.expr != nullptr) {
  5448. call->viral_state_flags |= o.expr->viral_state_flags;
  5449. }
  5450. }
  5451. });
  5452. isize positional_operand_count = positional_operands.count;
  5453. if (variadic) {
  5454. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5455. } else if (positional_operand_count > pt->param_count) {
  5456. err = CallArgumentError_TooManyArguments;
  5457. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5458. if (show_error) {
  5459. gbString proc_str = expr_to_string(ce->proc);
  5460. defer (gb_string_free(proc_str));
  5461. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5462. }
  5463. return err;
  5464. }
  5465. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5466. for (isize i = 0; i < positional_operand_count; i++) {
  5467. ordered_operands[i] = positional_operands[i];
  5468. visited[i] = true;
  5469. }
  5470. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5471. bool named_variadic_param = false;
  5472. if (named_operands.count != 0) {
  5473. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5474. for_array(i, ce->split_args->named) {
  5475. Ast *arg = ce->split_args->named[i];
  5476. Operand operand = named_operands[i];
  5477. ast_node(fv, FieldValue, arg);
  5478. if (fv->field->kind != Ast_Ident) {
  5479. if (show_error) {
  5480. gbString expr_str = expr_to_string(fv->field);
  5481. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5482. gb_string_free(expr_str);
  5483. }
  5484. err = CallArgumentError_InvalidFieldValue;
  5485. continue;
  5486. }
  5487. String name = fv->field->Ident.token.string;
  5488. isize param_index = lookup_procedure_parameter(pt, name);
  5489. if (param_index < 0) {
  5490. if (show_error) {
  5491. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5492. }
  5493. err = CallArgumentError_ParameterNotFound;
  5494. continue;
  5495. }
  5496. if (pt->variadic && param_index == pt->variadic_index) {
  5497. named_variadic_param = true;
  5498. }
  5499. if (visited[param_index]) {
  5500. if (show_error) {
  5501. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5502. }
  5503. err = CallArgumentError_DuplicateParameter;
  5504. continue;
  5505. }
  5506. visited[param_index] = true;
  5507. ordered_operands[param_index] = operand;
  5508. }
  5509. }
  5510. isize dummy_argument_count = 0;
  5511. bool actually_variadic = false;
  5512. if (variadic) {
  5513. if (visited[pt->variadic_index] &&
  5514. positional_operand_count < positional_operands.count) {
  5515. if (show_error) {
  5516. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5517. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5518. }
  5519. err = CallArgumentError_DuplicateParameter;
  5520. } else if (!visited[pt->variadic_index]) {
  5521. visited[pt->variadic_index] = true;
  5522. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5523. if (vari_expand) {
  5524. if (variadic_operands.count == 0) {
  5525. error(call, "'..' in the wrong position");
  5526. } else {
  5527. GB_ASSERT(variadic_operands.count != 0);
  5528. *variadic_operand = variadic_operands[0];
  5529. variadic_operand->type = default_type(variadic_operand->type);
  5530. actually_variadic = true;
  5531. }
  5532. } else {
  5533. AstFile *f = call->file();
  5534. // HACK(bill): this is an awful hack
  5535. Operand o = {};
  5536. o.mode = Addressing_Value;
  5537. o.expr = ast_ident(f, make_token_ident("nil"));
  5538. o.expr->Ident.token.pos = ast_token(call).pos;
  5539. if (variadic_operands.count != 0) {
  5540. actually_variadic = true;
  5541. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5542. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5543. o.type = vt->type;
  5544. } else {
  5545. dummy_argument_count += 1;
  5546. o.type = t_untyped_nil;
  5547. }
  5548. *variadic_operand = o;
  5549. }
  5550. }
  5551. }
  5552. for (isize i = 0; i < pt->param_count; i++) {
  5553. if (!visited[i]) {
  5554. Entity *e = pt->params->Tuple.variables[i];
  5555. bool context_allocator_error = false;
  5556. if (e->kind == Entity_Variable) {
  5557. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5558. if (ast_file_vet_explicit_allocators(c->file)) {
  5559. // NOTE(lucas): check if we are trying to default to context.allocator or context.temp_allocator
  5560. if (e->Variable.param_value.original_ast_expr->kind == Ast_SelectorExpr) {
  5561. auto& expr = e->Variable.param_value.original_ast_expr->SelectorExpr.expr;
  5562. auto& selector = e->Variable.param_value.original_ast_expr->SelectorExpr.selector;
  5563. if (expr->kind == Ast_Implicit &&
  5564. expr->Implicit.string == STR_LIT("context") &&
  5565. selector->kind == Ast_Ident &&
  5566. (selector->Ident.token.string == STR_LIT("allocator") ||
  5567. selector->Ident.token.string == STR_LIT("temp_allocator"))) {
  5568. context_allocator_error = true;
  5569. }
  5570. }
  5571. }
  5572. if (!context_allocator_error) {
  5573. ordered_operands[i].mode = Addressing_Value;
  5574. ordered_operands[i].type = e->type;
  5575. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5576. dummy_argument_count += 1;
  5577. score += assign_score_function(1);
  5578. continue;
  5579. }
  5580. }
  5581. }
  5582. if (show_error) {
  5583. if (context_allocator_error) {
  5584. gbString str = type_to_string(e->type);
  5585. error(call, "Parameter '%.*s' of type '%s' must be explicitly provided in procedure call",
  5586. LIT(e->token.string), str);
  5587. gb_string_free(str);
  5588. } else if (e->kind == Entity_TypeName) {
  5589. error(call, "Type parameter '%.*s' is missing in procedure call",
  5590. LIT(e->token.string));
  5591. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5592. // Ignore
  5593. } else {
  5594. gbString str = type_to_string(e->type);
  5595. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5596. LIT(e->token.string), str);
  5597. gb_string_free(str);
  5598. }
  5599. }
  5600. err = CallArgumentError_ParameterMissing;
  5601. }
  5602. }
  5603. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5604. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5605. i64 s = 0;
  5606. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5607. bool ok = false;
  5608. if (e && (e->flags & EntityFlag_AnyInt)) {
  5609. if (is_type_integer(param_type)) {
  5610. ok = check_is_castable_to(c, o, param_type);
  5611. }
  5612. }
  5613. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5614. if (show_error) {
  5615. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5616. }
  5617. }
  5618. if (ok) {
  5619. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5620. } else {
  5621. if (show_error) {
  5622. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5623. }
  5624. err = CallArgumentError_WrongTypes;
  5625. }
  5626. } else if (show_error) {
  5627. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5628. }
  5629. if (e && e->flags & EntityFlag_ConstInput) {
  5630. if (o->mode != Addressing_Constant) {
  5631. if (show_error) {
  5632. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5633. }
  5634. err = CallArgumentError_NoneConstantParameter;
  5635. }
  5636. }
  5637. if (!err && is_type_any(param_type)) {
  5638. add_type_info_type(c, o->type);
  5639. }
  5640. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5641. add_type_info_type(c, o->type);
  5642. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5643. } else if (show_error && is_type_untyped(o->type)) {
  5644. update_untyped_expr_type(c, o->expr, param_type, true);
  5645. }
  5646. return s;
  5647. };
  5648. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5649. err = CallArgumentError_None;
  5650. if (variadic) {
  5651. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5652. Type *t = pt->params->Tuple.variables[0]->type;
  5653. if (is_type_polymorphic(t)) {
  5654. if (show_error) {
  5655. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5656. }
  5657. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5658. }
  5659. }
  5660. } else {
  5661. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5662. PolyProcData poly_proc_data = {};
  5663. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5664. gen_entity = poly_proc_data.gen_entity;
  5665. Type *gept = base_type(gen_entity->type);
  5666. GB_ASSERT(is_type_proc(gept));
  5667. final_proc_type = gen_entity->type;
  5668. pt = &gept->Proc;
  5669. } else {
  5670. err = CallArgumentError_WrongTypes;
  5671. }
  5672. }
  5673. for (isize i = 0; i < pt->param_count; i++) {
  5674. Operand *o = &ordered_operands[i];
  5675. if (o->mode == Addressing_Invalid) {
  5676. continue;
  5677. }
  5678. Entity *e = pt->params->Tuple.variables[i];
  5679. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5680. if (e->kind == Entity_TypeName) {
  5681. GB_ASSERT(pt->is_polymorphic);
  5682. if (o->mode != Addressing_Type) {
  5683. if (show_error) {
  5684. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5685. }
  5686. err = CallArgumentError_WrongTypes;
  5687. }
  5688. if (are_types_identical(e->type, o->type)) {
  5689. score += assign_score_function(1);
  5690. } else {
  5691. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5692. }
  5693. continue;
  5694. }
  5695. if (param_is_variadic) {
  5696. if (!named_variadic_param) {
  5697. continue;
  5698. }
  5699. }
  5700. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5701. }
  5702. }
  5703. if (variadic) {
  5704. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5705. Type *slice = var_entity->type;
  5706. GB_ASSERT(is_type_slice(slice));
  5707. Type *elem = base_type(slice)->Slice.elem;
  5708. Type *t = elem;
  5709. if (is_type_polymorphic(t)) {
  5710. if (show_error) {
  5711. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5712. }
  5713. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5714. }
  5715. for_array(operand_index, variadic_operands) {
  5716. Operand *o = &variadic_operands[operand_index];
  5717. if (vari_expand) {
  5718. t = slice;
  5719. if (operand_index > 0) {
  5720. if (show_error) {
  5721. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5722. }
  5723. if (data) {
  5724. data->score = score;
  5725. data->result_type = final_proc_type->Proc.results;
  5726. data->gen_entity = gen_entity;
  5727. }
  5728. return CallArgumentError_MultipleVariadicExpand;
  5729. }
  5730. }
  5731. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5732. }
  5733. if (!vari_expand && variadic_operands.count != 0) {
  5734. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5735. if (c->decl) {
  5736. bool found = false;
  5737. for (auto &vr : c->decl->variadic_reuses) {
  5738. if (are_types_identical(slice, vr.slice_type)) {
  5739. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5740. found = true;
  5741. break;
  5742. }
  5743. }
  5744. if (!found) {
  5745. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5746. }
  5747. }
  5748. }
  5749. }
  5750. if (data) {
  5751. data->score = score;
  5752. data->result_type = final_proc_type->Proc.results;
  5753. data->gen_entity = gen_entity;
  5754. Ast *proc_lit = nullptr;
  5755. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5756. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5757. if (vp && vp->kind == Ast_ProcLit) {
  5758. proc_lit = vp;
  5759. }
  5760. }
  5761. if (proc_lit == nullptr) {
  5762. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5763. }
  5764. }
  5765. return err;
  5766. }
  5767. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5768. GB_ASSERT(ce != nullptr);
  5769. if (ce->args.count == 0) {
  5770. return false;
  5771. }
  5772. return ce->args[0]->kind == Ast_FieldValue;
  5773. }
  5774. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5775. Entity **lhs = nullptr;
  5776. isize lhs_count = -1;
  5777. if (proc_type == nullptr || proc_type == t_invalid) {
  5778. return nullptr;
  5779. }
  5780. GB_ASSERT(is_type_proc(proc_type));
  5781. TypeProc *pt = &base_type(proc_type)->Proc;
  5782. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5783. if (pt->params != nullptr) {
  5784. lhs = pt->params->Tuple.variables.data;
  5785. lhs_count = pt->params->Tuple.variables.count;
  5786. }
  5787. } else {
  5788. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5789. if (pt->params == nullptr) {
  5790. lhs_count = 0;
  5791. } else {
  5792. lhs_count = pt->params->Tuple.variables.count;
  5793. }
  5794. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5795. for (isize i = 0; i < lhs_count; i++) {
  5796. Entity *e = pt->params->Tuple.variables[i];
  5797. if (!is_type_polymorphic(e->type)) {
  5798. lhs[i] = e;
  5799. }
  5800. }
  5801. }
  5802. if (lhs_count_) *lhs_count_ = lhs_count;
  5803. return lhs;
  5804. }
  5805. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5806. if (clauses != nullptr) {
  5807. for (Ast *clause : *clauses) {
  5808. Operand o = {};
  5809. check_expr(ctx, &o, clause);
  5810. if (o.mode != Addressing_Constant) {
  5811. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5812. if (print_err && call_expr) error(call_expr, "at caller location");
  5813. return false;
  5814. } else if (o.value.kind != ExactValue_Bool) {
  5815. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5816. if (print_err && call_expr) error(call_expr, "at caller location");
  5817. return false;
  5818. } else if (!o.value.value_bool) {
  5819. if (print_err) {
  5820. ERROR_BLOCK();
  5821. gbString str = expr_to_string(clause);
  5822. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5823. gb_string_free(str);
  5824. if (scope != nullptr) {
  5825. isize print_count = 0;
  5826. for (auto const &entry : scope->elements) {
  5827. Entity *e = entry.value;
  5828. switch (e->kind) {
  5829. case Entity_TypeName: {
  5830. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5831. gbString str = type_to_string(e->type);
  5832. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5833. gb_string_free(str);
  5834. print_count += 1;
  5835. break;
  5836. }
  5837. case Entity_Constant: {
  5838. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5839. gbString str = exact_value_to_string(e->Constant.value);
  5840. if (is_type_untyped(e->type)) {
  5841. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5842. } else {
  5843. gbString t = type_to_string(e->type);
  5844. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5845. gb_string_free(t);
  5846. }
  5847. gb_string_free(str);
  5848. print_count += 1;
  5849. break;
  5850. }
  5851. }
  5852. }
  5853. }
  5854. if (call_expr) {
  5855. TokenPos pos = ast_token(call_expr).pos;
  5856. error_line("%s at caller location\n", token_pos_to_string(pos));
  5857. }
  5858. }
  5859. return false;
  5860. }
  5861. if (ast_file_vet_style(ctx->file)) {
  5862. Ast *c = unparen_expr(clause);
  5863. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5864. ERROR_BLOCK();
  5865. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5866. gbString x = expr_to_string(c->BinaryExpr.left);
  5867. gbString y = expr_to_string(c->BinaryExpr.right);
  5868. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5869. gb_string_free(y);
  5870. gb_string_free(x);
  5871. }
  5872. }
  5873. }
  5874. }
  5875. return true;
  5876. }
  5877. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5878. bool success = true;
  5879. type = base_type(type);
  5880. if (named_args.count > 0) {
  5881. TypeProc *pt = nullptr;
  5882. if (is_type_proc(type)) {
  5883. pt = &type->Proc;
  5884. }
  5885. for_array(i, named_args) {
  5886. Ast *arg = named_args[i];
  5887. if (arg->kind != Ast_FieldValue) {
  5888. if (show_error) {
  5889. error(arg, "Expected a 'field = value'");
  5890. }
  5891. return false;
  5892. }
  5893. ast_node(fv, FieldValue, arg);
  5894. if (fv->field->kind != Ast_Ident) {
  5895. if (show_error) {
  5896. gbString expr_str = expr_to_string(fv->field);
  5897. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5898. gb_string_free(expr_str);
  5899. }
  5900. success = false;
  5901. continue;
  5902. }
  5903. String key = fv->field->Ident.token.string;
  5904. Ast *value = fv->value;
  5905. Type *type_hint = nullptr;
  5906. if (pt) {
  5907. isize param_index = lookup_procedure_parameter(pt, key);
  5908. if (param_index < 0) {
  5909. if (show_error) {
  5910. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5911. }
  5912. success = false;
  5913. continue;
  5914. }
  5915. Entity *e = pt->params->Tuple.variables[param_index];
  5916. if (!is_type_polymorphic(e->type)) {
  5917. type_hint = e->type;
  5918. }
  5919. }
  5920. Operand o = {};
  5921. check_expr_with_type_hint(c, &o, value, type_hint);
  5922. if (o.mode == Addressing_Invalid) {
  5923. success = false;
  5924. }
  5925. array_add(named_operands, o);
  5926. }
  5927. }
  5928. return success;
  5929. }
  5930. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5931. Entity *e, Type *proc_type,
  5932. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5933. CallArgumentErrorMode show_error_mode,
  5934. CallArgumentData *data) {
  5935. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5936. Ast *ident = operand->expr;
  5937. while (ident->kind == Ast_SelectorExpr) {
  5938. Ast *s = ident->SelectorExpr.selector;
  5939. ident = s;
  5940. }
  5941. if (e == nullptr) {
  5942. e = entity_of_node(ident);
  5943. if (e != nullptr) {
  5944. proc_type = e->type;
  5945. }
  5946. }
  5947. GB_ASSERT(proc_type != nullptr);
  5948. proc_type = base_type(proc_type);
  5949. if (proc_type == t_invalid) {
  5950. return false;
  5951. }
  5952. GB_ASSERT(proc_type->kind == Type_Proc);
  5953. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5954. if (return_on_failure && err != CallArgumentError_None) {
  5955. return false;
  5956. }
  5957. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5958. if (!return_on_failure && entity_to_use != nullptr) {
  5959. add_entity_use(c, ident, entity_to_use);
  5960. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5961. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5962. }
  5963. if (data->gen_entity != nullptr) {
  5964. Entity *e = data->gen_entity;
  5965. DeclInfo *decl = data->gen_entity->decl_info;
  5966. CheckerContext ctx = *c;
  5967. ctx.scope = decl->scope;
  5968. ctx.decl = decl;
  5969. ctx.proc_name = e->token.string;
  5970. ctx.curr_proc_decl = decl;
  5971. ctx.curr_proc_sig = e->type;
  5972. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5973. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5974. if (return_on_failure) {
  5975. if (!ok) {
  5976. return false;
  5977. }
  5978. } else {
  5979. decl->where_clauses_evaluated = true;
  5980. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5981. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5982. }
  5983. if (is_type_proc(data->gen_entity->type)) {
  5984. Type *t = base_type(entity_to_use->type);
  5985. data->result_type = t->Proc.results;
  5986. }
  5987. }
  5988. }
  5989. return true;
  5990. }
  5991. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5992. ast_node(ce, CallExpr, call);
  5993. GB_ASSERT(ce->split_args != nullptr);
  5994. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5995. Slice<Ast *> const &named_args = ce->split_args->named;
  5996. CallArgumentData data = {};
  5997. data.result_type = t_invalid;
  5998. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5999. auto procs = proc_group_entities_cloned(c, *operand);
  6000. if (procs.count > 1) {
  6001. isize max_arg_count = positional_args.count + named_args.count;
  6002. for (Ast *arg : positional_args) {
  6003. // NOTE(bill): The only thing that may have multiple values
  6004. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6005. arg = strip_or_return_expr(arg);
  6006. if (arg && arg->kind == Ast_CallExpr) {
  6007. max_arg_count = ISIZE_MAX;
  6008. break;
  6009. }
  6010. }
  6011. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  6012. // NOTE(bill): The only thing that may have multiple values
  6013. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6014. if (arg->kind == Ast_FieldValue) {
  6015. arg = strip_or_return_expr(arg->FieldValue.value);
  6016. if (arg && arg->kind == Ast_CallExpr) {
  6017. max_arg_count = ISIZE_MAX;
  6018. break;
  6019. }
  6020. }
  6021. }
  6022. // ignore named arguments first
  6023. for (Ast *arg : named_args) {
  6024. if (arg->kind != Ast_FieldValue) {
  6025. continue;
  6026. }
  6027. ast_node(fv, FieldValue, arg);
  6028. if (fv->field->kind != Ast_Ident) {
  6029. continue;
  6030. }
  6031. String key = fv->field->Ident.token.string;
  6032. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  6033. Type *t = procs[proc_index]->type;
  6034. if (is_type_proc(t)) {
  6035. isize param_index = lookup_procedure_parameter(t, key);
  6036. if (param_index < 0) {
  6037. array_unordered_remove(&procs, proc_index);
  6038. }
  6039. }
  6040. }
  6041. }
  6042. if (procs.count == 0) {
  6043. // if any of the named arguments are wrong, the `procs` will be empty
  6044. // just start from scratch
  6045. array_free(&procs);
  6046. procs = proc_group_entities_cloned(c, *operand);
  6047. }
  6048. // filter by positional argument length
  6049. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  6050. Entity *proc = procs[proc_index];
  6051. Type *pt = base_type(proc->type);
  6052. if (!(pt != nullptr && is_type_proc(pt))) {
  6053. proc_index++;
  6054. continue;
  6055. }
  6056. isize param_count = 0;
  6057. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  6058. if (param_count_excluding_defaults > max_arg_count) {
  6059. array_unordered_remove(&procs, proc_index);
  6060. continue;
  6061. }
  6062. proc_index++;
  6063. }
  6064. }
  6065. Entity **lhs = nullptr;
  6066. isize lhs_count = -1;
  6067. i32 variadic_index = -1;
  6068. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6069. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6070. defer (array_free(&positional_operands));
  6071. defer (array_free(&named_operands));
  6072. if (procs.count == 1) {
  6073. Entity *e = procs[0];
  6074. Type *pt = base_type(e->type);
  6075. if (pt != nullptr && is_type_proc(pt)) {
  6076. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  6077. if (pt->Proc.variadic) {
  6078. variadic_index = pt->Proc.variadic_index;
  6079. }
  6080. }
  6081. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6082. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  6083. check_call_arguments_single(c, call, operand,
  6084. e, e->type,
  6085. positional_operands, named_operands,
  6086. CallArgumentErrorMode::ShowErrors,
  6087. &data);
  6088. }
  6089. return data;
  6090. }
  6091. {
  6092. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6093. // where the same positional parameter has the same type value (and ellipsis)
  6094. isize proc_arg_count = -1;
  6095. for (Entity *p : procs) {
  6096. Type *pt = base_type(p->type);
  6097. if (pt != nullptr && is_type_proc(pt)) {
  6098. if (proc_arg_count < 0) {
  6099. proc_arg_count = pt->Proc.param_count;
  6100. } else {
  6101. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6102. }
  6103. }
  6104. }
  6105. if (proc_arg_count >= 0) {
  6106. lhs_count = proc_arg_count;
  6107. if (lhs_count > 0) {
  6108. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6109. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6110. Entity *e = nullptr;
  6111. for (Entity *p : procs) {
  6112. Type *pt = base_type(p->type);
  6113. if (!(pt != nullptr && is_type_proc(pt))) {
  6114. continue;
  6115. }
  6116. if (e == nullptr) {
  6117. e = pt->Proc.params->Tuple.variables[param_index];
  6118. } else {
  6119. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6120. if (e == f) {
  6121. continue;
  6122. }
  6123. if (are_types_identical(e->type, f->type)) {
  6124. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6125. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6126. if (ee == fe) {
  6127. continue;
  6128. }
  6129. }
  6130. // NOTE(bill): Entities are not close enough to be used
  6131. e = nullptr;
  6132. break;
  6133. }
  6134. }
  6135. lhs[param_index] = e;
  6136. }
  6137. for (Entity *p : procs) {
  6138. Type *pt = base_type(p->type);
  6139. if (!(pt != nullptr && is_type_proc(pt))) {
  6140. continue;
  6141. }
  6142. if (pt->Proc.is_polymorphic) {
  6143. if (variadic_index == -1) {
  6144. variadic_index = pt->Proc.variadic_index;
  6145. } else if (variadic_index != pt->Proc.variadic_index) {
  6146. variadic_index = -1;
  6147. break;
  6148. }
  6149. } else {
  6150. variadic_index = -1;
  6151. break;
  6152. }
  6153. }
  6154. }
  6155. }
  6156. }
  6157. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6158. for_array(i, named_args) {
  6159. Ast *arg = named_args[i];
  6160. if (arg->kind != Ast_FieldValue) {
  6161. error(arg, "Expected a 'field = value'");
  6162. return data;
  6163. }
  6164. ast_node(fv, FieldValue, arg);
  6165. if (fv->field->kind != Ast_Ident) {
  6166. gbString expr_str = expr_to_string(fv->field);
  6167. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6168. gb_string_free(expr_str);
  6169. return data;
  6170. }
  6171. String key = fv->field->Ident.token.string;
  6172. Ast *value = fv->value;
  6173. Type *type_hint = nullptr;
  6174. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6175. Entity *e = lhs[lhs_idx];
  6176. if (e != nullptr && e->token.string == key &&
  6177. !is_type_polymorphic(e->type)) {
  6178. type_hint = e->type;
  6179. break;
  6180. }
  6181. }
  6182. Operand o = {};
  6183. check_expr_with_type_hint(c, &o, value, type_hint);
  6184. array_add(&named_operands, o);
  6185. }
  6186. gb_free(heap_allocator(), lhs);
  6187. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6188. defer (array_free(&valids));
  6189. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6190. defer (array_free(&proc_entities));
  6191. for (Entity *proc : procs) {
  6192. array_add(&proc_entities, proc);
  6193. }
  6194. int max_matched_features = 0;
  6195. gbString expr_name = expr_to_string(operand->expr);
  6196. defer (gb_string_free(expr_name));
  6197. for_array(i, procs) {
  6198. Entity *p = procs[i];
  6199. if (p->flags & EntityFlag_Disabled) {
  6200. continue;
  6201. }
  6202. Type *pt = base_type(p->type);
  6203. if (pt != nullptr && is_type_proc(pt)) {
  6204. CallArgumentData data = {};
  6205. CheckerContext ctx = *c;
  6206. ctx.no_polymorphic_errors = true;
  6207. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6208. ctx.hide_polymorphic_errors = true;
  6209. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6210. p, pt,
  6211. positional_operands, named_operands,
  6212. CallArgumentErrorMode::NoErrors,
  6213. &data);
  6214. if (!is_a_candidate) {
  6215. continue;
  6216. }
  6217. isize index = i;
  6218. ValidIndexAndScore item = {};
  6219. item.score = data.score;
  6220. if (data.gen_entity != nullptr) {
  6221. array_add(&proc_entities, data.gen_entity);
  6222. index = proc_entities.count-1;
  6223. // prefer non-polymorphic procedures over polymorphic
  6224. item.score += assign_score_function(1);
  6225. }
  6226. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6227. item.index = index;
  6228. array_add(&valids, item);
  6229. }
  6230. }
  6231. if (max_matched_features > 0) {
  6232. for_array(i, valids) {
  6233. Entity *p = procs[valids[i].index];
  6234. Type *t = base_type(p->type);
  6235. GB_ASSERT(t->kind == Type_Proc);
  6236. int matched = matched_target_features(&t->Proc);
  6237. valids[i].score += assign_score_function(max_matched_features-matched);
  6238. }
  6239. }
  6240. if (valids.count > 1) {
  6241. array_sort(valids, valid_index_and_score_cmp);
  6242. i64 best_score = valids[0].score;
  6243. Entity *best_entity = proc_entities[valids[0].index];
  6244. GB_ASSERT(best_entity != nullptr);
  6245. for (isize i = 1; i < valids.count; i++) {
  6246. if (best_score > valids[i].score) {
  6247. valids.count = i;
  6248. break;
  6249. }
  6250. if (best_entity == proc_entities[valids[i].index]) {
  6251. valids.count = i;
  6252. break;
  6253. }
  6254. }
  6255. }
  6256. auto print_argument_types = [&]() {
  6257. error_line("\tGiven argument types: (");
  6258. isize i = 0;
  6259. for (Operand const &o : positional_operands) {
  6260. if (i++ > 0) error_line(", ");
  6261. gbString type = type_to_string(o.type);
  6262. defer (gb_string_free(type));
  6263. error_line("%s", type);
  6264. }
  6265. for (Operand const &o : named_operands) {
  6266. if (i++ > 0) error_line(", ");
  6267. gbString type = type_to_string(o.type);
  6268. defer (gb_string_free(type));
  6269. if (i < ce->split_args->named.count) {
  6270. Ast *named_field = ce->split_args->named[i];
  6271. ast_node(fv, FieldValue, named_field);
  6272. gbString field = expr_to_string(fv->field);
  6273. defer (gb_string_free(field));
  6274. error_line("%s = %s", field, type);
  6275. } else {
  6276. error_line("%s", type);
  6277. }
  6278. }
  6279. error_line(")\n");
  6280. };
  6281. if (valids.count == 0) {
  6282. ERROR_BLOCK();
  6283. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6284. if (positional_operands.count == 0 && named_operands.count == 0) {
  6285. error_line("\tNo given arguments\n");
  6286. } else {
  6287. print_argument_types();
  6288. }
  6289. if (procs.count == 0) {
  6290. procs = proc_group_entities_cloned(c, *operand);
  6291. }
  6292. if (procs.count > 0) {
  6293. error_line("Did you mean to use one of the following:\n");
  6294. }
  6295. // Try to reduce the list further for `$T: typeid` like parameters
  6296. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6297. isize possibly_ignore_set = 0;
  6298. if (true) {
  6299. // NOTE(bill): This currently only checks for #soa types
  6300. for_array(i, procs) {
  6301. Entity *proc = procs[i];
  6302. Type *t = base_type(proc->type);
  6303. if (t == nullptr || t->kind != Type_Proc) {
  6304. continue;
  6305. }
  6306. TypeProc *pt = &t->Proc;
  6307. if (pt->param_count == 0) {
  6308. continue;
  6309. }
  6310. for_array(j, pt->params->Tuple.variables) {
  6311. Entity *v = pt->params->Tuple.variables[j];
  6312. if (v->kind != Entity_TypeName) {
  6313. continue;
  6314. }
  6315. Type *dst_t = base_type(v->type);
  6316. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6317. dst_t = dst_t->Generic.specialized;
  6318. }
  6319. if (j >= positional_operands.count) {
  6320. continue;
  6321. }
  6322. Operand const &o = positional_operands[j];
  6323. if (o.mode != Addressing_Type) {
  6324. continue;
  6325. }
  6326. Type *t = base_type(o.type);
  6327. if (t->kind == dst_t->kind) {
  6328. continue;
  6329. }
  6330. Type *st = base_type(type_deref(o.type));
  6331. Type *dt = base_type(type_deref(dst_t));
  6332. if (st->kind == dt->kind) {
  6333. continue;
  6334. }
  6335. if (is_type_soa_struct(st)) {
  6336. possibly_ignore[i] = true;
  6337. possibly_ignore_set += 1;
  6338. continue;
  6339. }
  6340. }
  6341. }
  6342. }
  6343. if (possibly_ignore_set == procs.count) {
  6344. possibly_ignore_set = 0;
  6345. }
  6346. isize max_name_length = 0;
  6347. isize max_type_length = 0;
  6348. for_array(i, procs) {
  6349. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6350. continue;
  6351. }
  6352. Entity *proc = procs[i];
  6353. Type *t = base_type(proc->type);
  6354. if (t == t_invalid) continue;
  6355. String prefix = {};
  6356. String prefix_sep = {};
  6357. if (proc->pkg) {
  6358. prefix = proc->pkg->name;
  6359. prefix_sep = str_lit(".");
  6360. }
  6361. String name = proc->token.string;
  6362. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6363. gbString pt;
  6364. if (t->Proc.node != nullptr) {
  6365. pt = expr_to_string(t->Proc.node);
  6366. } else {
  6367. pt = type_to_string(t);
  6368. }
  6369. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6370. gb_string_free(pt);
  6371. }
  6372. isize max_spaces = gb_max(max_name_length, max_type_length);
  6373. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6374. for (isize i = 0; i < max_spaces; i++) {
  6375. spaces[i] = ' ';
  6376. }
  6377. spaces[max_spaces] = 0;
  6378. for_array(i, procs) {
  6379. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6380. continue;
  6381. }
  6382. Entity *proc = procs[i];
  6383. TokenPos pos = proc->token.pos;
  6384. Type *t = base_type(proc->type);
  6385. if (t == t_invalid) continue;
  6386. GB_ASSERT(t->kind == Type_Proc);
  6387. gbString pt;
  6388. defer (gb_string_free(pt));
  6389. if (t->Proc.node != nullptr) {
  6390. pt = expr_to_string(t->Proc.node);
  6391. } else {
  6392. pt = type_to_string(t);
  6393. }
  6394. String prefix = {};
  6395. String prefix_sep = {};
  6396. if (proc->pkg) {
  6397. prefix = proc->pkg->name;
  6398. prefix_sep = str_lit(".");
  6399. }
  6400. String name = proc->token.string;
  6401. isize len = prefix.len + prefix_sep.len + name.len;
  6402. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6403. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6404. char const *sep = "::";
  6405. if (proc->kind == Entity_Variable) {
  6406. sep = ":=";
  6407. }
  6408. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6409. LIT(prefix), LIT(prefix_sep), LIT(name),
  6410. name_padding, spaces,
  6411. sep,
  6412. pt,
  6413. type_padding, spaces,
  6414. token_pos_to_string(pos)
  6415. );
  6416. }
  6417. if (procs.count > 0) {
  6418. error_line("\n");
  6419. }
  6420. data.result_type = t_invalid;
  6421. } else if (valids.count > 1) {
  6422. ERROR_BLOCK();
  6423. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6424. if (positional_operands.count == 0 && named_operands.count == 0) {
  6425. error_line("\tNo given arguments\n");
  6426. } else {
  6427. print_argument_types();
  6428. }
  6429. for (auto const &valid : valids) {
  6430. Entity *proc = proc_entities[valid.index];
  6431. GB_ASSERT(proc != nullptr);
  6432. TokenPos pos = proc->token.pos;
  6433. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6434. gbString pt = nullptr;
  6435. defer (gb_string_free(pt));
  6436. if (t->Proc.node != nullptr) {
  6437. pt = expr_to_string(t->Proc.node);
  6438. } else {
  6439. pt = type_to_string(t);
  6440. }
  6441. String name = proc->token.string;
  6442. char const *sep = "::";
  6443. if (proc->kind == Entity_Variable) {
  6444. sep = ":=";
  6445. }
  6446. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6447. if (proc->decl_info->proc_lit != nullptr) {
  6448. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6449. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6450. if (pl->where_token.kind != Token_Invalid) {
  6451. error_line("\n\t\twhere ");
  6452. for_array(j, pl->where_clauses) {
  6453. Ast *clause = pl->where_clauses[j];
  6454. if (j != 0) {
  6455. error_line("\t\t ");
  6456. }
  6457. gbString str = expr_to_string(clause);
  6458. error_line("%s", str);
  6459. gb_string_free(str);
  6460. if (j != pl->where_clauses.count-1) {
  6461. error_line(",");
  6462. }
  6463. }
  6464. error_line("\n\t");
  6465. }
  6466. }
  6467. error_line("at %s\n", token_pos_to_string(pos));
  6468. }
  6469. data.result_type = t_invalid;
  6470. } else {
  6471. GB_ASSERT(valids.count == 1);
  6472. Ast *ident = operand->expr;
  6473. while (ident->kind == Ast_SelectorExpr) {
  6474. Ast *s = ident->SelectorExpr.selector;
  6475. ident = s;
  6476. }
  6477. Entity *e = proc_entities[valids[0].index];
  6478. GB_ASSERT(e != nullptr);
  6479. Array<Operand> named_operands = {};
  6480. check_call_arguments_single(c, call, operand,
  6481. e, e->type,
  6482. positional_operands, named_operands,
  6483. CallArgumentErrorMode::ShowErrors,
  6484. &data);
  6485. return data;
  6486. }
  6487. return data;
  6488. }
  6489. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6490. Type *proc_type = nullptr;
  6491. CallArgumentData data = {};
  6492. data.result_type = t_invalid;
  6493. proc_type = base_type(operand->type);
  6494. TypeProc *pt = nullptr;
  6495. if (proc_type) {
  6496. pt = &proc_type->Proc;
  6497. }
  6498. TEMPORARY_ALLOCATOR_GUARD();
  6499. ast_node(ce, CallExpr, call);
  6500. bool any_failure = false;
  6501. // Split positional and named args into separate arrays/slices
  6502. Slice<Ast *> positional_args = {};
  6503. Slice<Ast *> named_args = {};
  6504. if (ce->split_args == nullptr) {
  6505. positional_args = ce->args;
  6506. for (isize i = 0; i < ce->args.count; i++) {
  6507. Ast *arg = ce->args.data[i];
  6508. if (arg->kind == Ast_FieldValue) {
  6509. positional_args.count = i;
  6510. break;
  6511. }
  6512. }
  6513. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6514. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6515. split_args->positional = positional_args;
  6516. split_args->named = named_args;
  6517. ce->split_args = split_args;
  6518. } else {
  6519. positional_args = ce->split_args->positional;
  6520. named_args = ce->split_args->named;
  6521. }
  6522. if (operand->mode == Addressing_ProcGroup) {
  6523. return check_call_arguments_proc_group(c, operand, call);
  6524. }
  6525. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6526. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6527. defer (array_free(&positional_operands));
  6528. defer (array_free(&named_operands));
  6529. if (positional_args.count > 0) {
  6530. Entity **lhs = nullptr;
  6531. isize lhs_count = -1;
  6532. i32 variadic_index = -1;
  6533. if (pt != nullptr) {
  6534. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6535. if (pt->variadic) {
  6536. variadic_index = pt->variadic_index;
  6537. }
  6538. }
  6539. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6540. }
  6541. if (named_args.count > 0) {
  6542. for_array(i, named_args) {
  6543. Ast *arg = named_args[i];
  6544. if (arg->kind != Ast_FieldValue) {
  6545. error(arg, "Expected a 'field = value'");
  6546. return data;
  6547. }
  6548. ast_node(fv, FieldValue, arg);
  6549. if (fv->field->kind != Ast_Ident) {
  6550. gbString expr_str = expr_to_string(fv->field);
  6551. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6552. any_failure = true;
  6553. gb_string_free(expr_str);
  6554. continue;
  6555. }
  6556. String key = fv->field->Ident.token.string;
  6557. Ast *value = fv->value;
  6558. isize param_index = lookup_procedure_parameter(pt, key);
  6559. Type *type_hint = nullptr;
  6560. if (param_index >= 0) {
  6561. Entity *e = pt->params->Tuple.variables[param_index];
  6562. type_hint = e->type;
  6563. }
  6564. Operand o = {};
  6565. check_expr_with_type_hint(c, &o, value, type_hint);
  6566. if (o.mode == Addressing_Invalid) {
  6567. any_failure = true;
  6568. }
  6569. array_add(&named_operands, o);
  6570. }
  6571. }
  6572. if (!any_failure) {
  6573. check_call_arguments_single(c, call, operand,
  6574. nullptr, proc_type,
  6575. positional_operands, named_operands,
  6576. CallArgumentErrorMode::ShowErrors,
  6577. &data);
  6578. } else if (pt) {
  6579. data.result_type = pt->results;
  6580. }
  6581. return data;
  6582. }
  6583. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6584. if (!is_type_polymorphic_record(t)) {
  6585. return -1;
  6586. }
  6587. TypeTuple *params = get_record_polymorphic_params(t);
  6588. if (params == nullptr) {
  6589. return -1;
  6590. }
  6591. for_array(i, params->variables) {
  6592. Entity *e = params->variables[i];
  6593. String name = e->token.string;
  6594. if (is_blank_ident(name)) {
  6595. continue;
  6596. }
  6597. if (name == parameter_name) {
  6598. return i;
  6599. }
  6600. }
  6601. return -1;
  6602. }
  6603. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6604. ast_node(ce, CallExpr, call);
  6605. Type *original_type = operand->type;
  6606. GB_ASSERT(is_type_polymorphic_record(original_type));
  6607. bool show_error = true;
  6608. Array<Operand> operands = {};
  6609. defer (array_free(&operands));
  6610. CallArgumentError err = CallArgumentError_None;
  6611. bool named_fields = false;
  6612. {
  6613. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6614. auto prev_type_path = c->type_path;
  6615. c->type_path = new_checker_type_path();
  6616. defer ({
  6617. destroy_checker_type_path(c->type_path);
  6618. c->type_path = prev_type_path;
  6619. });
  6620. if (is_call_expr_field_value(ce)) {
  6621. named_fields = true;
  6622. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6623. for_array(i, ce->args) {
  6624. Ast *arg = ce->args[i];
  6625. ast_node(fv, FieldValue, arg);
  6626. if (fv->value == nullptr) {
  6627. error(fv->eq, "Expected a value");
  6628. err = CallArgumentError_InvalidFieldValue;
  6629. continue;
  6630. }
  6631. if (fv->field->kind == Ast_Ident) {
  6632. String name = fv->field->Ident.token.string;
  6633. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6634. if (index >= 0) {
  6635. TypeTuple *params = get_record_polymorphic_params(original_type);
  6636. Entity *e = params->variables[index];
  6637. if (e->kind == Entity_Constant) {
  6638. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6639. continue;
  6640. }
  6641. }
  6642. }
  6643. check_expr_or_type(c, &operands[i], fv->value);
  6644. }
  6645. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6646. if (vari_expand) {
  6647. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6648. }
  6649. } else {
  6650. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6651. Entity **lhs = nullptr;
  6652. isize lhs_count = -1;
  6653. TypeTuple *params = get_record_polymorphic_params(original_type);
  6654. if (params != nullptr) {
  6655. lhs = params->variables.data;
  6656. lhs_count = params->variables.count;
  6657. }
  6658. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6659. }
  6660. }
  6661. if (err != 0) {
  6662. operand->mode = Addressing_Invalid;
  6663. return err;
  6664. }
  6665. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6666. isize param_count = tuple->variables.count;
  6667. isize minimum_param_count = param_count;
  6668. for (; minimum_param_count > 0; minimum_param_count--) {
  6669. Entity *e = tuple->variables[minimum_param_count-1];
  6670. if (e->kind != Entity_Constant) {
  6671. break;
  6672. }
  6673. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6674. break;
  6675. }
  6676. }
  6677. Array<Operand> ordered_operands = operands;
  6678. if (!named_fields) {
  6679. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6680. array_copy(&ordered_operands, operands, 0);
  6681. } else {
  6682. TEMPORARY_ALLOCATOR_GUARD();
  6683. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6684. // LEAK(bill)
  6685. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6686. for_array(i, ce->args) {
  6687. Ast *arg = ce->args[i];
  6688. ast_node(fv, FieldValue, arg);
  6689. if (fv->field->kind != Ast_Ident) {
  6690. if (show_error) {
  6691. gbString expr_str = expr_to_string(fv->field);
  6692. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6693. gb_string_free(expr_str);
  6694. }
  6695. err = CallArgumentError_InvalidFieldValue;
  6696. continue;
  6697. }
  6698. String name = fv->field->Ident.token.string;
  6699. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6700. if (index < 0) {
  6701. if (show_error) {
  6702. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6703. }
  6704. err = CallArgumentError_ParameterNotFound;
  6705. continue;
  6706. }
  6707. if (visited[index]) {
  6708. if (show_error) {
  6709. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6710. }
  6711. err = CallArgumentError_DuplicateParameter;
  6712. continue;
  6713. }
  6714. visited[index] = true;
  6715. ordered_operands[index] = operands[i];
  6716. }
  6717. for (isize i = 0; i < param_count; i++) {
  6718. if (!visited[i]) {
  6719. Entity *e = tuple->variables[i];
  6720. if (is_blank_ident(e->token)) {
  6721. continue;
  6722. }
  6723. if (show_error) {
  6724. if (e->kind == Entity_TypeName) {
  6725. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6726. LIT(e->token.string));
  6727. } else {
  6728. gbString str = type_to_string(e->type);
  6729. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6730. LIT(e->token.string), str);
  6731. gb_string_free(str);
  6732. }
  6733. }
  6734. err = CallArgumentError_ParameterMissing;
  6735. }
  6736. }
  6737. }
  6738. if (err != 0) {
  6739. operand->mode = Addressing_Invalid;
  6740. return err;
  6741. }
  6742. while (ordered_operands.count > 0) {
  6743. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6744. break;
  6745. }
  6746. array_pop(&ordered_operands);
  6747. }
  6748. if (minimum_param_count != param_count) {
  6749. if (param_count < ordered_operands.count) {
  6750. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6751. err = CallArgumentError_TooManyArguments;
  6752. } else if (minimum_param_count > ordered_operands.count) {
  6753. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6754. err = CallArgumentError_TooFewArguments;
  6755. }
  6756. } else {
  6757. if (param_count < ordered_operands.count) {
  6758. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6759. err = CallArgumentError_TooManyArguments;
  6760. } else if (param_count > ordered_operands.count) {
  6761. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6762. err = CallArgumentError_TooFewArguments;
  6763. }
  6764. }
  6765. if (err != 0) {
  6766. return err;
  6767. }
  6768. if (minimum_param_count != param_count) {
  6769. array_resize(&ordered_operands, param_count);
  6770. isize missing_count = 0;
  6771. // NOTE(bill): Replace missing operands with the default values (if possible)
  6772. for_array(i, ordered_operands) {
  6773. Operand *o = &ordered_operands[i];
  6774. if (o->expr == nullptr) {
  6775. Entity *e = tuple->variables[i];
  6776. if (e->kind == Entity_Constant) {
  6777. missing_count += 1;
  6778. o->mode = Addressing_Constant;
  6779. o->type = default_type(e->type);
  6780. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6781. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6782. o->value = e->Constant.param_value.value;
  6783. }
  6784. } else if (e->kind == Entity_TypeName) {
  6785. missing_count += 1;
  6786. o->mode = Addressing_Type;
  6787. o->type = e->type;
  6788. o->expr = e->identifier;
  6789. }
  6790. }
  6791. }
  6792. }
  6793. isize oo_count = gb_min(param_count, ordered_operands.count);
  6794. i64 score = 0;
  6795. for (isize i = 0; i < oo_count; i++) {
  6796. Entity *e = tuple->variables[i];
  6797. Operand *o = &ordered_operands[i];
  6798. if (o->mode == Addressing_Invalid) {
  6799. continue;
  6800. }
  6801. if (e->kind == Entity_TypeName) {
  6802. if (o->mode != Addressing_Type) {
  6803. if (show_error) {
  6804. gbString expr = expr_to_string(o->expr);
  6805. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6806. gb_string_free(expr);
  6807. }
  6808. err = CallArgumentError_WrongTypes;
  6809. }
  6810. if (are_types_identical(e->type, o->type)) {
  6811. score += assign_score_function(1);
  6812. } else {
  6813. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6814. }
  6815. } else {
  6816. i64 s = 0;
  6817. if (o->type->kind == Type_Generic) {
  6818. // Polymorphic name!
  6819. score += assign_score_function(1);
  6820. continue;
  6821. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6822. if (show_error) {
  6823. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6824. }
  6825. err = CallArgumentError_WrongTypes;
  6826. }
  6827. o->type = e->type;
  6828. if (o->mode != Addressing_Constant) {
  6829. bool valid = false;
  6830. if (is_type_proc(o->type)) {
  6831. Entity *proc_entity = entity_from_expr(o->expr);
  6832. valid = proc_entity != nullptr;
  6833. }
  6834. if (!valid) {
  6835. if (show_error) {
  6836. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6837. }
  6838. err = CallArgumentError_NoneConstantParameter;
  6839. }
  6840. }
  6841. score += s;
  6842. }
  6843. // NOTE(bill): Add type info the parameters
  6844. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6845. // add_type_info_type(c, o->type);
  6846. }
  6847. if (show_error && err) {
  6848. return err;
  6849. }
  6850. {
  6851. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6852. mutex_lock(&found_gen_types->mutex);
  6853. defer (mutex_unlock(&found_gen_types->mutex));
  6854. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6855. if (found_entity) {
  6856. operand->mode = Addressing_Type;
  6857. operand->type = found_entity->type;
  6858. return err;
  6859. }
  6860. CheckerContext ctx = *c;
  6861. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6862. ctx.scope = polymorphic_record_parent_scope(original_type);
  6863. GB_ASSERT(ctx.scope != nullptr);
  6864. Type *bt = base_type(original_type);
  6865. String generated_name = make_string_c(expr_to_string(call));
  6866. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6867. if (bt->kind == Type_Struct) {
  6868. Ast *node = clone_ast(bt->Struct.node);
  6869. Type *struct_type = alloc_type_struct();
  6870. struct_type->Struct.node = node;
  6871. struct_type->Struct.polymorphic_parent = original_type;
  6872. set_base_type(named_type, struct_type);
  6873. check_open_scope(&ctx, node);
  6874. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6875. check_close_scope(&ctx);
  6876. } else if (bt->kind == Type_Union) {
  6877. Ast *node = clone_ast(bt->Union.node);
  6878. Type *union_type = alloc_type_union();
  6879. union_type->Union.node = node;
  6880. union_type->Union.polymorphic_parent = original_type;
  6881. set_base_type(named_type, union_type);
  6882. check_open_scope(&ctx, node);
  6883. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6884. check_close_scope(&ctx);
  6885. } else {
  6886. GB_PANIC("Unsupported parametric polymorphic record type");
  6887. }
  6888. bt = base_type(named_type);
  6889. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6890. GB_ASSERT(original_type->kind == Type_Named);
  6891. Entity *e = original_type->Named.type_name;
  6892. GB_ASSERT(e->kind == Entity_TypeName);
  6893. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6894. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6895. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6896. if (tuple != nullptr) for_array(i, tuple->variables) {
  6897. Entity *v = tuple->variables[i];
  6898. String name = v->token.string;
  6899. if (i > 0) {
  6900. s = gb_string_append_fmt(s, ", ");
  6901. }
  6902. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6903. if (v->kind == Entity_TypeName) {
  6904. if (v->type->kind != Type_Generic) {
  6905. s = gb_string_append_fmt(s, "=");
  6906. s = write_type_to_string(s, v->type, false);
  6907. }
  6908. } else if (v->kind == Entity_Constant) {
  6909. if (v->Constant.value.kind != ExactValue_Invalid) {
  6910. s = gb_string_append_fmt(s, "=");
  6911. s = write_exact_value_to_string(s, v->Constant.value);
  6912. }
  6913. }
  6914. }
  6915. s = gb_string_append_fmt(s, ")");
  6916. String new_name = make_string_c(s);
  6917. named_type->Named.name = new_name;
  6918. if (named_type->Named.type_name) {
  6919. named_type->Named.type_name->token.string = new_name;
  6920. }
  6921. }
  6922. operand->mode = Addressing_Type;
  6923. operand->type = named_type;
  6924. }
  6925. return err;
  6926. }
  6927. // returns true on success
  6928. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6929. bool success = true;
  6930. if (args.count > 0) {
  6931. if (allow_mixed) {
  6932. bool was_named = false;
  6933. for (Ast *arg : args) {
  6934. if (was_named && arg->kind != Ast_FieldValue) {
  6935. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6936. success = false;
  6937. break;
  6938. }
  6939. was_named = was_named || arg->kind == Ast_FieldValue;
  6940. }
  6941. } else {
  6942. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6943. for (Ast *arg : args) {
  6944. bool mix = false;
  6945. if (first_is_field_value) {
  6946. mix = arg->kind != Ast_FieldValue;
  6947. } else {
  6948. mix = arg->kind == Ast_FieldValue;
  6949. }
  6950. if (mix) {
  6951. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6952. success = false;
  6953. }
  6954. }
  6955. }
  6956. }
  6957. return success;
  6958. }
  6959. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6960. operand->mode = Addressing_Invalid; \
  6961. operand->expr = call; \
  6962. return Expr_Stmt; \
  6963. }
  6964. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6965. if (proc != nullptr &&
  6966. proc->kind == Ast_BasicDirective) {
  6967. ast_node(bd, BasicDirective, proc);
  6968. String name = bd->name.string;
  6969. if (
  6970. name == "location" ||
  6971. name == "exists" ||
  6972. name == "assert" ||
  6973. name == "panic" ||
  6974. name == "defined" ||
  6975. name == "config" ||
  6976. name == "load" ||
  6977. name == "load_directory" ||
  6978. name == "load_hash" ||
  6979. name == "hash" ||
  6980. name == "caller_expression"
  6981. ) {
  6982. operand->mode = Addressing_Builtin;
  6983. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6984. operand->expr = proc;
  6985. operand->type = t_invalid;
  6986. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6987. } else {
  6988. error(proc, "Unknown directive: #%.*s", LIT(name));
  6989. operand->expr = proc;
  6990. operand->type = t_invalid;
  6991. operand->mode = Addressing_Invalid;
  6992. return Expr_Expr;
  6993. }
  6994. if (inlining != ProcInlining_none) {
  6995. error(call, "Inlining operators are not allowed on built-in procedures");
  6996. }
  6997. } else {
  6998. if (proc != nullptr) {
  6999. check_expr_or_type(c, operand, proc);
  7000. } else {
  7001. GB_ASSERT(operand->expr != nullptr);
  7002. }
  7003. }
  7004. if (operand->mode == Addressing_Invalid) {
  7005. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  7006. for (Ast *arg : args) {
  7007. if (arg->kind == Ast_FieldValue) {
  7008. arg = arg->FieldValue.value;
  7009. }
  7010. check_expr_base(c, operand, arg, nullptr);
  7011. }
  7012. operand->mode = Addressing_Invalid;
  7013. operand->expr = call;
  7014. return Expr_Stmt;
  7015. }
  7016. if (operand->mode == Addressing_Type) {
  7017. Type *t = operand->type;
  7018. if (is_type_polymorphic_record(t)) {
  7019. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  7020. if (!is_type_named(t)) {
  7021. gbString s = expr_to_string(operand->expr);
  7022. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  7023. gb_string_free(s);
  7024. operand->mode = Addressing_Invalid;
  7025. operand->type = t_invalid;;
  7026. return Expr_Expr;
  7027. }
  7028. auto err = check_polymorphic_record_type(c, operand, call);
  7029. if (err == 0) {
  7030. Ast *ident = operand->expr;
  7031. while (ident->kind == Ast_SelectorExpr) {
  7032. Ast *s = ident->SelectorExpr.selector;
  7033. ident = s;
  7034. }
  7035. Type *ot = operand->type;
  7036. GB_ASSERT(ot->kind == Type_Named);
  7037. Entity *e = ot->Named.type_name;
  7038. add_entity_use(c, ident, e);
  7039. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  7040. } else {
  7041. operand->mode = Addressing_Invalid;
  7042. operand->type = t_invalid;
  7043. }
  7044. } else {
  7045. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  7046. operand->mode = Addressing_Invalid;
  7047. isize arg_count = args.count;
  7048. switch (arg_count) {
  7049. case 0:
  7050. {
  7051. gbString str = type_to_string(t);
  7052. error(call, "Missing argument in conversion to '%s'", str);
  7053. gb_string_free(str);
  7054. } break;
  7055. default:
  7056. {
  7057. gbString str = type_to_string(t);
  7058. if (t->kind == Type_Basic) {
  7059. ERROR_BLOCK();
  7060. switch (t->Basic.kind) {
  7061. case Basic_complex32:
  7062. case Basic_complex64:
  7063. case Basic_complex128:
  7064. error(call, "Too many arguments in conversion to '%s'", str);
  7065. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  7066. break;
  7067. case Basic_quaternion64:
  7068. case Basic_quaternion128:
  7069. case Basic_quaternion256:
  7070. error(call, "Too many arguments in conversion to '%s'", str);
  7071. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  7072. break;
  7073. default:
  7074. error(call, "Too many arguments in conversion to '%s'", str);
  7075. }
  7076. } else {
  7077. error(call, "Too many arguments in conversion to '%s'", str);
  7078. }
  7079. gb_string_free(str);
  7080. } break;
  7081. case 1: {
  7082. Ast *arg = args[0];
  7083. if (arg->kind == Ast_FieldValue) {
  7084. error(call, "'field = value' cannot be used in a type conversion");
  7085. arg = arg->FieldValue.value;
  7086. // NOTE(bill): Carry on the cast regardless
  7087. }
  7088. check_expr_with_type_hint(c, operand, arg, t);
  7089. if (operand->mode != Addressing_Invalid) {
  7090. if (is_type_polymorphic(t)) {
  7091. error(call, "A polymorphic type cannot be used in a type conversion");
  7092. } else {
  7093. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7094. // as it assumes it is determining the type
  7095. check_cast(c, operand, t);
  7096. }
  7097. }
  7098. operand->type = t;
  7099. operand->expr = call;
  7100. if (operand->mode != Addressing_Invalid) {
  7101. update_untyped_expr_type(c, arg, t, false);
  7102. }
  7103. break;
  7104. }
  7105. }
  7106. }
  7107. return Expr_Expr;
  7108. }
  7109. if (operand->mode == Addressing_Builtin) {
  7110. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7111. i32 id = operand->builtin_id;
  7112. Entity *e = entity_of_node(operand->expr);
  7113. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7114. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7115. }
  7116. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7117. operand->mode = Addressing_Invalid;
  7118. operand->type = t_invalid;
  7119. }
  7120. operand->expr = call;
  7121. return builtin_procs[id].kind;
  7122. }
  7123. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7124. Entity *initial_entity = entity_of_node(operand->expr);
  7125. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7126. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7127. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7128. if (c->decl) {
  7129. c->decl->defer_used += 1;
  7130. }
  7131. }
  7132. add_entity_use(c, operand->expr, initial_entity);
  7133. if (initial_entity->Procedure.entry_point_only) {
  7134. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7135. // Okay
  7136. } else {
  7137. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7138. }
  7139. }
  7140. }
  7141. if (operand->mode != Addressing_ProcGroup) {
  7142. Type *proc_type = base_type(operand->type);
  7143. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7144. bool valid_mode = is_operand_value(*operand);
  7145. if (!valid_type || !valid_mode) {
  7146. Ast *e = operand->expr;
  7147. gbString str = expr_to_string(e);
  7148. gbString type_str = type_to_string(operand->type);
  7149. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7150. gb_string_free(type_str);
  7151. gb_string_free(str);
  7152. operand->mode = Addressing_Invalid;
  7153. operand->expr = call;
  7154. return Expr_Stmt;
  7155. }
  7156. }
  7157. CallArgumentData data = check_call_arguments(c, operand, call);
  7158. Type *result_type = data.result_type;
  7159. gb_zero_item(operand);
  7160. operand->expr = call;
  7161. if (result_type == t_invalid) {
  7162. operand->mode = Addressing_Invalid;
  7163. operand->type = t_invalid;
  7164. return Expr_Stmt;
  7165. }
  7166. Type *pt = base_type(operand->type);
  7167. if (pt == nullptr) {
  7168. pt = t_invalid;
  7169. }
  7170. if (pt == t_invalid) {
  7171. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7172. pt = type_of_expr(operand->expr->CallExpr.proc);
  7173. }
  7174. if (pt == t_invalid && data.gen_entity) {
  7175. pt = data.gen_entity->type;
  7176. }
  7177. }
  7178. pt = base_type(pt);
  7179. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7180. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7181. ERROR_BLOCK();
  7182. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7183. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7184. }
  7185. }
  7186. if (result_type == nullptr) {
  7187. operand->mode = Addressing_NoValue;
  7188. } else {
  7189. GB_ASSERT(is_type_tuple(result_type));
  7190. isize count = result_type->Tuple.variables.count;
  7191. switch (count) {
  7192. case 0:
  7193. operand->mode = Addressing_NoValue;
  7194. break;
  7195. case 1:
  7196. operand->mode = Addressing_Value;
  7197. operand->type = result_type->Tuple.variables[0]->type;
  7198. break;
  7199. default:
  7200. operand->mode = Addressing_Value;
  7201. operand->type = result_type;
  7202. break;
  7203. }
  7204. }
  7205. bool is_call_inlined = false;
  7206. switch (inlining) {
  7207. case ProcInlining_inline:
  7208. is_call_inlined = true;
  7209. if (proc != nullptr) {
  7210. Entity *e = entity_from_expr(proc);
  7211. if (e != nullptr && e->kind == Entity_Procedure) {
  7212. DeclInfo *decl = e->decl_info;
  7213. if (decl->proc_lit) {
  7214. ast_node(pl, ProcLit, decl->proc_lit);
  7215. if (pl->inlining == ProcInlining_no_inline) {
  7216. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7217. }
  7218. }
  7219. }
  7220. }
  7221. break;
  7222. case ProcInlining_no_inline:
  7223. break;
  7224. case ProcInlining_none:
  7225. if (proc != nullptr) {
  7226. Entity *e = entity_from_expr(proc);
  7227. if (e != nullptr && e->kind == Entity_Procedure) {
  7228. DeclInfo *decl = e->decl_info;
  7229. if (decl->proc_lit) {
  7230. ast_node(pl, ProcLit, decl->proc_lit);
  7231. if (pl->inlining == ProcInlining_inline) {
  7232. is_call_inlined = true;
  7233. }
  7234. }
  7235. }
  7236. }
  7237. }
  7238. {
  7239. String invalid;
  7240. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7241. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7242. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7243. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7244. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7245. }
  7246. }
  7247. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7248. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7249. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7250. }
  7251. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7252. if (is_call_inlined) {
  7253. if (c->curr_proc_decl == nullptr) {
  7254. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7255. } else {
  7256. GB_ASSERT(c->curr_proc_decl->entity);
  7257. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7258. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7259. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7260. ERROR_BLOCK();
  7261. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7262. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7263. }
  7264. }
  7265. }
  7266. }
  7267. }
  7268. operand->expr = call;
  7269. {
  7270. Type *type = nullptr;
  7271. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7272. type = type_of_expr(operand->expr->CallExpr.proc);
  7273. }
  7274. if (type == nullptr) {
  7275. type = pt;
  7276. }
  7277. type = base_type(type);
  7278. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7279. operand->mode = Addressing_OptionalOk;
  7280. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7281. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7282. operand->expr->CallExpr.optional_ok_one = true;
  7283. }
  7284. }
  7285. }
  7286. return Expr_Expr;
  7287. }
  7288. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7289. check_expr_base(c, o, e, t);
  7290. check_not_tuple(c, o);
  7291. char const *err_str = nullptr;
  7292. switch (o->mode) {
  7293. case Addressing_NoValue:
  7294. err_str = "used as a value";
  7295. break;
  7296. case Addressing_Type:
  7297. if (t == nullptr || !is_type_typeid(t)) {
  7298. err_str = "is not an expression but a type, in this context it is ambiguous";
  7299. }
  7300. break;
  7301. case Addressing_Builtin:
  7302. err_str = "must be called";
  7303. break;
  7304. }
  7305. if (err_str != nullptr) {
  7306. gbString str = expr_to_string(e);
  7307. error(e, "'%s' %s", str, err_str);
  7308. gb_string_free(str);
  7309. o->mode = Addressing_Invalid;
  7310. }
  7311. }
  7312. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7313. switch (t->kind) {
  7314. case Type_Basic:
  7315. if (t->Basic.kind == Basic_string) {
  7316. if (o->mode == Addressing_Constant) {
  7317. GB_ASSERT(o->value.kind == ExactValue_String);
  7318. *max_count = o->value.value_string.len;
  7319. }
  7320. if (o->mode != Addressing_Constant) {
  7321. o->mode = Addressing_Value;
  7322. }
  7323. o->type = t_u8;
  7324. return true;
  7325. } else if (t->Basic.kind == Basic_string16) {
  7326. if (o->mode == Addressing_Constant) {
  7327. GB_ASSERT(o->value.kind == ExactValue_String16);
  7328. *max_count = o->value.value_string16.len;
  7329. }
  7330. if (o->mode != Addressing_Constant) {
  7331. o->mode = Addressing_Value;
  7332. }
  7333. o->type = t_u16;
  7334. return true;
  7335. } else if (t->Basic.kind == Basic_UntypedString) {
  7336. if (o->mode == Addressing_Constant) {
  7337. *max_count = o->value.value_string.len;
  7338. o->type = t_u8;
  7339. return true;
  7340. }
  7341. return false;
  7342. }
  7343. break;
  7344. case Type_MultiPointer:
  7345. o->type = t->MultiPointer.elem;
  7346. if (o->mode != Addressing_Constant) {
  7347. o->mode = Addressing_Variable;
  7348. }
  7349. return true;
  7350. case Type_Array:
  7351. *max_count = t->Array.count;
  7352. if (indirection) {
  7353. o->mode = Addressing_Variable;
  7354. } else if (o->mode != Addressing_Variable &&
  7355. o->mode != Addressing_Constant) {
  7356. o->mode = Addressing_Value;
  7357. }
  7358. o->type = t->Array.elem;
  7359. return true;
  7360. case Type_EnumeratedArray:
  7361. *max_count = t->EnumeratedArray.count;
  7362. if (indirection) {
  7363. o->mode = Addressing_Variable;
  7364. } else if (o->mode != Addressing_Variable &&
  7365. o->mode != Addressing_Constant) {
  7366. o->mode = Addressing_Value;
  7367. }
  7368. o->type = t->EnumeratedArray.elem;
  7369. return true;
  7370. case Type_Matrix:
  7371. if (indirection) {
  7372. o->mode = Addressing_Variable;
  7373. } else if (o->mode != Addressing_Variable) {
  7374. o->mode = Addressing_Value;
  7375. }
  7376. if (t->Matrix.is_row_major) {
  7377. *max_count = t->Matrix.row_count;
  7378. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7379. } else {
  7380. *max_count = t->Matrix.column_count;
  7381. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7382. }
  7383. return true;
  7384. case Type_Slice:
  7385. o->type = t->Slice.elem;
  7386. if (o->mode != Addressing_Constant) {
  7387. o->mode = Addressing_Variable;
  7388. }
  7389. return true;
  7390. case Type_DynamicArray:
  7391. o->type = t->DynamicArray.elem;
  7392. if (o->mode != Addressing_Constant) {
  7393. o->mode = Addressing_Variable;
  7394. }
  7395. return true;
  7396. case Type_Struct:
  7397. if (t->Struct.soa_kind != StructSoa_None) {
  7398. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7399. *max_count = t->Struct.soa_count;
  7400. }
  7401. o->type = t->Struct.soa_elem;
  7402. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7403. o->mode = Addressing_SoaVariable;
  7404. } else {
  7405. o->mode = Addressing_Value;
  7406. }
  7407. return true;
  7408. }
  7409. return false;
  7410. }
  7411. if (is_type_pointer(original_type) && indirection) {
  7412. Type *ptr = base_type(original_type);
  7413. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7414. o->type = ptr->MultiPointer.elem;
  7415. o->mode = Addressing_Value;
  7416. return true;
  7417. }
  7418. }
  7419. return false;
  7420. }
  7421. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7422. if (is_type_untyped_uninit(x)) {
  7423. return true;
  7424. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7425. return true;
  7426. } else if (is_type_untyped_uninit(y)) {
  7427. return true;
  7428. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7429. return true;
  7430. }
  7431. return are_types_identical(x, y);
  7432. }
  7433. gb_internal bool check_range(CheckerContext *c, Ast *node, bool is_for_loop, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  7434. if (!is_ast_range(node)) {
  7435. return false;
  7436. }
  7437. ast_node(ie, BinaryExpr, node);
  7438. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7439. if (x->mode == Addressing_Invalid) {
  7440. return false;
  7441. }
  7442. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7443. if (y->mode == Addressing_Invalid) {
  7444. return false;
  7445. }
  7446. convert_to_typed(c, x, y->type);
  7447. if (x->mode == Addressing_Invalid) {
  7448. return false;
  7449. }
  7450. convert_to_typed(c, y, x->type);
  7451. if (y->mode == Addressing_Invalid) {
  7452. return false;
  7453. }
  7454. convert_to_typed(c, x, default_type(y->type));
  7455. if (x->mode == Addressing_Invalid) {
  7456. return false;
  7457. }
  7458. convert_to_typed(c, y, default_type(x->type));
  7459. if (y->mode == Addressing_Invalid) {
  7460. return false;
  7461. }
  7462. if (!are_types_identical(x->type, y->type)) {
  7463. if (x->type != t_invalid &&
  7464. y->type != t_invalid) {
  7465. gbString xt = type_to_string(x->type);
  7466. gbString yt = type_to_string(y->type);
  7467. gbString expr_str = expr_to_string(x->expr);
  7468. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7469. gb_string_free(expr_str);
  7470. gb_string_free(yt);
  7471. gb_string_free(xt);
  7472. }
  7473. return false;
  7474. }
  7475. Type *type = x->type;
  7476. if (is_for_loop) {
  7477. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7478. error(ie->op, "Only numerical types are allowed within interval expressions");
  7479. return false;
  7480. }
  7481. } else {
  7482. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7483. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7484. return false;
  7485. }
  7486. }
  7487. if (x->mode == Addressing_Constant &&
  7488. y->mode == Addressing_Constant) {
  7489. ExactValue a = x->value;
  7490. ExactValue b = y->value;
  7491. GB_ASSERT(are_types_identical(x->type, y->type));
  7492. TokenKind op = Token_Lt;
  7493. switch (ie->op.kind) {
  7494. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7495. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7496. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7497. default: error(ie->op, "Invalid range operator"); break;
  7498. }
  7499. bool ok = compare_exact_values(op, a, b);
  7500. if (!ok) {
  7501. // TODO(bill): Better error message
  7502. error(ie->op, "Invalid interval range");
  7503. return false;
  7504. }
  7505. ExactValue inline_for_depth = exact_value_sub(b, a);
  7506. if (ie->op.kind != Token_RangeHalf) {
  7507. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7508. }
  7509. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7510. } else if (inline_for_depth_ != nullptr) {
  7511. error(ie->op, "Interval expressions must be constant");
  7512. return false;
  7513. }
  7514. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7515. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7516. return true;
  7517. }
  7518. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7519. if (is_operand_nil(*o)) {
  7520. return true;
  7521. }
  7522. Ast *expr = unparen_expr(o->expr);
  7523. if (expr != nullptr) {
  7524. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7525. if (e != nullptr && e->kind == Entity_Procedure) {
  7526. return true;
  7527. }
  7528. if (expr->kind == Ast_ProcLit) {
  7529. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7530. return true;
  7531. }
  7532. }
  7533. return o->mode == Addressing_Constant;
  7534. }
  7535. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7536. if (is_type_enum(th)) {
  7537. Type *enum_type = base_type(th);
  7538. GB_ASSERT(enum_type->kind == Type_Enum);
  7539. String name = ise->selector->Ident.token.string;
  7540. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7541. if (e == nullptr) {
  7542. return false;
  7543. }
  7544. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7545. GB_ASSERT(e->kind == Entity_Constant);
  7546. o->value = e->Constant.value;
  7547. o->mode = Addressing_Constant;
  7548. o->type = e->type;
  7549. return true;
  7550. }
  7551. if (is_type_union(th)) {
  7552. TEMPORARY_ALLOCATOR_GUARD();
  7553. Type *union_type = base_type(th);
  7554. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7555. for (Type *vt : union_type->Union.variants) {
  7556. Operand x = {};
  7557. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7558. array_add(&operands, x);
  7559. }
  7560. }
  7561. if (operands.count == 1) {
  7562. *o = operands[0];
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. }
  7568. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7569. ast_node(ise, ImplicitSelectorExpr, node);
  7570. o->type = t_invalid;
  7571. o->expr = node;
  7572. o->mode = Addressing_Invalid;
  7573. Type *th = type_hint;
  7574. if (th == nullptr) {
  7575. gbString str = expr_to_string(node);
  7576. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7577. gb_string_free(str);
  7578. return Expr_Expr;
  7579. }
  7580. o->type = th;
  7581. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7582. if (!ok) {
  7583. String name = ise->selector->Ident.token.string;
  7584. if (is_type_enum(th)) {
  7585. ERROR_BLOCK();
  7586. Type *bt = base_type(th);
  7587. GB_ASSERT(bt->kind == Type_Enum);
  7588. gbString typ = type_to_string(th);
  7589. defer (gb_string_free(typ));
  7590. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7591. check_did_you_mean_type(name, bt->Enum.fields);
  7592. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7593. ERROR_BLOCK();
  7594. gbString typ = type_to_string(th);
  7595. gbString str = expr_to_string(node);
  7596. error(node, "Cannot convert enum value to '%s'", typ);
  7597. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7598. gb_string_free(typ);
  7599. gb_string_free(str);
  7600. } else {
  7601. gbString typ = type_to_string(th);
  7602. gbString str = expr_to_string(node);
  7603. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7604. gb_string_free(str);
  7605. gb_string_free(typ);
  7606. }
  7607. }
  7608. o->expr = node;
  7609. return Expr_Expr;
  7610. }
  7611. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7612. switch (x->mode) {
  7613. case Addressing_MapIndex:
  7614. case Addressing_OptionalOk:
  7615. case Addressing_OptionalOkPtr:
  7616. if (val_type_) *val_type_ = x->type;
  7617. break;
  7618. default:
  7619. if (ok_type_) *ok_type_ = x->type;
  7620. return;
  7621. }
  7622. Ast *expr = unparen_expr(x->expr);
  7623. if (expr->kind == Ast_CallExpr) {
  7624. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7625. if (is_type_proc(pt)) {
  7626. Type *tuple = pt->Proc.results;
  7627. if (pt->Proc.result_count >= 2) {
  7628. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7629. }
  7630. if (change_operand) {
  7631. expr->CallExpr.optional_ok_one = false;
  7632. x->type = tuple;
  7633. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7634. }
  7635. return;
  7636. }
  7637. }
  7638. Type *tuple = make_optional_ok_type(x->type);
  7639. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7640. if (change_operand) {
  7641. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7642. x->type = tuple;
  7643. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7644. }
  7645. }
  7646. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7647. ast_node(ie, MatrixIndexExpr, node);
  7648. check_expr(c, o, ie->expr);
  7649. node->viral_state_flags |= ie->expr->viral_state_flags;
  7650. if (o->mode == Addressing_Invalid) {
  7651. o->expr = node;
  7652. return;
  7653. }
  7654. Type *t = base_type(type_deref(o->type));
  7655. bool is_ptr = is_type_pointer(o->type);
  7656. bool is_const = o->mode == Addressing_Constant;
  7657. if (t->kind != Type_Matrix) {
  7658. gbString str = expr_to_string(o->expr);
  7659. gbString type_str = type_to_string(o->type);
  7660. defer (gb_string_free(str));
  7661. defer (gb_string_free(type_str));
  7662. if (is_const) {
  7663. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7664. } else {
  7665. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7666. }
  7667. o->mode = Addressing_Invalid;
  7668. o->expr = node;
  7669. return;
  7670. }
  7671. o->type = t->Matrix.elem;
  7672. if (is_ptr) {
  7673. o->mode = Addressing_Variable;
  7674. } else if (o->mode != Addressing_Variable) {
  7675. o->mode = Addressing_Value;
  7676. }
  7677. if (ie->row_index == nullptr) {
  7678. gbString str = expr_to_string(o->expr);
  7679. error(o->expr, "Missing row index for '%s'", str);
  7680. gb_string_free(str);
  7681. o->mode = Addressing_Invalid;
  7682. o->expr = node;
  7683. return;
  7684. }
  7685. if (ie->column_index == nullptr) {
  7686. gbString str = expr_to_string(o->expr);
  7687. error(o->expr, "Missing column index for '%s'", str);
  7688. gb_string_free(str);
  7689. o->mode = Addressing_Invalid;
  7690. o->expr = node;
  7691. return;
  7692. }
  7693. i64 row_count = t->Matrix.row_count;
  7694. i64 column_count = t->Matrix.column_count;
  7695. i64 row_index = 0;
  7696. i64 column_index = 0;
  7697. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7698. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7699. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7700. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7701. }
  7702. gb_unused(row_ok);
  7703. gb_unused(column_ok);
  7704. }
  7705. struct TypeAndToken {
  7706. Type *type;
  7707. Token token;
  7708. };
  7709. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7710. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7711. if (operand.mode != Addressing_Constant) {
  7712. return;
  7713. }
  7714. if (operand.value.kind == ExactValue_Invalid) {
  7715. return;
  7716. }
  7717. uintptr key = hash_exact_value(operand.value);
  7718. GB_ASSERT(key != 0);
  7719. isize count = multi_map_count(seen, key);
  7720. if (count) {
  7721. TEMPORARY_ALLOCATOR_GUARD();
  7722. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7723. multi_map_get_all(seen, key, taps);
  7724. for (isize i = 0; i < count; i++) {
  7725. TypeAndToken tap = taps[i];
  7726. Operand to = {};
  7727. to.mode = Addressing_Value;
  7728. to.type = tap.type;
  7729. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7730. continue;
  7731. }
  7732. TokenPos pos = tap.token.pos;
  7733. if (use_expr) {
  7734. gbString expr_str = expr_to_string(operand.expr);
  7735. error(operand.expr,
  7736. "Duplicate case '%s'\n"
  7737. "\tprevious case at %s",
  7738. expr_str,
  7739. token_pos_to_string(pos));
  7740. gb_string_free(expr_str);
  7741. } else {
  7742. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7743. }
  7744. return;
  7745. }
  7746. }
  7747. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7748. multi_map_insert(seen, key, tap);
  7749. }
  7750. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7751. if (is_type_enum(x.type)) {
  7752. // TODO(bill): Fix this logic so it's fast!!!
  7753. i64 v0 = exact_value_to_i64(lhs.value);
  7754. i64 v1 = exact_value_to_i64(rhs.value);
  7755. Operand v = {};
  7756. v.mode = Addressing_Constant;
  7757. v.type = x.type;
  7758. v.expr = x.expr;
  7759. Type *bt = base_type(x.type);
  7760. GB_ASSERT(bt->kind == Type_Enum);
  7761. for (i64 vi = v0; vi <= v1; vi++) {
  7762. if (upper_op != Token_LtEq && vi == v1) {
  7763. break;
  7764. }
  7765. v.value = exact_value_i64(vi);
  7766. add_constant_switch_case(ctx, seen, v);
  7767. }
  7768. } else {
  7769. add_constant_switch_case(ctx, seen, lhs);
  7770. if (upper_op == Token_LtEq) {
  7771. add_constant_switch_case(ctx, seen, rhs);
  7772. }
  7773. }
  7774. }
  7775. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7776. add_constant_switch_case(ctx, seen, x);
  7777. }
  7778. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7779. ast_node(bd, BasicDirective, node);
  7780. ExprKind kind = Expr_Expr;
  7781. o->mode = Addressing_Constant;
  7782. String name = bd->name.string;
  7783. if (name == "file") {
  7784. String file = get_file_path_string(bd->token.pos.file_id);
  7785. switch (build_context.source_code_location_info) {
  7786. case SourceCodeLocationInfo_Normal:
  7787. break;
  7788. case SourceCodeLocationInfo_Obfuscated:
  7789. file = obfuscate_string(file, "F");
  7790. break;
  7791. case SourceCodeLocationInfo_Filename:
  7792. file = last_path_element(file);
  7793. break;
  7794. case SourceCodeLocationInfo_None:
  7795. file = str_lit("");
  7796. break;
  7797. }
  7798. o->type = t_untyped_string;
  7799. o->value = exact_value_string(file);
  7800. } else if (name == "directory") {
  7801. String file = get_file_path_string(bd->token.pos.file_id);
  7802. String path = dir_from_path(file);
  7803. switch (build_context.source_code_location_info) {
  7804. case SourceCodeLocationInfo_Normal:
  7805. break;
  7806. case SourceCodeLocationInfo_Obfuscated:
  7807. path = obfuscate_string(path, "D");
  7808. break;
  7809. case SourceCodeLocationInfo_Filename:
  7810. path = last_path_element(path);
  7811. break;
  7812. case SourceCodeLocationInfo_None:
  7813. path = str_lit("");
  7814. break;
  7815. }
  7816. o->type = t_untyped_string;
  7817. o->value = exact_value_string(path);
  7818. } else if (name == "line") {
  7819. i32 line = bd->token.pos.line;
  7820. switch (build_context.source_code_location_info) {
  7821. case SourceCodeLocationInfo_Normal:
  7822. break;
  7823. case SourceCodeLocationInfo_Obfuscated:
  7824. line = obfuscate_i32(line);
  7825. break;
  7826. case SourceCodeLocationInfo_Filename:
  7827. break;
  7828. case SourceCodeLocationInfo_None:
  7829. line = 0;
  7830. break;
  7831. }
  7832. o->type = t_untyped_integer;
  7833. o->value = exact_value_i64(line);
  7834. } else if (name == "procedure") {
  7835. if (c->curr_proc_decl == nullptr) {
  7836. error(node, "#procedure may only be used within procedures");
  7837. o->type = t_untyped_string;
  7838. o->value = exact_value_string(str_lit(""));
  7839. } else {
  7840. String p = c->proc_name;
  7841. switch (build_context.source_code_location_info) {
  7842. case SourceCodeLocationInfo_Normal:
  7843. break;
  7844. case SourceCodeLocationInfo_Obfuscated:
  7845. p = obfuscate_string(p, "P");
  7846. break;
  7847. case SourceCodeLocationInfo_Filename:
  7848. break;
  7849. case SourceCodeLocationInfo_None:
  7850. p = str_lit("");
  7851. break;
  7852. }
  7853. o->type = t_untyped_string;
  7854. o->value = exact_value_string(p);
  7855. }
  7856. } else if (name == "caller_location") {
  7857. init_core_source_code_location(c->checker);
  7858. error(node, "#caller_location may only be used as a default argument parameter");
  7859. o->type = t_source_code_location;
  7860. o->mode = Addressing_Value;
  7861. } else if (name == "caller_expression") {
  7862. error(node, "#caller_expression may only be used as a default argument parameter");
  7863. o->type = t_string;
  7864. o->mode = Addressing_Value;
  7865. } else if (name == "branch_location") {
  7866. if (!c->in_defer) {
  7867. error(node, "#branch_location may only be used within a 'defer' statement");
  7868. } else if (c->curr_proc_decl) {
  7869. Entity *e = c->curr_proc_decl->entity;
  7870. if (e != nullptr) {
  7871. GB_ASSERT(e->kind == Entity_Procedure);
  7872. e->Procedure.uses_branch_location = true;
  7873. }
  7874. }
  7875. o->type = t_source_code_location;
  7876. o->mode = Addressing_Value;
  7877. } else {
  7878. if (name == "location") {
  7879. init_core_source_code_location(c->checker);
  7880. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7881. o->type = t_source_code_location;
  7882. o->mode = Addressing_Value;
  7883. } else if (
  7884. name == "assert" ||
  7885. name == "defined" ||
  7886. name == "config" ||
  7887. name == "exists" ||
  7888. name == "load" ||
  7889. name == "load_hash" ||
  7890. name == "load_directory" ||
  7891. name == "load_or"
  7892. ) {
  7893. error(node, "'#%.*s' must be used as a call", LIT(name));
  7894. o->type = t_invalid;
  7895. o->mode = Addressing_Invalid;
  7896. } else {
  7897. error(node, "Unknown directive: #%.*s", LIT(name));
  7898. o->type = t_invalid;
  7899. o->mode = Addressing_Invalid;
  7900. }
  7901. }
  7902. return kind;
  7903. }
  7904. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7905. ExprKind kind = Expr_Expr;
  7906. Operand cond = {Addressing_Invalid};
  7907. ast_node(te, TernaryIfExpr, node);
  7908. check_expr(c, &cond, te->cond);
  7909. node->viral_state_flags |= te->cond->viral_state_flags;
  7910. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7911. error(te->cond, "Non-boolean condition in ternary if expression");
  7912. }
  7913. Operand x = {Addressing_Invalid};
  7914. Operand y = {Addressing_Invalid};
  7915. check_expr_or_type(c, &x, te->x, type_hint);
  7916. node->viral_state_flags |= te->x->viral_state_flags;
  7917. if (te->y != nullptr) {
  7918. Type *th = type_hint;
  7919. if (type_hint == nullptr && is_type_typed(x.type)) {
  7920. th = x.type;
  7921. }
  7922. check_expr_or_type(c, &y, te->y, th);
  7923. node->viral_state_flags |= te->y->viral_state_flags;
  7924. } else {
  7925. error(node, "A ternary expression must have an else clause");
  7926. return kind;
  7927. }
  7928. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7929. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7930. gbString type_string = expr_to_string(type_expr);
  7931. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7932. gb_string_free(type_string);
  7933. return kind;
  7934. }
  7935. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7936. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7937. if (x.mode == Addressing_Invalid) {
  7938. return kind;
  7939. }
  7940. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7941. if (y.mode == Addressing_Invalid) {
  7942. x.mode = Addressing_Invalid;
  7943. return kind;
  7944. }
  7945. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7946. // x: union{f32} = f32(123) if cond else nil
  7947. if (type_hint && !is_type_any(type_hint)) {
  7948. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7949. check_cast(c, &x, type_hint);
  7950. check_cast(c, &y, type_hint);
  7951. }
  7952. }
  7953. if (!ternary_compare_types(x.type, y.type)) {
  7954. gbString its = type_to_string(x.type);
  7955. gbString ets = type_to_string(y.type);
  7956. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7957. gb_string_free(ets);
  7958. gb_string_free(its);
  7959. return kind;
  7960. }
  7961. o->type = x.type;
  7962. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7963. o->type = y.type;
  7964. }
  7965. o->mode = Addressing_Value;
  7966. o->expr = node;
  7967. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7968. if (check_cast_internal(c, &x, type_hint) &&
  7969. check_cast_internal(c, &y, type_hint)) {
  7970. convert_to_typed(c, o, type_hint);
  7971. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7972. o->type = type_hint;
  7973. }
  7974. }
  7975. return kind;
  7976. }
  7977. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7978. ExprKind kind = Expr_Expr;
  7979. Operand cond = {};
  7980. ast_node(te, TernaryWhenExpr, node);
  7981. check_expr(c, &cond, te->cond);
  7982. node->viral_state_flags |= te->cond->viral_state_flags;
  7983. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7984. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7985. return kind;
  7986. }
  7987. if (cond.value.value_bool) {
  7988. check_expr_or_type(c, o, te->x, type_hint);
  7989. node->viral_state_flags |= te->x->viral_state_flags;
  7990. } else {
  7991. if (te->y != nullptr) {
  7992. check_expr_or_type(c, o, te->y, type_hint);
  7993. node->viral_state_flags |= te->y->viral_state_flags;
  7994. } else {
  7995. error(node, "A ternary when expression must have an else clause");
  7996. return kind;
  7997. }
  7998. }
  7999. return kind;
  8000. }
  8001. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8002. ast_node(oe, OrElseExpr, node);
  8003. String name = oe->token.string;
  8004. Ast *arg = oe->x;
  8005. Ast *default_value = oe->y;
  8006. Operand x = {};
  8007. Operand y = {};
  8008. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  8009. if (is_load_directive_call(arg)) {
  8010. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  8011. // Allow for chaining of '#load(path) or_else #load(path)'
  8012. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  8013. bool y_is_diverging = false;
  8014. check_expr_base(c, &y, default_value, x.type);
  8015. switch (y.mode) {
  8016. case Addressing_NoValue:
  8017. if (is_diverging_expr(y.expr)) {
  8018. // Allow
  8019. y.mode = Addressing_Value;
  8020. y_is_diverging = true;
  8021. } else {
  8022. error_operand_no_value(&y);
  8023. y.mode = Addressing_Invalid;
  8024. }
  8025. break;
  8026. case Addressing_Type:
  8027. error_operand_not_expression(&y);
  8028. y.mode = Addressing_Invalid;
  8029. break;
  8030. }
  8031. if (y.mode == Addressing_Invalid) {
  8032. o->mode = Addressing_Value;
  8033. o->type = t_invalid;
  8034. o->expr = node;
  8035. return Expr_Expr;
  8036. }
  8037. if (!y_is_diverging) {
  8038. check_assignment(c, &y, x.type, name);
  8039. if (y.mode != Addressing_Constant) {
  8040. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  8041. }
  8042. }
  8043. }
  8044. if (res == LoadDirective_Success) {
  8045. *o = x;
  8046. } else {
  8047. *o = y;
  8048. }
  8049. o->expr = node;
  8050. return Expr_Expr;
  8051. }
  8052. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  8053. if (x.mode == Addressing_Invalid) {
  8054. o->mode = Addressing_Value;
  8055. o->type = t_invalid;
  8056. o->expr = node;
  8057. return Expr_Expr;
  8058. }
  8059. Type *left_type = nullptr;
  8060. Type *right_type = nullptr;
  8061. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  8062. add_type_and_value(c, arg, x.mode, x.type, x.value);
  8063. bool y_is_diverging = false;
  8064. check_expr_base(c, &y, default_value, left_type);
  8065. switch (y.mode) {
  8066. case Addressing_NoValue:
  8067. if (is_diverging_expr(y.expr)) {
  8068. // Allow
  8069. y.mode = Addressing_Value;
  8070. y_is_diverging = true;
  8071. } else {
  8072. error_operand_no_value(&y);
  8073. y.mode = Addressing_Invalid;
  8074. }
  8075. break;
  8076. case Addressing_Type:
  8077. error_operand_not_expression(&y);
  8078. y.mode = Addressing_Invalid;
  8079. break;
  8080. }
  8081. if (y.mode == Addressing_Invalid) {
  8082. o->mode = Addressing_Value;
  8083. o->type = t_invalid;
  8084. o->expr = node;
  8085. return Expr_Expr;
  8086. }
  8087. if (left_type != nullptr) {
  8088. if (!y_is_diverging) {
  8089. if (is_type_tuple(left_type)) {
  8090. if (!is_type_tuple(y.type)) {
  8091. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  8092. } else if (!are_types_identical(left_type, y.type)) {
  8093. gbString xt = type_to_string(left_type);
  8094. gbString yt = type_to_string(y.type);
  8095. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  8096. gb_string_free(yt);
  8097. gb_string_free(xt);
  8098. }
  8099. } else {
  8100. check_assignment(c, &y, left_type, name);
  8101. }
  8102. }
  8103. } else {
  8104. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8105. }
  8106. if (left_type == nullptr) {
  8107. left_type = t_invalid;
  8108. }
  8109. o->mode = Addressing_Value;
  8110. o->type = left_type;
  8111. o->expr = node;
  8112. return Expr_Expr;
  8113. }
  8114. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8115. ast_node(re, OrReturnExpr, node);
  8116. String name = re->token.string;
  8117. Operand x = {};
  8118. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  8119. if (x.mode == Addressing_Invalid) {
  8120. o->mode = Addressing_Value;
  8121. o->type = t_invalid;
  8122. o->expr = node;
  8123. return Expr_Expr;
  8124. }
  8125. Type *left_type = nullptr;
  8126. Type *right_type = nullptr;
  8127. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8128. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  8129. if (right_type == nullptr) {
  8130. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8131. } else {
  8132. Type *proc_type = base_type(c->curr_proc_sig);
  8133. GB_ASSERT(proc_type->kind == Type_Proc);
  8134. Type *result_type = proc_type->Proc.results;
  8135. if (result_type == nullptr) {
  8136. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8137. } else {
  8138. GB_ASSERT(result_type->kind == Type_Tuple);
  8139. auto const &vars = result_type->Tuple.variables;
  8140. Type *end_type = vars[vars.count-1]->type;
  8141. if (vars.count > 1) {
  8142. if (!proc_type->Proc.has_named_results) {
  8143. 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));
  8144. }
  8145. }
  8146. Operand rhs = {};
  8147. rhs.type = right_type;
  8148. rhs.mode = Addressing_Value;
  8149. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8150. // NOTE(bill): allow implicit conversion between boolean types
  8151. // within 'or_return' to improve the experience using third-party code
  8152. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8153. ERROR_BLOCK();
  8154. // TODO(bill): better error message
  8155. gbString a = type_to_string(right_type);
  8156. gbString b = type_to_string(end_type);
  8157. gbString ret_type = type_to_string(result_type);
  8158. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8159. if (vars.count == 1) {
  8160. error_line("\tProcedure return value type: %s\n", ret_type);
  8161. } else {
  8162. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8163. }
  8164. gb_string_free(ret_type);
  8165. gb_string_free(b);
  8166. gb_string_free(a);
  8167. }
  8168. }
  8169. }
  8170. o->expr = node;
  8171. o->type = left_type;
  8172. if (left_type != nullptr) {
  8173. o->mode = Addressing_Value;
  8174. } else {
  8175. o->mode = Addressing_NoValue;
  8176. }
  8177. if (c->curr_proc_sig == nullptr) {
  8178. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8179. }
  8180. if (c->in_defer) {
  8181. error(node, "'or_return' cannot be used within a defer statement");
  8182. }
  8183. return Expr_Expr;
  8184. }
  8185. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8186. ast_node(be, OrBranchExpr, node);
  8187. String name = be->token.string;
  8188. Operand x = {};
  8189. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8190. if (x.mode == Addressing_Invalid) {
  8191. o->mode = Addressing_Value;
  8192. o->type = t_invalid;
  8193. o->expr = node;
  8194. return Expr_Expr;
  8195. }
  8196. Type *left_type = nullptr;
  8197. Type *right_type = nullptr;
  8198. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8199. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8200. if (right_type == nullptr) {
  8201. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8202. } else {
  8203. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8204. // okay
  8205. } else {
  8206. gbString s = type_to_string(right_type);
  8207. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8208. gb_string_free(s);
  8209. }
  8210. }
  8211. o->expr = node;
  8212. o->type = left_type;
  8213. if (left_type != nullptr) {
  8214. o->mode = Addressing_Value;
  8215. } else {
  8216. o->mode = Addressing_NoValue;
  8217. }
  8218. if (c->curr_proc_sig == nullptr) {
  8219. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8220. }
  8221. Ast *label = be->label;
  8222. switch (be->token.kind) {
  8223. case Token_or_break:
  8224. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8225. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8226. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8227. }
  8228. break;
  8229. case Token_or_continue:
  8230. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8231. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8232. }
  8233. break;
  8234. }
  8235. if (label != nullptr) {
  8236. if (c->in_defer) {
  8237. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8238. return Expr_Expr;
  8239. }
  8240. if (label->kind != Ast_Ident) {
  8241. error(label, "A branch statement's label name must be an identifier");
  8242. return Expr_Expr;
  8243. }
  8244. Ast *ident = label;
  8245. String name = ident->Ident.token.string;
  8246. Operand o = {};
  8247. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8248. if (e == nullptr) {
  8249. error(ident, "Undeclared label name: %.*s", LIT(name));
  8250. return Expr_Expr;
  8251. }
  8252. add_entity_use(c, ident, e);
  8253. if (e->kind != Entity_Label) {
  8254. error(ident, "'%.*s' is not a label", LIT(name));
  8255. return Expr_Expr;
  8256. }
  8257. Ast *parent = e->Label.parent;
  8258. GB_ASSERT(parent != nullptr);
  8259. switch (parent->kind) {
  8260. case Ast_BlockStmt:
  8261. case Ast_IfStmt:
  8262. case Ast_SwitchStmt:
  8263. if (be->token.kind != Token_or_break) {
  8264. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8265. }
  8266. break;
  8267. case Ast_RangeStmt:
  8268. case Ast_ForStmt:
  8269. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8270. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8271. }
  8272. break;
  8273. }
  8274. }
  8275. return Expr_Expr;
  8276. }
  8277. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8278. Type *bt = base_type(type);
  8279. StringSet fields_visited = {};
  8280. defer (string_set_destroy(&fields_visited));
  8281. StringMap<String> fields_visited_through_raw_union = {};
  8282. defer (string_map_destroy(&fields_visited_through_raw_union));
  8283. String assignment_str = str_lit("structure literal");
  8284. if (bt->kind == Type_BitField) {
  8285. assignment_str = str_lit("bit_field literal");
  8286. }
  8287. for (Ast *elem : elems) {
  8288. if (elem->kind != Ast_FieldValue) {
  8289. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8290. continue;
  8291. }
  8292. ast_node(fv, FieldValue, elem);
  8293. Ast *ident = fv->field;
  8294. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8295. gbString expr_str = expr_to_string(ident);
  8296. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8297. gb_string_free(expr_str);
  8298. ident = ident->ImplicitSelectorExpr.selector;
  8299. }
  8300. if (ident->kind != Ast_Ident) {
  8301. gbString expr_str = expr_to_string(ident);
  8302. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8303. gb_string_free(expr_str);
  8304. continue;
  8305. }
  8306. String name = ident->Ident.token.string;
  8307. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8308. bool is_unknown = sel.entity == nullptr;
  8309. if (is_unknown) {
  8310. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8311. continue;
  8312. }
  8313. Entity *field = nullptr;
  8314. if (bt->kind == Type_Struct) {
  8315. field = bt->Struct.fields[sel.index[0]];
  8316. } else if (bt->kind == Type_BitField) {
  8317. field = bt->BitField.fields[sel.index[0]];
  8318. } else {
  8319. GB_PANIC("Unknown type");
  8320. }
  8321. add_entity_use(c, ident, field);
  8322. if (string_set_update(&fields_visited, name)) {
  8323. if (sel.index.count > 1) {
  8324. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8325. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8326. } else {
  8327. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8328. }
  8329. } else {
  8330. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8331. }
  8332. continue;
  8333. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8334. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8335. continue;
  8336. }
  8337. if (sel.indirect) {
  8338. error(ident, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a %.*s", cast(int)sel.index.count-1, LIT(name), LIT(assignment_str));
  8339. continue;
  8340. }
  8341. if (sel.index.count > 1) {
  8342. GB_ASSERT(bt->kind == Type_Struct);
  8343. if (is_constant) {
  8344. Type *ft = type;
  8345. for (i32 index : sel.index) {
  8346. Type *bt = base_type(ft);
  8347. switch (bt->kind) {
  8348. case Type_Struct:
  8349. if (bt->Struct.is_raw_union) {
  8350. is_constant = false;
  8351. break;
  8352. }
  8353. ft = bt->Struct.fields[index]->type;
  8354. break;
  8355. case Type_Array:
  8356. ft = bt->Array.elem;
  8357. break;
  8358. case Type_BitField:
  8359. is_constant = false;
  8360. ft = bt->BitField.fields[index]->type;
  8361. break;
  8362. default:
  8363. GB_PANIC("invalid type: %s", type_to_string(ft));
  8364. break;
  8365. }
  8366. }
  8367. if (is_constant &&
  8368. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8369. is_constant = false;
  8370. }
  8371. }
  8372. Type *nested_ft = bt;
  8373. for (i32 index : sel.index) {
  8374. Type *bt = base_type(nested_ft);
  8375. switch (bt->kind) {
  8376. case Type_Struct:
  8377. if (bt->Struct.is_raw_union) {
  8378. for (Entity *re : bt->Struct.fields) {
  8379. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8380. }
  8381. }
  8382. nested_ft = bt->Struct.fields[index]->type;
  8383. break;
  8384. case Type_Array:
  8385. nested_ft = bt->Array.elem;
  8386. break;
  8387. case Type_BitField:
  8388. nested_ft = bt->BitField.fields[index]->type;
  8389. break;
  8390. default:
  8391. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8392. break;
  8393. }
  8394. }
  8395. field = sel.entity;
  8396. }
  8397. Operand o = {};
  8398. check_expr_or_type(c, &o, fv->value, field->type);
  8399. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8400. is_constant = false;
  8401. }
  8402. if (is_constant) {
  8403. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8404. }
  8405. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8406. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8407. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8408. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8409. }
  8410. check_assignment(c, &o, field->type, assignment_str);
  8411. c->bit_field_bit_size = prev_bit_field_bit_size;
  8412. }
  8413. }
  8414. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8415. type_expr = unparen_expr(type_expr);
  8416. if (type_expr == nullptr) {
  8417. return false;
  8418. }
  8419. // [?]Type
  8420. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8421. Ast *count = type_expr->ArrayType.count;
  8422. if (count->kind == Ast_UnaryExpr &&
  8423. count->UnaryExpr.op.kind == Token_Question) {
  8424. return true;
  8425. }
  8426. }
  8427. return false;
  8428. }
  8429. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8430. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8431. ERROR_BLOCK();
  8432. error(node, "Compound literals of dynamic types are disabled by default");
  8433. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8434. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8435. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8436. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8437. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8438. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8439. }
  8440. return false;
  8441. }
  8442. return cl->elems.count > 0;
  8443. }
  8444. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8445. ExprKind kind = Expr_Expr;
  8446. ast_node(cl, CompoundLit, node);
  8447. Type *type = type_hint;
  8448. if (type != nullptr && is_type_untyped(type)) {
  8449. type = nullptr;
  8450. }
  8451. bool is_to_be_determined_array_count = false;
  8452. bool is_constant = true;
  8453. bool is_soa = false;
  8454. Ast *type_expr = cl->type;
  8455. bool used_type_hint_expr = false;
  8456. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8457. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8458. type_expr = clone_ast(c->type_hint_expr);
  8459. used_type_hint_expr = true;
  8460. }
  8461. }
  8462. if (type_expr != nullptr) {
  8463. type = nullptr;
  8464. // [?]Type
  8465. if (type_expr->kind == Ast_ArrayType) {
  8466. Ast *count = type_expr->ArrayType.count;
  8467. if (count != nullptr) {
  8468. if (count->kind == Ast_UnaryExpr &&
  8469. count->UnaryExpr.op.kind == Token_Question) {
  8470. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8471. is_to_be_determined_array_count = true;
  8472. }
  8473. } else {
  8474. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8475. }
  8476. if (cl->elems.count > 0) {
  8477. if (type_expr->ArrayType.tag != nullptr) {
  8478. Ast *tag = type_expr->ArrayType.tag;
  8479. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8480. String name = tag->BasicDirective.name.string;
  8481. if (name == "soa") {
  8482. is_soa = true;
  8483. if (count == nullptr) {
  8484. error(node, "#soa slices are not supported for compound literals");
  8485. return kind;
  8486. } else if (count->kind == Ast_UnaryExpr &&
  8487. count->UnaryExpr.op.kind == Token_Question) {
  8488. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8489. }
  8490. }
  8491. }
  8492. }
  8493. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8494. if (cl->elems.count > 0) {
  8495. Ast *tag = type_expr->DynamicArrayType.tag;
  8496. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8497. String name = tag->BasicDirective.name.string;
  8498. if (name == "soa") {
  8499. is_soa = true;
  8500. error(node, "#soa dynamic arrays are not supported for compound literals");
  8501. return kind;
  8502. }
  8503. }
  8504. }
  8505. if (type == nullptr) {
  8506. type = check_type(c, type_expr);
  8507. }
  8508. }
  8509. if (type == nullptr) {
  8510. error(node, "Missing type in compound literal");
  8511. return kind;
  8512. }
  8513. Type *t = base_type(type);
  8514. if (is_type_polymorphic(t)) {
  8515. gbString str = type_to_string(type);
  8516. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8517. o->expr = node;
  8518. o->type = type;
  8519. gb_string_free(str);
  8520. return kind;
  8521. }
  8522. switch (t->kind) {
  8523. case Type_Struct:
  8524. if (cl->elems.count == 0) {
  8525. break; // NOTE(bill): No need to init
  8526. }
  8527. if (t->Struct.soa_kind == StructSoa_None) {
  8528. if (t->Struct.is_raw_union) {
  8529. if (cl->elems.count > 0) {
  8530. // NOTE: unions cannot be constant
  8531. is_constant = false;
  8532. if (cl->elems[0]->kind != Ast_FieldValue) {
  8533. gbString type_str = type_to_string(type);
  8534. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8535. gb_string_free(type_str);
  8536. } else {
  8537. if (cl->elems.count != 1) {
  8538. gbString type_str = type_to_string(type);
  8539. 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);
  8540. gb_string_free(type_str);
  8541. } else {
  8542. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8543. }
  8544. }
  8545. }
  8546. break;
  8547. }
  8548. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8549. isize field_count = t->Struct.fields.count;
  8550. isize min_field_count = t->Struct.fields.count;
  8551. for (isize i = min_field_count-1; i >= 0; i--) {
  8552. Entity *e = t->Struct.fields[i];
  8553. GB_ASSERT(e->kind == Entity_Variable);
  8554. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8555. min_field_count--;
  8556. } else {
  8557. break;
  8558. }
  8559. }
  8560. if (cl->elems[0]->kind == Ast_FieldValue) {
  8561. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8562. } else {
  8563. bool seen_field_value = false;
  8564. for_array(index, cl->elems) {
  8565. Entity *field = nullptr;
  8566. Ast *elem = cl->elems[index];
  8567. if (elem->kind == Ast_FieldValue) {
  8568. seen_field_value = true;
  8569. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8570. continue;
  8571. } else if (seen_field_value) {
  8572. error(elem, "Value elements cannot be used after a 'field = value'");
  8573. continue;
  8574. }
  8575. if (index >= field_count) {
  8576. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8577. break;
  8578. }
  8579. if (field == nullptr) {
  8580. field = t->Struct.fields[index];
  8581. }
  8582. Operand o = {};
  8583. check_expr_or_type(c, &o, elem, field->type);
  8584. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8585. is_constant = false;
  8586. }
  8587. if (is_constant) {
  8588. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8589. }
  8590. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8591. }
  8592. if (cl->elems.count < field_count) {
  8593. if (min_field_count < field_count) {
  8594. if (cl->elems.count < min_field_count) {
  8595. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8596. }
  8597. } else {
  8598. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8599. }
  8600. }
  8601. }
  8602. break;
  8603. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8604. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8605. break;
  8606. }
  8607. /*fallthrough*/
  8608. case Type_Slice:
  8609. case Type_Array:
  8610. case Type_DynamicArray:
  8611. case Type_SimdVector:
  8612. case Type_Matrix:
  8613. {
  8614. Type *elem_type = nullptr;
  8615. String context_name = {};
  8616. i64 max_type_count = -1;
  8617. if (t->kind == Type_Struct) {
  8618. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8619. elem_type = t->Struct.soa_elem;
  8620. context_name = str_lit("#soa array literal");
  8621. if (!is_to_be_determined_array_count) {
  8622. max_type_count = t->Struct.soa_count;
  8623. }
  8624. } else if (t->kind == Type_Slice) {
  8625. elem_type = t->Slice.elem;
  8626. context_name = str_lit("slice literal");
  8627. } else if (t->kind == Type_Array) {
  8628. elem_type = t->Array.elem;
  8629. context_name = str_lit("array literal");
  8630. if (!is_to_be_determined_array_count) {
  8631. max_type_count = t->Array.count;
  8632. }
  8633. } else if (t->kind == Type_Array) {
  8634. elem_type = t->Array.elem;
  8635. context_name = str_lit("array literal");
  8636. if (!is_to_be_determined_array_count) {
  8637. max_type_count = t->Array.count;
  8638. }
  8639. } else if (t->kind == Type_DynamicArray) {
  8640. elem_type = t->DynamicArray.elem;
  8641. context_name = str_lit("dynamic array literal");
  8642. is_constant = false;
  8643. } else if (t->kind == Type_SimdVector) {
  8644. elem_type = t->SimdVector.elem;
  8645. context_name = str_lit("simd vector literal");
  8646. max_type_count = t->SimdVector.count;
  8647. } else if (t->kind == Type_Matrix) {
  8648. elem_type = t->Matrix.elem;
  8649. context_name = str_lit("matrix literal");
  8650. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8651. } else {
  8652. GB_PANIC("unreachable");
  8653. }
  8654. i64 max = 0;
  8655. Type *bet = base_type(elem_type);
  8656. if (!elem_type_can_be_constant(bet)) {
  8657. is_constant = false;
  8658. }
  8659. if (bet == t_invalid) {
  8660. break;
  8661. }
  8662. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8663. RangeCache rc = range_cache_make(heap_allocator());
  8664. defer (range_cache_destroy(&rc));
  8665. for (Ast *elem : cl->elems) {
  8666. if (elem->kind != Ast_FieldValue) {
  8667. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8668. continue;
  8669. }
  8670. ast_node(fv, FieldValue, elem);
  8671. if (is_ast_range(fv->field)) {
  8672. Token op = fv->field->BinaryExpr.op;
  8673. Operand x = {};
  8674. Operand y = {};
  8675. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8676. if (!ok) {
  8677. continue;
  8678. }
  8679. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8680. error(x.expr, "Expected a constant integer as an array field");
  8681. continue;
  8682. }
  8683. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8684. error(y.expr, "Expected a constant integer as an array field");
  8685. continue;
  8686. }
  8687. i64 lo = exact_value_to_i64(x.value);
  8688. i64 hi = exact_value_to_i64(y.value);
  8689. i64 max_index = hi;
  8690. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8691. hi -= 1;
  8692. } else { // .. (inclusive)
  8693. max_index += 1;
  8694. }
  8695. bool new_range = range_cache_add_range(&rc, lo, hi);
  8696. if (!new_range) {
  8697. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8698. continue;
  8699. }
  8700. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8701. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8702. continue;
  8703. }
  8704. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8705. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8706. continue;
  8707. }
  8708. if (max < hi) {
  8709. max = max_index;
  8710. }
  8711. Operand operand = {};
  8712. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8713. check_assignment(c, &operand, elem_type, context_name);
  8714. is_constant = is_constant && operand.mode == Addressing_Constant;
  8715. } else {
  8716. Operand op_index = {};
  8717. check_expr(c, &op_index, fv->field);
  8718. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8719. error(elem, "Expected a constant integer as an array field");
  8720. continue;
  8721. }
  8722. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8723. i64 index = exact_value_to_i64(op_index.value);
  8724. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8725. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8726. continue;
  8727. }
  8728. bool new_index = range_cache_add_index(&rc, index);
  8729. if (!new_index) {
  8730. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8731. continue;
  8732. }
  8733. if (max < index+1) {
  8734. max = index+1;
  8735. }
  8736. Operand operand = {};
  8737. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8738. check_assignment(c, &operand, elem_type, context_name);
  8739. is_constant = is_constant && operand.mode == Addressing_Constant;
  8740. }
  8741. }
  8742. cl->max_count = max;
  8743. } else {
  8744. isize index = 0;
  8745. for (; index < cl->elems.count; index++) {
  8746. Ast *e = cl->elems[index];
  8747. if (e == nullptr) {
  8748. error(node, "Invalid literal element");
  8749. continue;
  8750. }
  8751. if (e->kind == Ast_FieldValue) {
  8752. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8753. continue;
  8754. }
  8755. if (0 <= max_type_count && max_type_count <= index) {
  8756. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8757. }
  8758. Operand operand = {};
  8759. check_expr_with_type_hint(c, &operand, e, elem_type);
  8760. check_assignment(c, &operand, elem_type, context_name);
  8761. is_constant = is_constant && operand.mode == Addressing_Constant;
  8762. }
  8763. if (max < index) {
  8764. max = index;
  8765. }
  8766. }
  8767. if (t->kind == Type_Array) {
  8768. if (is_to_be_determined_array_count) {
  8769. t->Array.count = max;
  8770. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8771. if (0 < max && max < t->Array.count) {
  8772. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8773. }
  8774. }
  8775. } else if (t->kind == Type_Struct) {
  8776. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8777. if (is_to_be_determined_array_count) {
  8778. t->Struct.soa_count = cast(i32)max;
  8779. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8780. if (0 < max && max < t->Struct.soa_count) {
  8781. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8782. }
  8783. }
  8784. }
  8785. if (t->kind == Type_SimdVector) {
  8786. if (!is_constant) {
  8787. // error(node, "Expected all constant elements for a simd vector");
  8788. }
  8789. }
  8790. if (t->kind == Type_DynamicArray) {
  8791. if (check_for_dynamic_literals(c, node, cl)) {
  8792. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8793. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8794. }
  8795. }
  8796. if (t->kind == Type_Matrix) {
  8797. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8798. if (0 < max && max < max_type_count) {
  8799. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8800. }
  8801. }
  8802. }
  8803. break;
  8804. }
  8805. case Type_EnumeratedArray:
  8806. {
  8807. Type *elem_type = t->EnumeratedArray.elem;
  8808. Type *index_type = t->EnumeratedArray.index;
  8809. String context_name = str_lit("enumerated array literal");
  8810. i64 max_type_count = t->EnumeratedArray.count;
  8811. gbString index_type_str = type_to_string(index_type);
  8812. defer (gb_string_free(index_type_str));
  8813. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8814. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8815. String total_lo_string = {};
  8816. String total_hi_string = {};
  8817. GB_ASSERT(is_type_enum(index_type));
  8818. {
  8819. Type *bt = base_type(index_type);
  8820. GB_ASSERT(bt->kind == Type_Enum);
  8821. for (Entity *f : bt->Enum.fields) {
  8822. if (f->kind != Entity_Constant) {
  8823. continue;
  8824. }
  8825. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8826. total_lo_string = f->token.string;
  8827. }
  8828. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8829. total_hi_string = f->token.string;
  8830. }
  8831. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8832. break;
  8833. }
  8834. }
  8835. }
  8836. i64 max = 0;
  8837. Type *bet = base_type(elem_type);
  8838. if (!elem_type_can_be_constant(bet)) {
  8839. is_constant = false;
  8840. }
  8841. if (bet == t_invalid) {
  8842. break;
  8843. }
  8844. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8845. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8846. defer (map_destroy(&seen));
  8847. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8848. RangeCache rc = range_cache_make(heap_allocator());
  8849. defer (range_cache_destroy(&rc));
  8850. for (Ast *elem : cl->elems) {
  8851. if (elem->kind != Ast_FieldValue) {
  8852. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8853. continue;
  8854. }
  8855. ast_node(fv, FieldValue, elem);
  8856. if (is_ast_range(fv->field)) {
  8857. Token op = fv->field->BinaryExpr.op;
  8858. Operand x = {};
  8859. Operand y = {};
  8860. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8861. if (!ok) {
  8862. continue;
  8863. }
  8864. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8865. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8866. continue;
  8867. }
  8868. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8869. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8870. continue;
  8871. }
  8872. i64 lo = exact_value_to_i64(x.value);
  8873. i64 hi = exact_value_to_i64(y.value);
  8874. i64 max_index = hi;
  8875. if (op.kind == Token_RangeHalf) {
  8876. hi -= 1;
  8877. }
  8878. bool new_range = range_cache_add_range(&rc, lo, hi);
  8879. if (!new_range) {
  8880. gbString lo_str = expr_to_string(x.expr);
  8881. gbString hi_str = expr_to_string(y.expr);
  8882. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8883. gb_string_free(hi_str);
  8884. gb_string_free(lo_str);
  8885. continue;
  8886. }
  8887. // NOTE(bill): These are sanity checks for invalid enum values
  8888. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8889. gbString lo_str = expr_to_string(x.expr);
  8890. 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));
  8891. gb_string_free(lo_str);
  8892. continue;
  8893. }
  8894. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8895. gbString hi_str = expr_to_string(y.expr);
  8896. 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));
  8897. gb_string_free(hi_str);
  8898. continue;
  8899. }
  8900. if (max < hi) {
  8901. max = max_index;
  8902. }
  8903. Operand operand = {};
  8904. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8905. check_assignment(c, &operand, elem_type, context_name);
  8906. is_constant = is_constant && operand.mode == Addressing_Constant;
  8907. TokenKind upper_op = Token_LtEq;
  8908. if (op.kind == Token_RangeHalf) {
  8909. upper_op = Token_Lt;
  8910. }
  8911. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8912. } else {
  8913. Operand op_index = {};
  8914. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8915. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8916. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8917. continue;
  8918. }
  8919. i64 index = exact_value_to_i64(op_index.value);
  8920. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8921. gbString idx_str = expr_to_string(op_index.expr);
  8922. 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));
  8923. gb_string_free(idx_str);
  8924. continue;
  8925. }
  8926. bool new_index = range_cache_add_index(&rc, index);
  8927. if (!new_index) {
  8928. gbString idx_str = expr_to_string(op_index.expr);
  8929. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8930. gb_string_free(idx_str);
  8931. continue;
  8932. }
  8933. if (max < index+1) {
  8934. max = index+1;
  8935. }
  8936. Operand operand = {};
  8937. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8938. check_assignment(c, &operand, elem_type, context_name);
  8939. is_constant = is_constant && operand.mode == Addressing_Constant;
  8940. add_to_seen_map(c, &seen, op_index);
  8941. }
  8942. }
  8943. cl->max_count = max;
  8944. } else {
  8945. isize index = 0;
  8946. for (; index < cl->elems.count; index++) {
  8947. Ast *e = cl->elems[index];
  8948. if (e == nullptr) {
  8949. error(node, "Invalid literal element");
  8950. continue;
  8951. }
  8952. if (e->kind == Ast_FieldValue) {
  8953. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8954. continue;
  8955. }
  8956. if (0 <= max_type_count && max_type_count <= index) {
  8957. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8958. }
  8959. Operand operand = {};
  8960. check_expr_with_type_hint(c, &operand, e, elem_type);
  8961. check_assignment(c, &operand, elem_type, context_name);
  8962. is_constant = is_constant && operand.mode == Addressing_Constant;
  8963. }
  8964. if (max < index) {
  8965. max = index;
  8966. }
  8967. }
  8968. bool was_error = false;
  8969. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8970. if (0 < max && max < t->EnumeratedArray.count) {
  8971. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8972. was_error = true;
  8973. } else {
  8974. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8975. was_error = true;
  8976. }
  8977. }
  8978. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8979. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8980. TEMPORARY_ALLOCATOR_GUARD();
  8981. Type *et = base_type(index_type);
  8982. GB_ASSERT(et->kind == Type_Enum);
  8983. auto fields = et->Enum.fields;
  8984. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8985. for (Entity *f : fields) {
  8986. if (f->kind != Entity_Constant) {
  8987. continue;
  8988. }
  8989. ExactValue v = f->Constant.value;
  8990. uintptr hash = hash_exact_value(v);
  8991. auto found = map_get(&seen, hash);
  8992. if (!found) {
  8993. array_add(&unhandled, f);
  8994. }
  8995. }
  8996. if (unhandled.count > 0) {
  8997. ERROR_BLOCK();
  8998. if (unhandled.count == 1) {
  8999. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  9000. } else {
  9001. error(node, "Unhandled enumerated array cases:");
  9002. for_array(i, unhandled) {
  9003. Entity *f = unhandled[i];
  9004. error_line("\t%.*s\n", LIT(f->token.string));
  9005. }
  9006. }
  9007. if (!build_context.terse_errors) {
  9008. error_line("\n");
  9009. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  9010. }
  9011. }
  9012. }
  9013. break;
  9014. }
  9015. case Type_Basic: {
  9016. if (!is_type_any(t)) {
  9017. if (cl->elems.count != 0) {
  9018. gbString s = type_to_string(t);
  9019. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  9020. gb_string_free(s);
  9021. is_constant = false;
  9022. }
  9023. break;
  9024. }
  9025. if (cl->elems.count == 0) {
  9026. break; // NOTE(bill): No need to init
  9027. }
  9028. { // Checker values
  9029. Type *field_types[2] = {t_rawptr, t_typeid};
  9030. isize field_count = 2;
  9031. if (cl->elems[0]->kind == Ast_FieldValue) {
  9032. bool fields_visited[2] = {};
  9033. for_array(i, cl->elems) {
  9034. Ast *elem = cl->elems[i];
  9035. if (elem->kind != Ast_FieldValue) {
  9036. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9037. continue;
  9038. }
  9039. ast_node(fv, FieldValue, elem);
  9040. if (fv->field->kind != Ast_Ident) {
  9041. gbString expr_str = expr_to_string(fv->field);
  9042. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  9043. gb_string_free(expr_str);
  9044. continue;
  9045. }
  9046. String name = fv->field->Ident.token.string;
  9047. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  9048. if (sel.entity == nullptr) {
  9049. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  9050. continue;
  9051. }
  9052. isize index = sel.index[0];
  9053. if (fields_visited[index]) {
  9054. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  9055. continue;
  9056. }
  9057. fields_visited[index] = true;
  9058. check_expr(c, o, fv->value);
  9059. // NOTE(bill): 'any' literals can never be constant
  9060. is_constant = false;
  9061. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9062. }
  9063. } else {
  9064. for_array(index, cl->elems) {
  9065. Ast *elem = cl->elems[index];
  9066. if (elem->kind == Ast_FieldValue) {
  9067. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9068. continue;
  9069. }
  9070. check_expr(c, o, elem);
  9071. if (index >= field_count) {
  9072. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  9073. break;
  9074. }
  9075. // NOTE(bill): 'any' literals can never be constant
  9076. is_constant = false;
  9077. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9078. }
  9079. if (cl->elems.count < field_count) {
  9080. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  9081. }
  9082. }
  9083. }
  9084. break;
  9085. }
  9086. case Type_Map: {
  9087. if (cl->elems.count == 0) {
  9088. break;
  9089. }
  9090. is_constant = false;
  9091. { // Checker values
  9092. bool key_is_typeid = is_type_typeid(t->Map.key);
  9093. bool value_is_typeid = is_type_typeid(t->Map.value);
  9094. for (Ast *elem : cl->elems) {
  9095. if (elem->kind != Ast_FieldValue) {
  9096. error(elem, "Only 'field = value' elements are allowed in a map literal");
  9097. continue;
  9098. }
  9099. ast_node(fv, FieldValue, elem);
  9100. if (key_is_typeid) {
  9101. check_expr_or_type(c, o, fv->field, t->Map.key);
  9102. } else {
  9103. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  9104. }
  9105. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  9106. if (o->mode == Addressing_Invalid) {
  9107. continue;
  9108. }
  9109. if (value_is_typeid) {
  9110. check_expr_or_type(c, o, fv->value, t->Map.value);
  9111. } else {
  9112. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  9113. }
  9114. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  9115. }
  9116. }
  9117. if (check_for_dynamic_literals(c, node, cl)) {
  9118. add_map_reserve_dependencies(c);
  9119. add_map_set_dependencies(c);
  9120. }
  9121. break;
  9122. }
  9123. case Type_BitSet: {
  9124. if (cl->elems.count == 0) {
  9125. break; // NOTE(bill): No need to init
  9126. }
  9127. Type *et = base_type(t->BitSet.elem);
  9128. isize field_count = 0;
  9129. if (et != nullptr && et->kind == Type_Enum) {
  9130. field_count = et->Enum.fields.count;
  9131. }
  9132. if (is_type_array(bit_set_to_int(t))) {
  9133. is_constant = false;
  9134. }
  9135. for (Ast *elem : cl->elems) {
  9136. if (elem->kind == Ast_FieldValue) {
  9137. error(elem, "'field = value' in a bit_set literal is not allowed");
  9138. is_constant = false;
  9139. continue;
  9140. }
  9141. check_expr_with_type_hint(c, o, elem, et);
  9142. if (is_constant) {
  9143. is_constant = o->mode == Addressing_Constant;
  9144. }
  9145. if (elem->kind == Ast_BinaryExpr) {
  9146. switch (elem->BinaryExpr.op.kind) {
  9147. case Token_Or:
  9148. {
  9149. gbString x = expr_to_string(elem->BinaryExpr.left);
  9150. gbString y = expr_to_string(elem->BinaryExpr.right);
  9151. gbString e = expr_to_string(elem);
  9152. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9153. gb_string_free(e);
  9154. gb_string_free(y);
  9155. gb_string_free(x);
  9156. }
  9157. break;
  9158. }
  9159. }
  9160. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9161. if (o->mode == Addressing_Constant) {
  9162. i64 lower = t->BitSet.lower;
  9163. i64 upper = t->BitSet.upper;
  9164. i64 v = exact_value_to_i64(o->value);
  9165. if (lower <= v && v <= upper) {
  9166. // okay
  9167. } else {
  9168. gbString s = expr_to_string(o->expr);
  9169. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9170. gb_string_free(s);
  9171. continue;
  9172. }
  9173. }
  9174. }
  9175. break;
  9176. }
  9177. case Type_BitField: {
  9178. if (cl->elems.count == 0) {
  9179. break; // NOTE(bill): No need to init
  9180. }
  9181. is_constant = false;
  9182. if (cl->elems[0]->kind != Ast_FieldValue) {
  9183. gbString type_str = type_to_string(type);
  9184. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9185. gb_string_free(type_str);
  9186. } else {
  9187. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9188. }
  9189. break;
  9190. }
  9191. default: {
  9192. if (cl->elems.count == 0) {
  9193. break; // NOTE(bill): No need to init
  9194. }
  9195. gbString str = type_to_string(type);
  9196. error(node, "Invalid compound literal type '%s'", str);
  9197. gb_string_free(str);
  9198. return kind;
  9199. }
  9200. }
  9201. if (is_constant) {
  9202. o->mode = Addressing_Constant;
  9203. if (is_type_bit_set(type)) {
  9204. // NOTE(bill): Encode as an integer
  9205. Type *bt = base_type(type);
  9206. BigInt bits = {};
  9207. BigInt one = {};
  9208. big_int_from_u64(&one, 1);
  9209. for (Ast *e : cl->elems) {
  9210. GB_ASSERT(e->kind != Ast_FieldValue);
  9211. TypeAndValue tav = e->tav;
  9212. if (tav.mode != Addressing_Constant) {
  9213. continue;
  9214. }
  9215. if (tav.value.kind != ExactValue_Integer) {
  9216. continue;
  9217. }
  9218. i64 v = big_int_to_i64(&tav.value.value_integer);
  9219. i64 lower = bt->BitSet.lower;
  9220. u64 index = cast(u64)(v-lower);
  9221. BigInt bit = {};
  9222. big_int_from_u64(&bit, index);
  9223. big_int_shl(&bit, &one, &bit);
  9224. big_int_or(&bits, &bits, &bit);
  9225. }
  9226. o->value.kind = ExactValue_Integer;
  9227. o->value.value_integer = bits;
  9228. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9229. ExactValue value = exact_value_compound(node);
  9230. Type *bt = core_type(type);
  9231. if (bt->kind == Type_Basic) {
  9232. if (bt->Basic.flags & BasicFlag_Boolean) {
  9233. value = exact_value_bool(false);
  9234. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9235. value = exact_value_i64(0);
  9236. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9237. value = exact_value_i64(0);
  9238. } else if (bt->Basic.flags & BasicFlag_Float) {
  9239. value = exact_value_float(0);
  9240. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9241. value = exact_value_complex(0, 0);
  9242. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9243. value = exact_value_quaternion(0, 0, 0, 0);
  9244. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9245. value = exact_value_pointer(0);
  9246. } else if (bt->Basic.flags & BasicFlag_String) {
  9247. String empty_string = {};
  9248. value = exact_value_string(empty_string);
  9249. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9250. value = exact_value_i64(0);
  9251. }
  9252. }
  9253. o->value = value;
  9254. } else {
  9255. o->value = exact_value_compound(node);
  9256. }
  9257. } else {
  9258. o->mode = Addressing_Value;
  9259. }
  9260. o->type = type;
  9261. return kind;
  9262. }
  9263. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9264. ExprKind kind = Expr_Expr;
  9265. ast_node(ta, TypeAssertion, node);
  9266. check_expr(c, o, ta->expr);
  9267. node->viral_state_flags |= ta->expr->viral_state_flags;
  9268. if (o->mode == Addressing_Invalid) {
  9269. o->expr = node;
  9270. return kind;
  9271. }
  9272. if (o->mode == Addressing_Constant) {
  9273. gbString expr_str = expr_to_string(o->expr);
  9274. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9275. gb_string_free(expr_str);
  9276. o->mode = Addressing_Invalid;
  9277. o->expr = node;
  9278. return kind;
  9279. }
  9280. if (is_type_untyped(o->type)) {
  9281. gbString expr_str = expr_to_string(o->expr);
  9282. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9283. gb_string_free(expr_str);
  9284. o->mode = Addressing_Invalid;
  9285. o->expr = node;
  9286. return kind;
  9287. }
  9288. Type *src = type_deref(o->type);
  9289. Type *bsrc = base_type(src);
  9290. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9291. if (!is_type_union(src)) {
  9292. gbString str = type_to_string(o->type);
  9293. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9294. gb_string_free(str);
  9295. o->mode = Addressing_Invalid;
  9296. o->expr = node;
  9297. return kind;
  9298. }
  9299. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9300. bool allowed = false;
  9301. for (Type *vt : bsrc->Union.variants) {
  9302. if (are_types_identical(vt, type_hint)) {
  9303. allowed = true;
  9304. add_type_info_type(c, vt);
  9305. break;
  9306. }
  9307. }
  9308. if (allowed) {
  9309. add_type_info_type(c, o->type);
  9310. o->type = type_hint;
  9311. o->mode = Addressing_OptionalOk;
  9312. goto end;
  9313. }
  9314. }
  9315. if (bsrc->Union.variants.count != 1) {
  9316. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9317. o->mode = Addressing_Invalid;
  9318. o->expr = node;
  9319. return kind;
  9320. }
  9321. add_type_info_type(c, o->type);
  9322. add_type_info_type(c, bsrc->Union.variants[0]);
  9323. o->type = bsrc->Union.variants[0];
  9324. o->mode = Addressing_OptionalOk;
  9325. } else {
  9326. Type *t = check_type(c, ta->type);
  9327. Type *dst = t;
  9328. if (is_type_union(src)) {
  9329. bool ok = false;
  9330. for (Type *vt : bsrc->Union.variants) {
  9331. if (are_types_identical(vt, dst)) {
  9332. ok = true;
  9333. break;
  9334. }
  9335. }
  9336. if (!ok) {
  9337. gbString expr_str = expr_to_string(o->expr);
  9338. gbString dst_type_str = type_to_string(t);
  9339. defer (gb_string_free(expr_str));
  9340. defer (gb_string_free(dst_type_str));
  9341. if (bsrc->Union.variants.count == 0) {
  9342. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9343. } else {
  9344. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9345. }
  9346. o->mode = Addressing_Invalid;
  9347. o->expr = node;
  9348. return kind;
  9349. }
  9350. add_type_info_type(c, o->type);
  9351. add_type_info_type(c, t);
  9352. o->type = t;
  9353. o->mode = Addressing_OptionalOk;
  9354. } else if (is_type_any(src)) {
  9355. o->type = t;
  9356. o->mode = Addressing_OptionalOk;
  9357. add_type_info_type(c, o->type);
  9358. add_type_info_type(c, t);
  9359. } else {
  9360. gbString str = type_to_string(o->type);
  9361. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9362. gb_string_free(str);
  9363. o->mode = Addressing_Invalid;
  9364. o->expr = node;
  9365. return kind;
  9366. }
  9367. }
  9368. end:;
  9369. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9370. add_package_dependency(c, "runtime", "type_assertion_check");
  9371. add_package_dependency(c, "runtime", "type_assertion_check2");
  9372. }
  9373. return kind;
  9374. }
  9375. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9376. ast_node(se, SelectorCallExpr, node);
  9377. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9378. // COM APIs is a great example of where this kind of thing is extremely useful
  9379. // General idea:
  9380. //
  9381. // x->y(123) == x.y(x, 123)
  9382. //
  9383. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9384. // Just regenerating a new AST aids things
  9385. //
  9386. // TODO(bill): Is this a good hack or not?
  9387. //
  9388. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9389. if (se->modified_call) {
  9390. // Prevent double evaluation
  9391. o->expr = node;
  9392. o->type = node->tav.type;
  9393. o->value = node->tav.value;
  9394. o->mode = node->tav.mode;
  9395. return Expr_Expr;
  9396. }
  9397. bool allow_arrow_right_selector_expr;
  9398. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9399. c->allow_arrow_right_selector_expr = true;
  9400. Operand x = {};
  9401. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9402. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9403. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9404. o->mode = Addressing_Invalid;
  9405. o->type = t_invalid;
  9406. o->expr = node;
  9407. return kind;
  9408. }
  9409. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9410. gbString type_str = type_to_string(x.type);
  9411. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9412. gb_string_free(type_str);
  9413. o->mode = Addressing_Invalid;
  9414. o->type = t_invalid;
  9415. o->expr = node;
  9416. return Expr_Stmt;
  9417. }
  9418. ast_node(ce, CallExpr, se->call);
  9419. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9420. Ast *first_arg = x.expr->SelectorExpr.expr;
  9421. GB_ASSERT(first_arg != nullptr);
  9422. Entity *e = entity_of_node(se->expr);
  9423. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9424. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9425. }
  9426. if (e->kind != Entity_ProcGroup) {
  9427. Type *pt = base_type(x.type);
  9428. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9429. Type *first_type = nullptr;
  9430. String first_arg_name = {};
  9431. if (pt->Proc.param_count > 0) {
  9432. Entity *f = pt->Proc.params->Tuple.variables[0];
  9433. first_type = f->type;
  9434. first_arg_name = f->token.string;
  9435. }
  9436. if (first_arg_name.len == 0) {
  9437. first_arg_name = str_lit("_");
  9438. }
  9439. if (first_type == nullptr) {
  9440. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9441. o->mode = Addressing_Invalid;
  9442. o->type = t_invalid;
  9443. o->expr = node;
  9444. return Expr_Stmt;
  9445. }
  9446. Operand y = {};
  9447. y.mode = first_arg->tav.mode;
  9448. y.type = first_arg->tav.type;
  9449. y.value = first_arg->tav.value;
  9450. if (check_is_assignable_to(c, &y, first_type)) {
  9451. // Do nothing, it's valid
  9452. } else {
  9453. Operand z = y;
  9454. z.type = type_deref(y.type);
  9455. if (check_is_assignable_to(c, &z, first_type)) {
  9456. // NOTE(bill): AST GENERATION HACK!
  9457. Token op = {Token_Pointer};
  9458. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9459. } else if (y.mode == Addressing_Variable) {
  9460. Operand w = y;
  9461. w.type = alloc_type_pointer(y.type);
  9462. if (check_is_assignable_to(c, &w, first_type)) {
  9463. // NOTE(bill): AST GENERATION HACK!
  9464. Token op = {Token_And};
  9465. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9466. }
  9467. }
  9468. }
  9469. if (ce->args.count > 0) {
  9470. bool fail = false;
  9471. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9472. for (Ast *arg : ce->args) {
  9473. bool mix = false;
  9474. if (first_is_field_value) {
  9475. mix = arg->kind != Ast_FieldValue;
  9476. } else {
  9477. mix = arg->kind == Ast_FieldValue;
  9478. }
  9479. if (mix) {
  9480. fail = true;
  9481. break;
  9482. }
  9483. }
  9484. if (!fail && first_is_field_value) {
  9485. Token op = {Token_Eq};
  9486. AstFile *f = first_arg->file();
  9487. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9488. }
  9489. }
  9490. }
  9491. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9492. modified_args[0] = first_arg;
  9493. slice_copy(&modified_args, ce->args, 1);
  9494. ce->args = modified_args;
  9495. se->modified_call = true;
  9496. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9497. c->allow_arrow_right_selector_expr = true;
  9498. check_expr_base(c, o, se->call, type_hint);
  9499. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9500. o->expr = node;
  9501. return Expr_Expr;
  9502. }
  9503. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9504. ExprKind kind = Expr_Expr;
  9505. ast_node(ie, IndexExpr, node);
  9506. check_expr(c, o, ie->expr);
  9507. node->viral_state_flags |= ie->expr->viral_state_flags;
  9508. if (o->mode == Addressing_Invalid) {
  9509. o->expr = node;
  9510. return kind;
  9511. }
  9512. Type *t = base_type(type_deref(o->type));
  9513. bool is_ptr = is_type_pointer(o->type);
  9514. bool is_const = o->mode == Addressing_Constant;
  9515. if (is_type_map(t)) {
  9516. Operand key = {};
  9517. if (is_type_typeid(t->Map.key)) {
  9518. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9519. } else {
  9520. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9521. }
  9522. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9523. if (key.mode == Addressing_Invalid) {
  9524. o->mode = Addressing_Invalid;
  9525. o->expr = node;
  9526. return kind;
  9527. }
  9528. o->mode = Addressing_MapIndex;
  9529. o->type = t->Map.value;
  9530. o->expr = node;
  9531. add_map_get_dependencies(c);
  9532. add_map_set_dependencies(c);
  9533. return Expr_Expr;
  9534. }
  9535. i64 max_count = -1;
  9536. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9537. if (is_const) {
  9538. if (is_type_array(t)) {
  9539. // Okay
  9540. } else if (is_type_slice(t)) {
  9541. // Okay
  9542. } else if (is_type_enumerated_array(t)) {
  9543. // Okay
  9544. } else if (is_type_string(t)) {
  9545. // Okay
  9546. } else if (is_type_matrix(t)) {
  9547. // Okay
  9548. } else {
  9549. valid = false;
  9550. }
  9551. }
  9552. if (!valid) {
  9553. gbString str = expr_to_string(o->expr);
  9554. gbString type_str = type_to_string(o->type);
  9555. defer (gb_string_free(str));
  9556. defer (gb_string_free(type_str));
  9557. if (is_const) {
  9558. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9559. } else {
  9560. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9561. }
  9562. o->mode = Addressing_Invalid;
  9563. o->expr = node;
  9564. return kind;
  9565. }
  9566. if (ie->index == nullptr) {
  9567. gbString str = expr_to_string(o->expr);
  9568. error(o->expr, "Missing index for '%s'", str);
  9569. gb_string_free(str);
  9570. o->mode = Addressing_Invalid;
  9571. o->expr = node;
  9572. return kind;
  9573. }
  9574. Type *index_type_hint = nullptr;
  9575. if (is_type_enumerated_array(t)) {
  9576. Type *bt = base_type(t);
  9577. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9578. index_type_hint = bt->EnumeratedArray.index;
  9579. }
  9580. i64 index = 0;
  9581. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9582. if (is_const) {
  9583. if (index < 0) {
  9584. ERROR_BLOCK();
  9585. gbString str = expr_to_string(o->expr);
  9586. error(o->expr, "Cannot index a constant '%s'", str);
  9587. if (!build_context.terse_errors) {
  9588. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9589. }
  9590. gb_string_free(str);
  9591. o->mode = Addressing_Invalid;
  9592. o->expr = node;
  9593. return kind;
  9594. } else if (ok && !is_type_matrix(t)) {
  9595. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9596. ExactValue value = tav.value;
  9597. o->mode = Addressing_Constant;
  9598. bool success = false;
  9599. bool finish = false;
  9600. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9601. if (!success) {
  9602. ERROR_BLOCK();
  9603. gbString str = expr_to_string(o->expr);
  9604. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9605. if (!build_context.terse_errors) {
  9606. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9607. }
  9608. gb_string_free(str);
  9609. o->mode = Addressing_Invalid;
  9610. o->expr = node;
  9611. return kind;
  9612. }
  9613. }
  9614. }
  9615. if (type_hint != nullptr && is_type_matrix(t)) {
  9616. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9617. // if a type hint exists
  9618. }
  9619. return kind;
  9620. }
  9621. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9622. ExprKind kind = Expr_Stmt;
  9623. ast_node(se, SliceExpr, node);
  9624. check_expr(c, o, se->expr);
  9625. node->viral_state_flags |= se->expr->viral_state_flags;
  9626. if (o->mode == Addressing_Invalid) {
  9627. o->mode = Addressing_Invalid;
  9628. o->expr = node;
  9629. return kind;
  9630. }
  9631. bool valid = false;
  9632. i64 max_count = -1;
  9633. Type *t = base_type(type_deref(o->type));
  9634. switch (t->kind) {
  9635. case Type_Basic:
  9636. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9637. valid = true;
  9638. if (o->mode == Addressing_Constant) {
  9639. GB_ASSERT(o->value.kind == ExactValue_String);
  9640. max_count = o->value.value_string.len;
  9641. }
  9642. o->type = type_deref(o->type);
  9643. } else if (t->Basic.kind == Basic_string16) {
  9644. valid = true;
  9645. if (o->mode == Addressing_Constant) {
  9646. GB_ASSERT(o->value.kind == ExactValue_String16);
  9647. max_count = o->value.value_string16.len;
  9648. }
  9649. o->type = type_deref(o->type);
  9650. }
  9651. break;
  9652. case Type_Array:
  9653. valid = true;
  9654. max_count = t->Array.count;
  9655. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9656. gbString str = expr_to_string(node);
  9657. error(node, "Cannot slice array '%s', value is not addressable", str);
  9658. gb_string_free(str);
  9659. o->mode = Addressing_Invalid;
  9660. o->expr = node;
  9661. return kind;
  9662. }
  9663. o->type = alloc_type_slice(t->Array.elem);
  9664. break;
  9665. case Type_MultiPointer:
  9666. valid = true;
  9667. o->type = type_deref(o->type);
  9668. break;
  9669. case Type_Slice:
  9670. valid = true;
  9671. o->type = type_deref(o->type);
  9672. break;
  9673. case Type_DynamicArray:
  9674. valid = true;
  9675. o->type = alloc_type_slice(t->DynamicArray.elem);
  9676. break;
  9677. case Type_Struct:
  9678. if (is_type_soa_struct(t)) {
  9679. valid = true;
  9680. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9681. max_count = t->Struct.soa_count;
  9682. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9683. gbString str = expr_to_string(node);
  9684. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9685. gb_string_free(str);
  9686. o->mode = Addressing_Invalid;
  9687. o->expr = node;
  9688. return kind;
  9689. }
  9690. }
  9691. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9692. }
  9693. break;
  9694. case Type_EnumeratedArray:
  9695. {
  9696. gbString str = expr_to_string(o->expr);
  9697. gbString type_str = type_to_string(o->type);
  9698. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9699. gb_string_free(type_str);
  9700. gb_string_free(str);
  9701. o->mode = Addressing_Invalid;
  9702. o->expr = node;
  9703. return kind;
  9704. }
  9705. break;
  9706. }
  9707. if (!valid) {
  9708. gbString str = expr_to_string(o->expr);
  9709. gbString type_str = type_to_string(o->type);
  9710. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9711. gb_string_free(type_str);
  9712. gb_string_free(str);
  9713. o->mode = Addressing_Invalid;
  9714. o->expr = node;
  9715. return kind;
  9716. }
  9717. if (se->low == nullptr && se->high != nullptr) {
  9718. // It is okay to continue as it will assume the 1st index is zero
  9719. }
  9720. i64 indices[2] = {};
  9721. Ast *nodes[2] = {se->low, se->high};
  9722. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9723. i64 index = max_count;
  9724. if (nodes[i] != nullptr) {
  9725. i64 capacity = -1;
  9726. if (max_count >= 0) {
  9727. capacity = max_count;
  9728. }
  9729. i64 j = 0;
  9730. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9731. index = j;
  9732. }
  9733. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9734. } else if (i == 0) {
  9735. index = 0;
  9736. }
  9737. indices[i] = index;
  9738. }
  9739. for (isize i = 0; i < gb_count_of(indices); i++) {
  9740. i64 a = indices[i];
  9741. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9742. i64 b = indices[j];
  9743. if (a > b && b >= 0) {
  9744. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9745. }
  9746. }
  9747. }
  9748. if (max_count < 0) {
  9749. if (o->mode == Addressing_Constant) {
  9750. gbString s = expr_to_string(se->expr);
  9751. error(se->expr, "Cannot slice constant value '%s'", s);
  9752. gb_string_free(s);
  9753. }
  9754. }
  9755. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9756. /*
  9757. x[:] -> [^]T
  9758. x[i:] -> [^]T
  9759. x[:n] -> []T
  9760. x[i:n] -> []T
  9761. */
  9762. o->type = alloc_type_slice(t->MultiPointer.elem);
  9763. }
  9764. o->mode = Addressing_Value;
  9765. if (is_type_string(t) && max_count >= 0) {
  9766. bool all_constant = true;
  9767. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9768. if (nodes[i] != nullptr) {
  9769. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9770. if (tav.mode != Addressing_Constant) {
  9771. all_constant = false;
  9772. break;
  9773. }
  9774. }
  9775. }
  9776. if (!all_constant) {
  9777. ERROR_BLOCK();
  9778. gbString str = expr_to_string(o->expr);
  9779. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9780. if (!build_context.terse_errors) {
  9781. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9782. }
  9783. gb_string_free(str);
  9784. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9785. o->expr = node;
  9786. return kind;
  9787. }
  9788. o->mode = Addressing_Constant;
  9789. o->type = t;
  9790. if (o->value.kind == ExactValue_String16) {
  9791. String16 s = o->value.value_string16;
  9792. o->value = exact_value_string16(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9793. } else {
  9794. String s = {};
  9795. if (o->value.kind == ExactValue_String) {
  9796. s = o->value.value_string;
  9797. }
  9798. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9799. }
  9800. }
  9801. return kind;
  9802. }
  9803. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9804. u32 prev_state_flags = c->state_flags;
  9805. defer (c->state_flags = prev_state_flags);
  9806. if (node->state_flags != 0) {
  9807. u32 in = node->state_flags;
  9808. u32 out = c->state_flags;
  9809. if (in & StateFlag_no_bounds_check) {
  9810. out |= StateFlag_no_bounds_check;
  9811. out &= ~StateFlag_bounds_check;
  9812. } else if (in & StateFlag_bounds_check) {
  9813. out |= StateFlag_bounds_check;
  9814. out &= ~StateFlag_no_bounds_check;
  9815. }
  9816. if (in & StateFlag_no_type_assert) {
  9817. out |= StateFlag_no_type_assert;
  9818. out &= ~StateFlag_type_assert;
  9819. } else if (in & StateFlag_type_assert) {
  9820. out |= StateFlag_type_assert;
  9821. out &= ~StateFlag_no_type_assert;
  9822. }
  9823. c->state_flags = out;
  9824. }
  9825. ExprKind kind = Expr_Stmt;
  9826. o->mode = Addressing_Invalid;
  9827. o->type = t_invalid;
  9828. o->value = {ExactValue_Invalid};
  9829. switch (node->kind) {
  9830. default:
  9831. return kind;
  9832. case_ast_node(be, BadExpr, node)
  9833. return kind;
  9834. case_end;
  9835. case_ast_node(i, Implicit, node);
  9836. switch (i->kind) {
  9837. case Token_context:
  9838. {
  9839. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9840. error(node, "'context' is only allowed within procedures");
  9841. return kind;
  9842. }
  9843. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9844. c->scope->flags |= ScopeFlag_ContextDefined;
  9845. }
  9846. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9847. error(node, "'context' has not been defined within this scope");
  9848. // Continue with value
  9849. }
  9850. init_core_context(c->checker);
  9851. o->mode = Addressing_Context;
  9852. o->type = t_context;
  9853. }
  9854. break;
  9855. default:
  9856. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9857. return kind;
  9858. }
  9859. case_end;
  9860. case_ast_node(i, Ident, node);
  9861. check_ident(c, o, node, nullptr, type_hint, false);
  9862. case_end;
  9863. case_ast_node(u, Uninit, node);
  9864. o->mode = Addressing_Value;
  9865. o->type = t_untyped_uninit;
  9866. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  9867. case_end;
  9868. case_ast_node(bl, BasicLit, node);
  9869. Type *t = t_invalid;
  9870. switch (node->tav.value.kind) {
  9871. case ExactValue_String: t = t_untyped_string; break;
  9872. case ExactValue_String16: t = t_string16; break; // TODO(bill): determine this correctly
  9873. case ExactValue_Float: t = t_untyped_float; break;
  9874. case ExactValue_Complex: t = t_untyped_complex; break;
  9875. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9876. case ExactValue_Integer:
  9877. t = t_untyped_integer;
  9878. if (bl->token.kind == Token_Rune) {
  9879. t = t_untyped_rune;
  9880. }
  9881. break;
  9882. default:
  9883. GB_PANIC("Unhandled value type for basic literal");
  9884. break;
  9885. }
  9886. o->mode = Addressing_Constant;
  9887. o->type = t;
  9888. o->value = node->tav.value;
  9889. case_end;
  9890. case_ast_node(bd, BasicDirective, node);
  9891. kind = check_basic_directive_expr(c, o, node, type_hint);
  9892. case_end;
  9893. case_ast_node(pg, ProcGroup, node);
  9894. error(node, "Illegal use of a procedure group");
  9895. o->mode = Addressing_Invalid;
  9896. case_end;
  9897. case_ast_node(pl, ProcLit, node);
  9898. CheckerContext ctx = *c;
  9899. DeclInfo *decl = nullptr;
  9900. Type *type = alloc_type(Type_Proc);
  9901. check_open_scope(&ctx, pl->type);
  9902. {
  9903. decl = make_decl_info(ctx.scope, ctx.decl);
  9904. decl->proc_lit = node;
  9905. ctx.decl = decl;
  9906. defer (ctx.decl = ctx.decl->parent);
  9907. if (pl->tags != 0) {
  9908. error(node, "A procedure literal cannot have tags");
  9909. pl->tags = 0; // TODO(bill): Should I zero this?!
  9910. }
  9911. check_procedure_type(&ctx, type, pl->type);
  9912. if (!is_type_proc(type)) {
  9913. gbString str = expr_to_string(node);
  9914. error(node, "Invalid procedure literal '%s'", str);
  9915. gb_string_free(str);
  9916. check_close_scope(&ctx);
  9917. return kind;
  9918. }
  9919. if (pl->body == nullptr) {
  9920. error(node, "A procedure literal must have a body");
  9921. return kind;
  9922. }
  9923. pl->decl = decl;
  9924. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9925. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9926. array_add(&ctx.checker->nested_proc_lits, decl);
  9927. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9928. }
  9929. check_close_scope(&ctx);
  9930. o->mode = Addressing_Value;
  9931. o->type = type;
  9932. case_end;
  9933. case_ast_node(te, TernaryIfExpr, node);
  9934. kind = check_ternary_if_expr(c, o, node, type_hint);
  9935. case_end;
  9936. case_ast_node(te, TernaryWhenExpr, node);
  9937. kind = check_ternary_when_expr(c, o, node, type_hint);
  9938. case_end;
  9939. case_ast_node(oe, OrElseExpr, node);
  9940. return check_or_else_expr(c, o, node, type_hint);
  9941. case_end;
  9942. case_ast_node(re, OrReturnExpr, node);
  9943. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9944. return check_or_return_expr(c, o, node, type_hint);
  9945. case_end;
  9946. case_ast_node(re, OrBranchExpr, node);
  9947. return check_or_branch_expr(c, o, node, type_hint);
  9948. case_end;
  9949. case_ast_node(cl, CompoundLit, node);
  9950. kind = check_compound_literal(c, o, node, type_hint);
  9951. case_end;
  9952. case_ast_node(pe, ParenExpr, node);
  9953. kind = check_expr_base(c, o, pe->expr, type_hint);
  9954. node->viral_state_flags |= pe->expr->viral_state_flags;
  9955. o->expr = node;
  9956. case_end;
  9957. case_ast_node(te, TagExpr, node);
  9958. String name = te->name.string;
  9959. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9960. if (te->expr) {
  9961. kind = check_expr_base(c, o, te->expr, type_hint);
  9962. node->viral_state_flags |= te->expr->viral_state_flags;
  9963. }
  9964. o->expr = node;
  9965. case_end;
  9966. case_ast_node(ta, TypeAssertion, node);
  9967. kind = check_type_assertion(c, o, node, type_hint);
  9968. case_end;
  9969. case_ast_node(tc, TypeCast, node);
  9970. check_expr_or_type(c, o, tc->type);
  9971. if (o->mode != Addressing_Type) {
  9972. gbString str = expr_to_string(tc->type);
  9973. error(tc->type, "Expected a type, got %s", str);
  9974. gb_string_free(str);
  9975. o->mode = Addressing_Invalid;
  9976. }
  9977. if (o->mode == Addressing_Invalid) {
  9978. o->expr = node;
  9979. return kind;
  9980. }
  9981. Type *type = o->type;
  9982. check_expr_base(c, o, tc->expr, type);
  9983. node->viral_state_flags |= tc->expr->viral_state_flags;
  9984. if (o->mode != Addressing_Invalid) {
  9985. switch (tc->token.kind) {
  9986. case Token_transmute:
  9987. check_transmute(c, node, o, type, true);
  9988. break;
  9989. case Token_cast:
  9990. check_cast(c, o, type, true);
  9991. break;
  9992. default:
  9993. error(node, "Invalid AST: Invalid casting expression");
  9994. o->mode = Addressing_Invalid;
  9995. break;
  9996. }
  9997. }
  9998. return Expr_Expr;
  9999. case_end;
  10000. case_ast_node(ac, AutoCast, node);
  10001. check_expr_base(c, o, ac->expr, type_hint);
  10002. node->viral_state_flags |= ac->expr->viral_state_flags;
  10003. if (o->mode == Addressing_Invalid) {
  10004. o->expr = node;
  10005. return kind;
  10006. }
  10007. if (type_hint) {
  10008. check_cast(c, o, type_hint);
  10009. }
  10010. o->expr = node;
  10011. return Expr_Expr;
  10012. case_end;
  10013. case_ast_node(ue, UnaryExpr, node);
  10014. Type *th = type_hint;
  10015. if (ue->op.kind == Token_And) {
  10016. th = type_deref(th);
  10017. }
  10018. check_expr_base(c, o, ue->expr, th);
  10019. node->viral_state_flags |= ue->expr->viral_state_flags;
  10020. if (o->mode != Addressing_Invalid) {
  10021. check_unary_expr(c, o, ue->op, node);
  10022. }
  10023. o->expr = node;
  10024. return Expr_Expr;
  10025. case_end;
  10026. case_ast_node(be, BinaryExpr, node);
  10027. check_binary_expr(c, o, node, type_hint, true);
  10028. if (o->mode == Addressing_Invalid) {
  10029. o->expr = node;
  10030. return kind;
  10031. }
  10032. case_end;
  10033. case_ast_node(se, SelectorExpr, node);
  10034. check_selector(c, o, node, type_hint);
  10035. node->viral_state_flags |= se->expr->viral_state_flags;
  10036. case_end;
  10037. case_ast_node(se, SelectorCallExpr, node);
  10038. return check_selector_call_expr(c, o, node, type_hint);
  10039. case_end;
  10040. case_ast_node(ise, ImplicitSelectorExpr, node);
  10041. return check_implicit_selector_expr(c, o, node, type_hint);
  10042. case_end;
  10043. case_ast_node(ie, IndexExpr, node);
  10044. kind = check_index_expr(c, o, node, type_hint);
  10045. case_end;
  10046. case_ast_node(se, SliceExpr, node);
  10047. kind = check_slice_expr(c, o, node, type_hint);
  10048. case_end;
  10049. case_ast_node(mie, MatrixIndexExpr, node);
  10050. check_matrix_index_expr(c, o, node, type_hint);
  10051. o->expr = node;
  10052. return Expr_Expr;
  10053. case_end;
  10054. case_ast_node(ce, CallExpr, node);
  10055. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  10056. case_end;
  10057. case_ast_node(de, DerefExpr, node);
  10058. check_expr_or_type(c, o, de->expr);
  10059. node->viral_state_flags |= de->expr->viral_state_flags;
  10060. if (o->mode == Addressing_Invalid) {
  10061. o->mode = Addressing_Invalid;
  10062. o->expr = node;
  10063. return kind;
  10064. } else if (o->mode == Addressing_Type) {
  10065. gbString str = expr_to_string(o->expr);
  10066. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  10067. o->mode = Addressing_Invalid;
  10068. o->expr = node;
  10069. return kind;
  10070. } else {
  10071. Type *t = base_type(o->type);
  10072. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  10073. o->mode = Addressing_Variable;
  10074. o->type = t->Pointer.elem;
  10075. } else if (t->kind == Type_SoaPointer) {
  10076. o->mode = Addressing_SoaVariable;
  10077. o->type = type_deref(t);
  10078. } else {
  10079. gbString str = expr_to_string(o->expr);
  10080. gbString typ = type_to_string(o->type);
  10081. ERROR_BLOCK();
  10082. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  10083. if (o->type && is_type_multi_pointer(o->type)) {
  10084. if (!build_context.terse_errors) {
  10085. error_line("\tDid you mean '%s[0]'?\n", str);
  10086. }
  10087. }
  10088. gb_string_free(typ);
  10089. gb_string_free(str);
  10090. o->mode = Addressing_Invalid;
  10091. o->expr = node;
  10092. return kind;
  10093. }
  10094. }
  10095. case_end;
  10096. case_ast_node(ia, InlineAsmExpr, node);
  10097. if (c->curr_proc_decl == nullptr) {
  10098. error(node, "Inline asm expressions are only allowed within a procedure body");
  10099. }
  10100. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  10101. Type *return_type = nullptr;
  10102. for_array(i, ia->param_types) {
  10103. param_types[i] = check_type(c, ia->param_types[i]);
  10104. }
  10105. if (ia->return_type != nullptr) {
  10106. return_type = check_type(c, ia->return_type);
  10107. }
  10108. Operand x = {};
  10109. check_expr(c, &x, ia->asm_string);
  10110. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10111. error(x.expr, "Expected a constant string for the inline asm main parameter");
  10112. }
  10113. check_expr(c, &x, ia->constraints_string);
  10114. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10115. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  10116. }
  10117. Scope *scope = create_scope(c->info, c->scope);
  10118. scope->flags |= ScopeFlag_Proc;
  10119. Type *params = alloc_type_tuple();
  10120. Type *results = alloc_type_tuple();
  10121. if (param_types.count != 0) {
  10122. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  10123. for_array(i, param_types) {
  10124. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  10125. }
  10126. }
  10127. if (return_type != nullptr) {
  10128. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  10129. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  10130. }
  10131. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  10132. o->type = pt;
  10133. o->mode = Addressing_Value;
  10134. o->expr = node;
  10135. return Expr_Expr;
  10136. case_end;
  10137. case Ast_DistinctType:
  10138. case Ast_TypeidType:
  10139. case Ast_PolyType:
  10140. case Ast_ProcType:
  10141. case Ast_PointerType:
  10142. case Ast_MultiPointerType:
  10143. case Ast_ArrayType:
  10144. case Ast_DynamicArrayType:
  10145. case Ast_StructType:
  10146. case Ast_UnionType:
  10147. case Ast_EnumType:
  10148. case Ast_MapType:
  10149. case Ast_BitSetType:
  10150. case Ast_MatrixType:
  10151. case Ast_RelativeType:
  10152. o->mode = Addressing_Type;
  10153. o->type = check_type(c, node);
  10154. break;
  10155. }
  10156. kind = Expr_Expr;
  10157. o->expr = node;
  10158. return kind;
  10159. }
  10160. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10161. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10162. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10163. o->type = t_invalid;
  10164. gbString xs = expr_to_string(o->expr);
  10165. if (o->mode == Addressing_Type) {
  10166. error(o->expr, "Invalid type usage '%s'", xs);
  10167. } else {
  10168. error(o->expr, "Invalid expression '%s'", xs);
  10169. }
  10170. gb_string_free(xs);
  10171. }
  10172. if (o->type != nullptr && is_type_untyped(o->type)) {
  10173. add_untyped(c, node, o->mode, o->type, o->value);
  10174. }
  10175. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10176. add_type_and_value(c, node, o->mode, o->type, o->value);
  10177. return kind;
  10178. }
  10179. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10180. check_expr_base(c, o, e, nullptr);
  10181. switch (o->mode) {
  10182. default:
  10183. return; // NOTE(bill): Valid
  10184. case Addressing_NoValue:
  10185. error_operand_no_value(o);
  10186. break;
  10187. }
  10188. o->mode = Addressing_Invalid;
  10189. }
  10190. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10191. check_expr_base(c, o, e, nullptr);
  10192. switch (o->mode) {
  10193. default:
  10194. return; // NOTE(bill): Valid
  10195. case Addressing_NoValue:
  10196. error_operand_no_value(o);
  10197. break;
  10198. case Addressing_Type:
  10199. error_operand_not_expression(o);
  10200. break;
  10201. }
  10202. o->mode = Addressing_Invalid;
  10203. }
  10204. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10205. check_expr_base(c, o, e, type_hint);
  10206. switch (o->mode) {
  10207. default:
  10208. return; // NOTE(bill): Valid
  10209. case Addressing_NoValue:
  10210. error_operand_no_value(o);
  10211. break;
  10212. case Addressing_Type:
  10213. error_operand_not_expression(o);
  10214. break;
  10215. }
  10216. o->mode = Addressing_Invalid;
  10217. }
  10218. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10219. if (o->mode == Addressing_Value) {
  10220. // NOTE(bill): Tuples are not first class thus never named
  10221. if (o->type->kind == Type_Tuple) {
  10222. isize count = o->type->Tuple.variables.count;
  10223. error(o->expr,
  10224. "%td-valued expression found where single value expected", count);
  10225. o->mode = Addressing_Invalid;
  10226. GB_ASSERT(count != 1);
  10227. }
  10228. }
  10229. }
  10230. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10231. check_multi_expr(c, o, e);
  10232. check_not_tuple(c, o);
  10233. }
  10234. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10235. check_expr_base(c, o, e, type_hint);
  10236. check_not_tuple(c, o);
  10237. error_operand_no_value(o);
  10238. }
  10239. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10240. switch (v.kind) {
  10241. case ExactValue_Invalid:
  10242. return true;
  10243. case ExactValue_Bool:
  10244. return !v.value_bool;
  10245. case ExactValue_String:
  10246. return v.value_string.len == 0;
  10247. case ExactValue_String16:
  10248. return v.value_string16.len == 0;
  10249. case ExactValue_Integer:
  10250. return big_int_is_zero(&v.value_integer);
  10251. case ExactValue_Float:
  10252. return v.value_float == 0.0;
  10253. case ExactValue_Complex:
  10254. if (v.value_complex) {
  10255. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10256. }
  10257. return true;
  10258. case ExactValue_Quaternion:
  10259. if (v.value_quaternion) {
  10260. return v.value_quaternion->real == 0.0 &&
  10261. v.value_quaternion->imag == 0.0 &&
  10262. v.value_quaternion->jmag == 0.0 &&
  10263. v.value_quaternion->kmag == 0.0;
  10264. }
  10265. return true;
  10266. case ExactValue_Pointer:
  10267. return v.value_pointer == 0;
  10268. case ExactValue_Compound:
  10269. if (v.value_compound == nullptr) {
  10270. return true;
  10271. } else {
  10272. ast_node(cl, CompoundLit, v.value_compound);
  10273. if (cl->elems.count == 0) {
  10274. return true;
  10275. } else {
  10276. for (Ast *elem : cl->elems) {
  10277. if (elem->tav.mode != Addressing_Constant) {
  10278. return false;
  10279. }
  10280. if (!is_exact_value_zero(elem->tav.value)) {
  10281. return false;
  10282. }
  10283. }
  10284. return true;
  10285. }
  10286. }
  10287. case ExactValue_Procedure:
  10288. return v.value_procedure == nullptr;
  10289. case ExactValue_Typeid:
  10290. return v.value_typeid == nullptr;
  10291. }
  10292. return true;
  10293. }
  10294. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10295. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10296. for_array(i, params) {
  10297. if (i > 0) {
  10298. str = gb_string_appendc(str, ", ");
  10299. }
  10300. str = write_expr_to_string(str, params[i], false);
  10301. }
  10302. return str;
  10303. }
  10304. gb_internal gbString string_append_string(gbString str, String string) {
  10305. if (string.len > 0) {
  10306. return gb_string_append_length(str, &string[0], string.len);
  10307. }
  10308. return str;
  10309. }
  10310. gb_internal gbString string_append_token(gbString str, Token token) {
  10311. str = string_append_string(str, token.string);
  10312. return str;
  10313. }
  10314. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10315. if (node == nullptr)
  10316. return str;
  10317. if (is_ast_stmt(node)) {
  10318. GB_ASSERT("stmt passed to write_expr_to_string");
  10319. }
  10320. switch (node->kind) {
  10321. default:
  10322. str = gb_string_appendc(str, "(BadExpr)");
  10323. break;
  10324. case_ast_node(i, Ident, node);
  10325. str = string_append_token(str, i->token);
  10326. case_end;
  10327. case_ast_node(i, Implicit, node);
  10328. str = string_append_token(str, *i);
  10329. case_end;
  10330. case_ast_node(bl, BasicLit, node);
  10331. str = string_append_token(str, bl->token);
  10332. case_end;
  10333. case_ast_node(bd, BasicDirective, node);
  10334. str = gb_string_append_rune(str, '#');
  10335. str = string_append_string(str, bd->name.string);
  10336. case_end;
  10337. case_ast_node(ud, Uninit, node);
  10338. str = gb_string_appendc(str, "---");
  10339. case_end;
  10340. case_ast_node(pg, ProcGroup, node);
  10341. str = gb_string_appendc(str, "proc{");
  10342. for_array(i, pg->args) {
  10343. if (i > 0) str = gb_string_appendc(str, ", ");
  10344. str = write_expr_to_string(str, pg->args[i], shorthand);
  10345. }
  10346. str = gb_string_append_rune(str, '}');
  10347. case_end;
  10348. case_ast_node(pl, ProcLit, node);
  10349. str = write_expr_to_string(str, pl->type, shorthand);
  10350. if (pl->body) {
  10351. str = gb_string_appendc(str, " {...}");
  10352. } else {
  10353. str = gb_string_appendc(str, " ---");
  10354. }
  10355. case_end;
  10356. case_ast_node(cl, CompoundLit, node);
  10357. str = write_expr_to_string(str, cl->type, shorthand);
  10358. str = gb_string_append_rune(str, '{');
  10359. if (shorthand) {
  10360. str = gb_string_appendc(str, "...");
  10361. } else {
  10362. for_array(i, cl->elems) {
  10363. if (i > 0) str = gb_string_appendc(str, ", ");
  10364. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10365. }
  10366. }
  10367. str = gb_string_append_rune(str, '}');
  10368. case_end;
  10369. case_ast_node(te, TagExpr, node);
  10370. str = gb_string_append_rune(str, '#');
  10371. str = string_append_token(str, te->name);
  10372. str = write_expr_to_string(str, te->expr, shorthand);
  10373. case_end;
  10374. case_ast_node(ue, UnaryExpr, node);
  10375. str = string_append_token(str, ue->op);
  10376. str = write_expr_to_string(str, ue->expr, shorthand);
  10377. case_end;
  10378. case_ast_node(de, DerefExpr, node);
  10379. str = write_expr_to_string(str, de->expr, shorthand);
  10380. str = gb_string_append_rune(str, '^');
  10381. case_end;
  10382. case_ast_node(be, BinaryExpr, node);
  10383. str = write_expr_to_string(str, be->left, shorthand);
  10384. str = gb_string_append_rune(str, ' ');
  10385. str = string_append_token(str, be->op);
  10386. str = gb_string_append_rune(str, ' ');
  10387. str = write_expr_to_string(str, be->right, shorthand);
  10388. case_end;
  10389. case_ast_node(te, TernaryIfExpr, node);
  10390. TokenPos x = ast_token(te->x).pos;
  10391. TokenPos cond = ast_token(te->cond).pos;
  10392. if (x < cond) {
  10393. str = write_expr_to_string(str, te->x, shorthand);
  10394. str = gb_string_appendc(str, " if ");
  10395. str = write_expr_to_string(str, te->cond, shorthand);
  10396. str = gb_string_appendc(str, " else ");
  10397. str = write_expr_to_string(str, te->y, shorthand);
  10398. } else {
  10399. str = write_expr_to_string(str, te->cond, shorthand);
  10400. str = gb_string_appendc(str, " ? ");
  10401. str = write_expr_to_string(str, te->x, shorthand);
  10402. str = gb_string_appendc(str, " : ");
  10403. str = write_expr_to_string(str, te->y, shorthand);
  10404. }
  10405. case_end;
  10406. case_ast_node(te, TernaryWhenExpr, node);
  10407. str = write_expr_to_string(str, te->x, shorthand);
  10408. str = gb_string_appendc(str, " when ");
  10409. str = write_expr_to_string(str, te->cond, shorthand);
  10410. str = gb_string_appendc(str, " else ");
  10411. str = write_expr_to_string(str, te->y, shorthand);
  10412. case_end;
  10413. case_ast_node(oe, OrElseExpr, node);
  10414. str = write_expr_to_string(str, oe->x, shorthand);
  10415. str = gb_string_appendc(str, " or_else ");
  10416. str = write_expr_to_string(str, oe->y, shorthand);
  10417. case_end;
  10418. case_ast_node(oe, OrReturnExpr, node);
  10419. str = write_expr_to_string(str, oe->expr, shorthand);
  10420. str = gb_string_appendc(str, " or_return");
  10421. case_end;
  10422. case_ast_node(oe, OrBranchExpr, node);
  10423. str = write_expr_to_string(str, oe->expr, shorthand);
  10424. str = gb_string_append_rune(str, ' ');
  10425. str = string_append_token(str, oe->token);
  10426. if (oe->label) {
  10427. str = gb_string_append_rune(str, ' ');
  10428. str = write_expr_to_string(str, oe->label, shorthand);
  10429. }
  10430. case_end;
  10431. case_ast_node(pe, ParenExpr, node);
  10432. str = gb_string_append_rune(str, '(');
  10433. str = write_expr_to_string(str, pe->expr, shorthand);
  10434. str = gb_string_append_rune(str, ')');
  10435. case_end;
  10436. case_ast_node(se, SelectorExpr, node);
  10437. str = write_expr_to_string(str, se->expr, shorthand);
  10438. str = string_append_token(str, se->token);
  10439. str = write_expr_to_string(str, se->selector, shorthand);
  10440. case_end;
  10441. case_ast_node(se, ImplicitSelectorExpr, node);
  10442. str = gb_string_append_rune(str, '.');
  10443. str = write_expr_to_string(str, se->selector, shorthand);
  10444. case_end;
  10445. case_ast_node(se, SelectorCallExpr, node);
  10446. str = write_expr_to_string(str, se->expr, shorthand);
  10447. str = gb_string_appendc(str, "(");
  10448. ast_node(ce, CallExpr, se->call);
  10449. isize start = se->modified_call ? 1 : 0;
  10450. for (isize i = start; i < ce->args.count; i++) {
  10451. Ast *arg = ce->args[i];
  10452. if (i > start) {
  10453. str = gb_string_appendc(str, ", ");
  10454. }
  10455. str = write_expr_to_string(str, arg, shorthand);
  10456. }
  10457. str = gb_string_appendc(str, ")");
  10458. case_end;
  10459. case_ast_node(ta, TypeAssertion, node);
  10460. str = write_expr_to_string(str, ta->expr, shorthand);
  10461. if (ta->type != nullptr &&
  10462. ta->type->kind == Ast_UnaryExpr &&
  10463. ta->type->UnaryExpr.op.kind == Token_Question) {
  10464. str = gb_string_appendc(str, ".?");
  10465. } else {
  10466. str = gb_string_appendc(str, ".(");
  10467. str = write_expr_to_string(str, ta->type, shorthand);
  10468. str = gb_string_append_rune(str, ')');
  10469. }
  10470. case_end;
  10471. case_ast_node(tc, TypeCast, node);
  10472. str = string_append_token(str, tc->token);
  10473. str = gb_string_append_rune(str, '(');
  10474. str = write_expr_to_string(str, tc->type, shorthand);
  10475. str = gb_string_append_rune(str, ')');
  10476. str = write_expr_to_string(str, tc->expr, shorthand);
  10477. case_end;
  10478. case_ast_node(ac, AutoCast, node);
  10479. str = string_append_token(str, ac->token);
  10480. str = gb_string_append_rune(str, ' ');
  10481. str = write_expr_to_string(str, ac->expr, shorthand);
  10482. case_end;
  10483. case_ast_node(ie, IndexExpr, node);
  10484. str = write_expr_to_string(str, ie->expr, shorthand);
  10485. str = gb_string_append_rune(str, '[');
  10486. str = write_expr_to_string(str, ie->index, shorthand);
  10487. str = gb_string_append_rune(str, ']');
  10488. case_end;
  10489. case_ast_node(se, SliceExpr, node);
  10490. str = write_expr_to_string(str, se->expr, shorthand);
  10491. str = gb_string_append_rune(str, '[');
  10492. str = write_expr_to_string(str, se->low, shorthand);
  10493. str = string_append_token(str, se->interval);
  10494. str = write_expr_to_string(str, se->high, shorthand);
  10495. str = gb_string_append_rune(str, ']');
  10496. case_end;
  10497. case_ast_node(mie, MatrixIndexExpr, node);
  10498. str = write_expr_to_string(str, mie->expr, shorthand);
  10499. str = gb_string_append_rune(str, '[');
  10500. str = write_expr_to_string(str, mie->row_index, shorthand);
  10501. str = gb_string_appendc(str, ", ");
  10502. str = write_expr_to_string(str, mie->column_index, shorthand);
  10503. str = gb_string_append_rune(str, ']');
  10504. case_end;
  10505. case_ast_node(e, Ellipsis, node);
  10506. str = gb_string_appendc(str, "..");
  10507. str = write_expr_to_string(str, e->expr, shorthand);
  10508. case_end;
  10509. case_ast_node(fv, FieldValue, node);
  10510. str = write_expr_to_string(str, fv->field, shorthand);
  10511. str = gb_string_appendc(str, " = ");
  10512. str = write_expr_to_string(str, fv->value, shorthand);
  10513. case_end;
  10514. case_ast_node(fv, EnumFieldValue, node);
  10515. str = write_expr_to_string(str, fv->name, shorthand);
  10516. if (fv->value) {
  10517. str = gb_string_appendc(str, " = ");
  10518. str = write_expr_to_string(str, fv->value, shorthand);
  10519. }
  10520. case_end;
  10521. case_ast_node(ht, HelperType, node);
  10522. str = gb_string_appendc(str, "#type ");
  10523. str = write_expr_to_string(str, ht->type, shorthand);
  10524. case_end;
  10525. case_ast_node(ht, DistinctType, node);
  10526. str = gb_string_appendc(str, "distinct ");
  10527. str = write_expr_to_string(str, ht->type, shorthand);
  10528. case_end;
  10529. case_ast_node(pt, PolyType, node);
  10530. str = gb_string_append_rune(str, '$');
  10531. str = write_expr_to_string(str, pt->type, shorthand);
  10532. if (pt->specialization != nullptr) {
  10533. str = gb_string_append_rune(str, '/');
  10534. str = write_expr_to_string(str, pt->specialization, shorthand);
  10535. }
  10536. case_end;
  10537. case_ast_node(pt, PointerType, node);
  10538. if (pt->tag) {
  10539. str = write_expr_to_string(str, pt->tag, false);
  10540. }
  10541. str = gb_string_append_rune(str, '^');
  10542. str = write_expr_to_string(str, pt->type, shorthand);
  10543. case_end;
  10544. case_ast_node(pt, MultiPointerType, node);
  10545. str = gb_string_appendc(str, "[^]");
  10546. str = write_expr_to_string(str, pt->type, shorthand);
  10547. case_end;
  10548. case_ast_node(at, ArrayType, node);
  10549. if (at->tag) {
  10550. str = write_expr_to_string(str, at->tag, false);
  10551. }
  10552. str = gb_string_append_rune(str, '[');
  10553. if (at->count != nullptr &&
  10554. at->count->kind == Ast_UnaryExpr &&
  10555. at->count->UnaryExpr.op.kind == Token_Question) {
  10556. str = gb_string_appendc(str, "?");
  10557. } else {
  10558. str = write_expr_to_string(str, at->count, shorthand);
  10559. }
  10560. str = gb_string_append_rune(str, ']');
  10561. str = write_expr_to_string(str, at->elem, shorthand);
  10562. case_end;
  10563. case_ast_node(at, DynamicArrayType, node);
  10564. if (at->tag) {
  10565. str = write_expr_to_string(str, at->tag, false);
  10566. }
  10567. str = gb_string_appendc(str, "[dynamic]");
  10568. str = write_expr_to_string(str, at->elem, shorthand);
  10569. case_end;
  10570. case_ast_node(bs, BitSetType, node);
  10571. str = gb_string_appendc(str, "bit_set[");
  10572. str = write_expr_to_string(str, bs->elem, shorthand);
  10573. str = gb_string_appendc(str, "]");
  10574. case_end;
  10575. case_ast_node(mt, MapType, node);
  10576. str = gb_string_appendc(str, "map[");
  10577. str = write_expr_to_string(str, mt->key, shorthand);
  10578. str = gb_string_append_rune(str, ']');
  10579. str = write_expr_to_string(str, mt->value, shorthand);
  10580. case_end;
  10581. case_ast_node(mt, MatrixType, node);
  10582. str = gb_string_appendc(str, "matrix[");
  10583. str = write_expr_to_string(str, mt->row_count, shorthand);
  10584. str = gb_string_appendc(str, ", ");
  10585. str = write_expr_to_string(str, mt->column_count, shorthand);
  10586. str = gb_string_append_rune(str, ']');
  10587. str = write_expr_to_string(str, mt->elem, shorthand);
  10588. case_end;
  10589. case_ast_node(f, Field, node);
  10590. if (f->flags&FieldFlag_using) {
  10591. str = gb_string_appendc(str, "using ");
  10592. }
  10593. if (f->flags&FieldFlag_no_alias) {
  10594. str = gb_string_appendc(str, "#no_alias ");
  10595. }
  10596. if (f->flags&FieldFlag_c_vararg) {
  10597. str = gb_string_appendc(str, "#c_vararg ");
  10598. }
  10599. if (f->flags&FieldFlag_any_int) {
  10600. str = gb_string_appendc(str, "#any_int ");
  10601. }
  10602. if (f->flags&FieldFlag_no_broadcast) {
  10603. str = gb_string_appendc(str, "#no_broadcast ");
  10604. }
  10605. if (f->flags&FieldFlag_const) {
  10606. str = gb_string_appendc(str, "#const ");
  10607. }
  10608. if (f->flags&FieldFlag_subtype) {
  10609. str = gb_string_appendc(str, "#subtype ");
  10610. }
  10611. for_array(i, f->names) {
  10612. Ast *name = f->names[i];
  10613. if (i > 0) str = gb_string_appendc(str, ", ");
  10614. str = write_expr_to_string(str, name, shorthand);
  10615. }
  10616. if (f->names.count > 0) {
  10617. if (f->type == nullptr && f->default_value != nullptr) {
  10618. str = gb_string_append_rune(str, ' ');
  10619. }
  10620. str = gb_string_appendc(str, ":");
  10621. }
  10622. if (f->type != nullptr) {
  10623. str = gb_string_append_rune(str, ' ');
  10624. str = write_expr_to_string(str, f->type, shorthand);
  10625. }
  10626. if (f->default_value != nullptr) {
  10627. if (f->type != nullptr) {
  10628. str = gb_string_append_rune(str, ' ');
  10629. }
  10630. str = gb_string_appendc(str, "= ");
  10631. str = write_expr_to_string(str, f->default_value, shorthand);
  10632. }
  10633. case_end;
  10634. case_ast_node(f, FieldList, node);
  10635. bool has_name = false;
  10636. for_array(i, f->list) {
  10637. ast_node(field, Field, f->list[i]);
  10638. if (field->names.count > 1) {
  10639. has_name = true;
  10640. break;
  10641. }
  10642. if (field->names.count == 0) {
  10643. continue;
  10644. }
  10645. if (!is_blank_ident(field->names[0])) {
  10646. has_name = true;
  10647. break;
  10648. }
  10649. }
  10650. for_array(i, f->list) {
  10651. if (i > 0) str = gb_string_appendc(str, ", ");
  10652. if (has_name) {
  10653. str = write_expr_to_string(str, f->list[i], shorthand);
  10654. } else {
  10655. ast_node(field, Field, f->list[i]);
  10656. if (field->flags&FieldFlag_using) {
  10657. str = gb_string_appendc(str, "using ");
  10658. }
  10659. if (field->flags&FieldFlag_no_alias) {
  10660. str = gb_string_appendc(str, "#no_alias ");
  10661. }
  10662. if (field->flags&FieldFlag_c_vararg) {
  10663. str = gb_string_appendc(str, "#c_vararg ");
  10664. }
  10665. if (field->flags&FieldFlag_any_int) {
  10666. str = gb_string_appendc(str, "#any_int ");
  10667. }
  10668. if (field->flags&FieldFlag_no_broadcast) {
  10669. str = gb_string_appendc(str, "#no_broadcast ");
  10670. }
  10671. if (field->flags&FieldFlag_const) {
  10672. str = gb_string_appendc(str, "#const ");
  10673. }
  10674. if (field->flags&FieldFlag_subtype) {
  10675. str = gb_string_appendc(str, "#subtype ");
  10676. }
  10677. str = write_expr_to_string(str, field->type, shorthand);
  10678. }
  10679. }
  10680. case_end;
  10681. case_ast_node(ce, CallExpr, node);
  10682. switch (ce->inlining) {
  10683. case ProcInlining_inline:
  10684. str = gb_string_appendc(str, "#force_inline ");
  10685. break;
  10686. case ProcInlining_no_inline:
  10687. str = gb_string_appendc(str, "#force_no_inline ");
  10688. break;
  10689. }
  10690. str = write_expr_to_string(str, ce->proc, shorthand);
  10691. str = gb_string_appendc(str, "(");
  10692. isize idx0 = cast(isize)ce->was_selector;
  10693. for (isize i = idx0; i < ce->args.count; i++) {
  10694. Ast *arg = ce->args[i];
  10695. if (i > idx0) {
  10696. str = gb_string_appendc(str, ", ");
  10697. }
  10698. str = write_expr_to_string(str, arg, shorthand);
  10699. }
  10700. str = gb_string_appendc(str, ")");
  10701. case_end;
  10702. case_ast_node(tt, TypeidType, node);
  10703. str = gb_string_appendc(str, "typeid");
  10704. if (tt->specialization) {
  10705. str = gb_string_appendc(str, "/");
  10706. str = write_expr_to_string(str, tt->specialization, shorthand);
  10707. }
  10708. case_end;
  10709. case_ast_node(pt, ProcType, node);
  10710. str = gb_string_appendc(str, "proc(");
  10711. str = write_expr_to_string(str, pt->params, shorthand);
  10712. str = gb_string_appendc(str, ")");
  10713. if (pt->results != nullptr) {
  10714. str = gb_string_appendc(str, " -> ");
  10715. bool parens_needed = false;
  10716. if (pt->results && pt->results->kind == Ast_FieldList) {
  10717. for (Ast *field : pt->results->FieldList.list) {
  10718. ast_node(f, Field, field);
  10719. if (f->names.count != 0) {
  10720. parens_needed = true;
  10721. break;
  10722. }
  10723. }
  10724. }
  10725. if (parens_needed) {
  10726. str = gb_string_append_rune(str, '(');
  10727. }
  10728. str = write_expr_to_string(str, pt->results, shorthand);
  10729. if (parens_needed) {
  10730. str = gb_string_append_rune(str, ')');
  10731. }
  10732. }
  10733. case_end;
  10734. case_ast_node(st, StructType, node);
  10735. str = gb_string_appendc(str, "struct ");
  10736. if (st->polymorphic_params) {
  10737. str = gb_string_append_rune(str, '(');
  10738. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10739. str = gb_string_appendc(str, ") ");
  10740. }
  10741. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10742. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10743. if (st->align) {
  10744. str = gb_string_appendc(str, "#align ");
  10745. str = write_expr_to_string(str, st->align, shorthand);
  10746. str = gb_string_append_rune(str, ' ');
  10747. }
  10748. str = gb_string_append_rune(str, '{');
  10749. if (shorthand) {
  10750. str = gb_string_appendc(str, "...");
  10751. } else {
  10752. str = write_struct_fields_to_string(str, st->fields);
  10753. }
  10754. str = gb_string_append_rune(str, '}');
  10755. case_end;
  10756. case_ast_node(st, UnionType, node);
  10757. str = gb_string_appendc(str, "union ");
  10758. if (st->polymorphic_params) {
  10759. str = gb_string_append_rune(str, '(');
  10760. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10761. str = gb_string_appendc(str, ") ");
  10762. }
  10763. switch (st->kind) {
  10764. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10765. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10766. }
  10767. if (st->align) {
  10768. str = gb_string_appendc(str, "#align ");
  10769. str = write_expr_to_string(str, st->align, shorthand);
  10770. str = gb_string_append_rune(str, ' ');
  10771. }
  10772. str = gb_string_append_rune(str, '{');
  10773. if (shorthand) {
  10774. str = gb_string_appendc(str, "...");
  10775. } else {
  10776. str = write_struct_fields_to_string(str, st->variants);
  10777. }
  10778. str = gb_string_append_rune(str, '}');
  10779. case_end;
  10780. case_ast_node(et, EnumType, node);
  10781. str = gb_string_appendc(str, "enum ");
  10782. if (et->base_type != nullptr) {
  10783. str = write_expr_to_string(str, et->base_type, shorthand);
  10784. str = gb_string_append_rune(str, ' ');
  10785. }
  10786. str = gb_string_append_rune(str, '{');
  10787. if (shorthand) {
  10788. str = gb_string_appendc(str, "...");
  10789. } else {
  10790. for_array(i, et->fields) {
  10791. if (i > 0) {
  10792. str = gb_string_appendc(str, ", ");
  10793. }
  10794. str = write_expr_to_string(str, et->fields[i], shorthand);
  10795. }
  10796. }
  10797. str = gb_string_append_rune(str, '}');
  10798. case_end;
  10799. case_ast_node(rt, RelativeType, node);
  10800. str = write_expr_to_string(str, rt->tag, shorthand);
  10801. str = gb_string_appendc(str, "" );
  10802. str = write_expr_to_string(str, rt->type, shorthand);
  10803. case_end;
  10804. case_ast_node(f, BitFieldField, node);
  10805. str = write_expr_to_string(str, f->name, shorthand);
  10806. str = gb_string_appendc(str, ": ");
  10807. str = write_expr_to_string(str, f->type, shorthand);
  10808. str = gb_string_appendc(str, " | ");
  10809. str = write_expr_to_string(str, f->bit_size, shorthand);
  10810. case_end;
  10811. case_ast_node(bf, BitFieldType, node);
  10812. str = gb_string_appendc(str, "bit_field ");
  10813. if (!shorthand) {
  10814. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10815. }
  10816. str = gb_string_appendc(str, " {");
  10817. if (shorthand) {
  10818. str = gb_string_appendc(str, "...");
  10819. } else {
  10820. for_array(i, bf->fields) {
  10821. if (i > 0) {
  10822. str = gb_string_appendc(str, ", ");
  10823. }
  10824. str = write_expr_to_string(str, bf->fields[i], false);
  10825. }
  10826. }
  10827. str = gb_string_appendc(str, "}");
  10828. case_end;
  10829. case_ast_node(ia, InlineAsmExpr, node);
  10830. str = gb_string_appendc(str, "asm(");
  10831. for_array(i, ia->param_types) {
  10832. if (i > 0) {
  10833. str = gb_string_appendc(str, ", ");
  10834. }
  10835. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10836. }
  10837. str = gb_string_appendc(str, ")");
  10838. if (ia->return_type != nullptr) {
  10839. str = gb_string_appendc(str, " -> ");
  10840. str = write_expr_to_string(str, ia->return_type, shorthand);
  10841. }
  10842. if (ia->has_side_effects) {
  10843. str = gb_string_appendc(str, " #side_effects");
  10844. }
  10845. if (ia->is_align_stack) {
  10846. str = gb_string_appendc(str, " #stack_align");
  10847. }
  10848. if (ia->dialect) {
  10849. str = gb_string_appendc(str, " #");
  10850. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10851. }
  10852. str = gb_string_appendc(str, " {");
  10853. if (shorthand) {
  10854. str = gb_string_appendc(str, "...");
  10855. } else {
  10856. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10857. str = gb_string_appendc(str, ", ");
  10858. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10859. }
  10860. str = gb_string_appendc(str, "}");
  10861. case_end;
  10862. }
  10863. return str;
  10864. }
  10865. gb_internal gbString expr_to_string(Ast *expression) {
  10866. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10867. }
  10868. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10869. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10870. }
  10871. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10872. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10873. }