check_expr.cpp 342 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910
  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 CallArgumentErrorMode {
  39. CallArgumentMode_NoErrors,
  40. CallArgumentMode_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. #define CALL_ARGUMENT_CHECKER(name) CallArgumentError name(CheckerContext *c, Ast *call, Type *proc_type, Entity *entity, Array<Operand> positional_operands, Array<Operand> const &named_operands, CallArgumentErrorMode show_error_mode, CallArgumentData *data)
  61. typedef CALL_ARGUMENT_CHECKER(CallArgumentCheckerType);
  62. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  64. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  65. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  66. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  67. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  68. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  69. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  70. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  71. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  72. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  73. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  74. gb_internal Entity * find_polymorphic_record_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> const &ordered_operands, bool *failure);
  75. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  76. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  77. gb_internal gbString expr_to_string (Ast *expression);
  78. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  79. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  80. gb_internal bool check_is_terminating (Ast *node, String const &label);
  81. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  82. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  83. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  84. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  85. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  86. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  87. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  88. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  89. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  90. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  91. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  92. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type);
  93. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  94. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  95. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  96. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  97. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_);
  98. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  99. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  101. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  102. gb_internal bool is_diverging_expr(Ast *expr);
  103. gb_internal CallArgumentError check_order_of_call_arguments(CheckerContext *c, Type *proc_type, Ast *call, bool show_error);
  104. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  105. enum LoadDirectiveResult {
  106. LoadDirective_Success = 0,
  107. LoadDirective_Error = 1,
  108. LoadDirective_NotFound = 2,
  109. };
  110. gb_internal bool is_load_directive_call(Ast *call) {
  111. call = unparen_expr(call);
  112. if (call->kind != Ast_CallExpr) {
  113. return false;
  114. }
  115. ast_node(ce, CallExpr, call);
  116. if (ce->proc->kind != Ast_BasicDirective) {
  117. return false;
  118. }
  119. ast_node(bd, BasicDirective, ce->proc);
  120. String name = bd->name.string;
  121. return name == "load";
  122. }
  123. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  124. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  125. auto results = did_you_mean_results(d);
  126. if (results.count != 0) {
  127. error_line("\tSuggestion: Did you mean?\n");
  128. for (auto const &result : results) {
  129. String const &target = result.target;
  130. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  131. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  132. }
  133. }
  134. }
  135. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  136. if (e->kind != Entity_TypeName) {
  137. return;
  138. }
  139. if (e->TypeName.objc_metadata == nullptr) {
  140. return;
  141. }
  142. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  143. Type *t = base_type(e->type);
  144. GB_ASSERT(t->kind == Type_Struct);
  145. if (is_type) {
  146. for (auto const &entry : objc_metadata->type_entries) {
  147. string_set_add(set, entry.name);
  148. }
  149. } else {
  150. for (auto const &entry : objc_metadata->value_entries) {
  151. string_set_add(set, entry.name);
  152. }
  153. }
  154. for (Entity *f : t->Struct.fields) {
  155. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  156. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  157. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  158. }
  159. }
  160. }
  161. }
  162. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  163. ERROR_BLOCK();
  164. GB_ASSERT(e->kind == Entity_TypeName);
  165. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  166. auto *objc_metadata = e->TypeName.objc_metadata;
  167. MUTEX_GUARD(objc_metadata->mutex);
  168. StringSet set = {};
  169. defer (string_set_destroy(&set));
  170. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  171. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  172. defer (did_you_mean_destroy(&d));
  173. for (String const &target : set) {
  174. did_you_mean_append(&d, target);
  175. }
  176. check_did_you_mean_print(&d, prefix);
  177. }
  178. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  179. ERROR_BLOCK();
  180. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  181. defer (did_you_mean_destroy(&d));
  182. for (Entity *e : fields) {
  183. did_you_mean_append(&d, e->token.string);
  184. }
  185. check_did_you_mean_print(&d, prefix);
  186. }
  187. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  188. ERROR_BLOCK();
  189. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  190. defer (did_you_mean_destroy(&d));
  191. for (Entity *e : fields) {
  192. did_you_mean_append(&d, e->token.string);
  193. }
  194. check_did_you_mean_print(&d, prefix);
  195. }
  196. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  197. ERROR_BLOCK();
  198. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  199. defer (did_you_mean_destroy(&d));
  200. rw_mutex_shared_lock(&scope->mutex);
  201. for (auto const &entry : scope->elements) {
  202. Entity *e = entry.value;
  203. did_you_mean_append(&d, e->token.string);
  204. }
  205. rw_mutex_shared_unlock(&scope->mutex);
  206. check_did_you_mean_print(&d, prefix);
  207. }
  208. gb_internal Entity *entity_from_expr(Ast *expr) {
  209. expr = unparen_expr(expr);
  210. switch (expr->kind) {
  211. case Ast_Ident:
  212. return expr->Ident.entity;
  213. case Ast_SelectorExpr:
  214. return entity_from_expr(expr->SelectorExpr.selector);
  215. }
  216. return nullptr;
  217. }
  218. gb_internal void error_operand_not_expression(Operand *o) {
  219. if (o->mode == Addressing_Type) {
  220. gbString err = expr_to_string(o->expr);
  221. error(o->expr, "'%s' is not an expression but a type", err);
  222. gb_string_free(err);
  223. o->mode = Addressing_Invalid;
  224. }
  225. }
  226. gb_internal void error_operand_no_value(Operand *o) {
  227. if (o->mode == Addressing_NoValue) {
  228. gbString err = expr_to_string(o->expr);
  229. Ast *x = unparen_expr(o->expr);
  230. if (x->kind == Ast_CallExpr) {
  231. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  232. } else {
  233. error(o->expr, "'%s' used as a value", err);
  234. }
  235. gb_string_free(err);
  236. o->mode = Addressing_Invalid;
  237. }
  238. }
  239. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  240. if (build_context.dynamic_map_calls) {
  241. add_package_dependency(c, "runtime", "__dynamic_map_get");
  242. } else {
  243. add_package_dependency(c, "runtime", "map_desired_position");
  244. add_package_dependency(c, "runtime", "map_probe_distance");
  245. }
  246. }
  247. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  248. init_core_source_code_location(c->checker);
  249. if (t_map_set_proc == nullptr) {
  250. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  251. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  252. }
  253. if (build_context.dynamic_map_calls) {
  254. add_package_dependency(c, "runtime", "__dynamic_map_set");
  255. } else {
  256. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  257. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  258. }
  259. }
  260. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  261. init_core_source_code_location(c->checker);
  262. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  263. }
  264. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  265. Scope *s = c->scope;
  266. check_collect_entities(c, nodes);
  267. for (auto const &entry : s->elements) {
  268. Entity *e = entry.value;
  269. switch (e->kind) {
  270. case Entity_Constant:
  271. case Entity_TypeName:
  272. case Entity_Procedure:
  273. break;
  274. default:
  275. continue;
  276. }
  277. DeclInfo *d = decl_info_of_entity(e);
  278. if (d != nullptr) {
  279. check_entity_decl(c, e, d, nullptr);
  280. }
  281. }
  282. }
  283. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  284. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  285. ///////////////////////////////////////////////////////////////////////////////
  286. // //
  287. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  288. // //
  289. ///////////////////////////////////////////////////////////////////////////////
  290. CheckerInfo *info = old_c->info;
  291. if (base_entity == nullptr) {
  292. return false;
  293. }
  294. if (!is_type_proc(base_entity->type)) {
  295. return false;
  296. }
  297. String name = base_entity->token.string;
  298. Type *src = base_type(base_entity->type);
  299. Type *dst = nullptr;
  300. if (type != nullptr) {
  301. dst = base_type(type);
  302. }
  303. if (param_operands == nullptr) {
  304. GB_ASSERT(dst != nullptr);
  305. }
  306. if (param_operands != nullptr) {
  307. GB_ASSERT(dst == nullptr);
  308. }
  309. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  310. return false;
  311. }
  312. if (dst != nullptr) {
  313. if (dst->Proc.is_polymorphic) {
  314. return false;
  315. }
  316. if (dst->Proc.param_count != src->Proc.param_count ||
  317. dst->Proc.result_count != src->Proc.result_count) {
  318. return false;
  319. }
  320. }
  321. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  322. if (old_decl == nullptr) {
  323. return false;
  324. }
  325. gbAllocator a = heap_allocator();
  326. Array<Operand> operands = {};
  327. if (param_operands) {
  328. operands = *param_operands;
  329. } else {
  330. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  331. for (isize i = 0; i < dst->Proc.param_count; i++) {
  332. Entity *param = dst->Proc.params->Tuple.variables[i];
  333. Operand o = {Addressing_Value};
  334. o.type = param->type;
  335. array_add(&operands, o);
  336. }
  337. }
  338. defer (if (param_operands == nullptr) {
  339. array_free(&operands);
  340. });
  341. CheckerContext nctx = *old_c;
  342. Scope *scope = create_scope(info, base_entity->scope);
  343. scope->flags |= ScopeFlag_Proc;
  344. nctx.scope = scope;
  345. nctx.allow_polymorphic_types = true;
  346. if (nctx.polymorphic_scope == nullptr) {
  347. nctx.polymorphic_scope = scope;
  348. }
  349. auto *pt = &src->Proc;
  350. // NOTE(bill): This is slightly memory leaking if the type already exists
  351. // Maybe it's better to check with the previous types first?
  352. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  353. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  354. if (!success) {
  355. return false;
  356. }
  357. GenProcsData *gen_procs = nullptr;
  358. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  359. GB_ASSERT(base_entity->kind == Entity_Procedure);
  360. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  361. gen_procs = base_entity->Procedure.gen_procs;
  362. if (gen_procs) {
  363. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  364. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  365. for (Entity *other : gen_procs->procs) {
  366. Type *pt = base_type(other->type);
  367. if (are_types_identical(pt, final_proc_type)) {
  368. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  369. if (poly_proc_data) {
  370. poly_proc_data->gen_entity = other;
  371. }
  372. return true;
  373. }
  374. }
  375. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  376. } else {
  377. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  378. gen_procs->procs.allocator = heap_allocator();
  379. base_entity->Procedure.gen_procs = gen_procs;
  380. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  381. }
  382. {
  383. // LEAK TODO(bill): This is technically a memory leak as it has to generate the type twice
  384. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  385. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  386. nctx.no_polymorphic_errors = false;
  387. // NOTE(bill): Reset scope from the failed procedure type
  388. scope_reset(scope);
  389. // LEAK TODO(bill): Cloning this AST may be leaky
  390. Ast *cloned_proc_type_node = clone_ast(pt->node);
  391. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  392. if (!success) {
  393. return false;
  394. }
  395. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  396. for (Entity *other : gen_procs->procs) {
  397. Type *pt = base_type(other->type);
  398. if (are_types_identical(pt, final_proc_type)) {
  399. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  400. if (poly_proc_data) {
  401. poly_proc_data->gen_entity = other;
  402. }
  403. DeclInfo *decl = other->decl_info;
  404. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  405. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  406. proc_info->file = other->file;
  407. proc_info->token = other->token;
  408. proc_info->decl = decl;
  409. proc_info->type = other->type;
  410. proc_info->body = decl->proc_lit->ProcLit.body;
  411. proc_info->tags = other->Procedure.tags;;
  412. proc_info->generated_from_polymorphic = true;
  413. proc_info->poly_def_node = poly_def_node;
  414. check_procedure_later(nctx.checker, proc_info);
  415. }
  416. return true;
  417. }
  418. }
  419. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  420. }
  421. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  422. ast_node(pl, ProcLit, proc_lit);
  423. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  424. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  425. final_proc_type->Proc.is_poly_specialized = true;
  426. final_proc_type->Proc.is_polymorphic = true;
  427. final_proc_type->Proc.variadic = src->Proc.variadic;
  428. final_proc_type->Proc.require_results = src->Proc.require_results;
  429. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  430. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  431. final_proc_type->Proc.diverging = src->Proc.diverging;
  432. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  433. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  434. for (isize i = 0; i < operands.count; i++) {
  435. Operand o = operands[i];
  436. if (final_proc_type == o.type ||
  437. base_entity->type == o.type) {
  438. // NOTE(bill): Cycle
  439. final_proc_type->Proc.is_poly_specialized = false;
  440. break;
  441. }
  442. }
  443. u64 tags = base_entity->Procedure.tags;
  444. Ast *ident = clone_ast(base_entity->identifier);
  445. Token token = ident->Ident.token;
  446. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  447. d->gen_proc_type = final_proc_type;
  448. d->type_expr = pl->type;
  449. d->proc_lit = proc_lit;
  450. d->proc_checked_state = ProcCheckedState_Unchecked;
  451. d->defer_use_checked = false;
  452. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  453. entity->identifier = ident;
  454. add_entity_and_decl_info(&nctx, ident, entity, d);
  455. // NOTE(bill): Set the scope afterwards as this is not real overloading
  456. entity->scope = scope->parent;
  457. entity->file = base_entity->file;
  458. entity->pkg = base_entity->pkg;
  459. entity->flags = 0;
  460. d->entity = entity;
  461. AstFile *file = nullptr;
  462. {
  463. Scope *s = entity->scope;
  464. while (s != nullptr && s->file == nullptr) {
  465. file = s->file;
  466. s = s->parent;
  467. }
  468. }
  469. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  470. array_add(&gen_procs->procs, entity);
  471. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  472. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  473. proc_info->file = file;
  474. proc_info->token = token;
  475. proc_info->decl = d;
  476. proc_info->type = final_proc_type;
  477. proc_info->body = pl->body;
  478. proc_info->tags = tags;
  479. proc_info->generated_from_polymorphic = true;
  480. proc_info->poly_def_node = poly_def_node;
  481. if (poly_proc_data) {
  482. poly_proc_data->gen_entity = entity;
  483. poly_proc_data->proc_info = proc_info;
  484. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  485. }
  486. // NOTE(bill): Check the newly generated procedure body
  487. check_procedure_later(nctx.checker, proc_info);
  488. return true;
  489. }
  490. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  491. if (operand->expr == nullptr) return false;
  492. Entity *base_entity = entity_of_node(operand->expr);
  493. if (base_entity == nullptr) return false;
  494. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  495. }
  496. 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) {
  497. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  498. }
  499. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  500. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  501. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  502. #define MAXIMUM_TYPE_DISTANCE 10
  503. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  504. if (c == nullptr) {
  505. GB_ASSERT(operand->mode == Addressing_Value);
  506. GB_ASSERT(is_type_typed(operand->type));
  507. }
  508. if (operand->mode == Addressing_Invalid ||
  509. type == t_invalid) {
  510. return -1;
  511. }
  512. if (operand->mode == Addressing_Builtin) {
  513. return -1;
  514. }
  515. if (operand->mode == Addressing_Type) {
  516. if (is_type_typeid(type)) {
  517. add_type_info_type(c, operand->type);
  518. return 4;
  519. }
  520. return -1;
  521. }
  522. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  523. return -1;
  524. }
  525. Type *s = operand->type;
  526. if (are_types_identical(s, type)) {
  527. return 0;
  528. }
  529. Type *src = base_type(s);
  530. Type *dst = base_type(type);
  531. if (is_type_untyped_uninit(src)) {
  532. return 1;
  533. }
  534. if (is_type_untyped_nil(src)) {
  535. if (type_has_nil(dst)) {
  536. return 1;
  537. }
  538. return -1;
  539. }
  540. if (is_type_untyped(src)) {
  541. if (is_type_any(dst)) {
  542. // NOTE(bill): Anything can cast to 'Any'
  543. add_type_info_type(c, s);
  544. return MAXIMUM_TYPE_DISTANCE;
  545. }
  546. if (dst->kind == Type_Basic) {
  547. if (operand->mode == Addressing_Constant) {
  548. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  549. if (is_type_typed(dst) && src->kind == Type_Basic) {
  550. switch (src->Basic.kind) {
  551. case Basic_UntypedRune:
  552. if (is_type_integer(dst) || is_type_rune(dst)) {
  553. return 1;
  554. }
  555. break;
  556. case Basic_UntypedInteger:
  557. if (is_type_integer(dst) || is_type_rune(dst)) {
  558. return 1;
  559. }
  560. break;
  561. case Basic_UntypedFloat:
  562. if (is_type_float(dst)) {
  563. return 1;
  564. }
  565. break;
  566. case Basic_UntypedComplex:
  567. if (is_type_complex(dst)) {
  568. return 1;
  569. }
  570. if (is_type_quaternion(dst)) {
  571. return 2;
  572. }
  573. break;
  574. case Basic_UntypedQuaternion:
  575. if (is_type_quaternion(dst)) {
  576. return 1;
  577. }
  578. break;
  579. }
  580. }
  581. return 2;
  582. }
  583. return -1;
  584. }
  585. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedRune) {
  586. if (is_type_integer(dst) || is_type_rune(dst)) {
  587. if (is_type_typed(type)) {
  588. return 2;
  589. }
  590. return 1;
  591. }
  592. return -1;
  593. }
  594. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedBool) {
  595. if (is_type_boolean(dst)) {
  596. if (is_type_typed(type)) {
  597. return 2;
  598. }
  599. return 1;
  600. }
  601. return -1;
  602. }
  603. }
  604. }
  605. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  606. if (c->in_enum_type) {
  607. return 3;
  608. }
  609. }
  610. {
  611. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  612. if (subtype_level > 0) {
  613. return 4 + subtype_level;
  614. }
  615. }
  616. // ^T <- rawptr
  617. #if 0
  618. // TODO(bill): Should C-style (not C++) pointer cast be allowed?
  619. if (is_type_pointer(dst) && is_type_rawptr(src)) {
  620. return true;
  621. }
  622. #endif
  623. #if 1
  624. // rawptr <- ^T
  625. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  626. return 5;
  627. }
  628. // rawptr <- [^]T
  629. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  630. return 5;
  631. }
  632. // ^T <- [^]T
  633. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  634. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  635. return 4;
  636. }
  637. }
  638. // [^]T <- ^T
  639. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  640. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  641. return 4;
  642. }
  643. }
  644. #endif
  645. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  646. bool modify_type = !c->no_polymorphic_errors;
  647. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  648. return 2;
  649. }
  650. }
  651. if (is_type_union(dst)) {
  652. for (Type *vt : dst->Union.variants) {
  653. if (are_types_identical(vt, s)) {
  654. return 1;
  655. }
  656. }
  657. // TODO(bill): Determine which rule is a better on in practice
  658. if (dst->Union.variants.count == 1) {
  659. Type *vt = dst->Union.variants[0];
  660. i64 score = check_distance_between_types(c, operand, vt);
  661. if (score >= 0) {
  662. return score+2;
  663. }
  664. } else if (is_type_untyped(src)) {
  665. i64 prev_lowest_score = -1;
  666. i64 lowest_score = -1;
  667. for (Type *vt : dst->Union.variants) {
  668. i64 score = check_distance_between_types(c, operand, vt);
  669. if (score >= 0) {
  670. if (lowest_score < 0) {
  671. lowest_score = score;
  672. } else {
  673. if (prev_lowest_score < 0) {
  674. prev_lowest_score = lowest_score;
  675. } else {
  676. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  677. }
  678. lowest_score = gb_min(lowest_score, score);
  679. }
  680. }
  681. }
  682. if (lowest_score >= 0) {
  683. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  684. return lowest_score+2;
  685. }
  686. }
  687. }
  688. }
  689. if (is_type_relative_pointer(dst)) {
  690. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  691. if (score >= 0) {
  692. return score+2;
  693. }
  694. }
  695. if (is_type_relative_slice(dst)) {
  696. i64 score = check_distance_between_types(c, operand, dst->RelativeSlice.slice_type);
  697. if (score >= 0) {
  698. return score+2;
  699. }
  700. }
  701. if (is_type_proc(dst)) {
  702. if (are_types_identical(src, dst)) {
  703. return 3;
  704. }
  705. PolyProcData poly_proc_data = {};
  706. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  707. Entity *e = poly_proc_data.gen_entity;
  708. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  709. add_entity_use(c, operand->expr, e);
  710. return 4;
  711. }
  712. }
  713. if (is_type_complex_or_quaternion(dst)) {
  714. Type *elem = base_complex_elem_type(dst);
  715. if (are_types_identical(elem, base_type(src))) {
  716. return 5;
  717. }
  718. }
  719. if (is_type_array(dst)) {
  720. Type *elem = base_array_type(dst);
  721. i64 distance = check_distance_between_types(c, operand, elem);
  722. if (distance >= 0) {
  723. return distance + 6;
  724. }
  725. }
  726. if (is_type_simd_vector(dst)) {
  727. Type *dst_elem = base_array_type(dst);
  728. i64 distance = check_distance_between_types(c, operand, dst_elem);
  729. if (distance >= 0) {
  730. return distance + 6;
  731. }
  732. }
  733. if (is_type_matrix(dst)) {
  734. if (are_types_identical(src, dst)) {
  735. return 5;
  736. }
  737. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  738. Type *dst_elem = base_array_type(dst);
  739. i64 distance = check_distance_between_types(c, operand, dst_elem);
  740. if (distance >= 0) {
  741. return distance + 7;
  742. }
  743. }
  744. }
  745. if (is_type_any(dst)) {
  746. if (!is_type_polymorphic(src)) {
  747. if (operand->mode == Addressing_Context && operand->type == t_context) {
  748. return -1;
  749. } else {
  750. // NOTE(bill): Anything can cast to 'Any'
  751. add_type_info_type(c, s);
  752. return MAXIMUM_TYPE_DISTANCE;
  753. }
  754. }
  755. }
  756. Ast *expr = unparen_expr(operand->expr);
  757. if (expr != nullptr) {
  758. if (expr->kind == Ast_AutoCast) {
  759. Operand x = *operand;
  760. x.expr = expr->AutoCast.expr;
  761. if (check_cast_internal(c, &x, type)) {
  762. return MAXIMUM_TYPE_DISTANCE;
  763. }
  764. }
  765. }
  766. return -1;
  767. }
  768. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  769. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  770. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  771. // TODO(bill): A decent score function
  772. i64 d = distance*distance; // x^2
  773. if (is_variadic && d >= 0) {
  774. d += distance + 1; // x^2 + x + 1
  775. }
  776. return gb_max(c - d, 0);
  777. }
  778. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  779. i64 score = 0;
  780. i64 distance = check_distance_between_types(c, operand, type);
  781. bool ok = distance >= 0;
  782. if (ok) {
  783. score = assign_score_function(distance, is_variadic);
  784. }
  785. if (score_) *score_ = score;
  786. return ok;
  787. }
  788. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  789. i64 score = 0;
  790. return check_is_assignable_to_with_score(c, operand, type, &score);
  791. }
  792. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  793. Operand x = {};
  794. x.type = src;
  795. x.mode = Addressing_Value;
  796. return check_is_assignable_to(nullptr, &x, dst);
  797. }
  798. gb_internal AstPackage *get_package_of_type(Type *type) {
  799. for (;;) {
  800. if (type == nullptr) {
  801. return nullptr;
  802. }
  803. switch (type->kind) {
  804. case Type_Basic:
  805. return builtin_pkg;
  806. case Type_Named:
  807. if (type->Named.type_name != nullptr) {
  808. return type->Named.type_name->pkg;
  809. }
  810. return nullptr;
  811. case Type_Pointer:
  812. type = type->Pointer.elem;
  813. continue;
  814. case Type_Array:
  815. type = type->Array.elem;
  816. continue;
  817. case Type_Slice:
  818. type = type->Slice.elem;
  819. continue;
  820. case Type_DynamicArray:
  821. type = type->DynamicArray.elem;
  822. continue;
  823. case Type_RelativePointer:
  824. type = type->RelativePointer.pointer_type;
  825. continue;
  826. case Type_RelativeSlice:
  827. type = type->RelativeSlice.slice_type;
  828. continue;
  829. }
  830. return nullptr;
  831. }
  832. }
  833. // NOTE(bill): 'content_name' is for debugging and error messages
  834. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  835. check_not_tuple(c, operand);
  836. if (operand->mode == Addressing_Invalid) {
  837. return;
  838. }
  839. if (is_type_untyped(operand->type)) {
  840. Type *target_type = type;
  841. if (type == nullptr || is_type_any(type)) {
  842. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  843. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  844. operand->mode = Addressing_Invalid;
  845. return;
  846. }
  847. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  848. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  849. operand->mode = Addressing_Invalid;
  850. return;
  851. }
  852. target_type = default_type(operand->type);
  853. if (type != nullptr && !is_type_any(type)) {
  854. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  855. }
  856. add_type_info_type(c, type);
  857. add_type_info_type(c, target_type);
  858. }
  859. convert_to_typed(c, operand, target_type);
  860. if (operand->mode == Addressing_Invalid) {
  861. return;
  862. }
  863. }
  864. if (type == nullptr) {
  865. return;
  866. }
  867. if (operand->mode == Addressing_ProcGroup) {
  868. bool good = false;
  869. if (type != nullptr && is_type_proc(type)) {
  870. Array<Entity *> procs = proc_group_entities(c, *operand);
  871. // NOTE(bill): These should be done
  872. for (Entity *e : procs) {
  873. Type *t = base_type(e->type);
  874. if (t == t_invalid) {
  875. continue;
  876. }
  877. Operand x = {};
  878. x.mode = Addressing_Value;
  879. x.type = t;
  880. if (check_is_assignable_to(c, &x, type)) {
  881. add_entity_use(c, operand->expr, e);
  882. good = true;
  883. break;
  884. }
  885. }
  886. }
  887. if (!good) {
  888. gbString expr_str = expr_to_string(operand->expr);
  889. gbString op_type_str = type_to_string(operand->type);
  890. gbString type_str = type_to_string(type);
  891. defer (gb_string_free(type_str));
  892. defer (gb_string_free(op_type_str));
  893. defer (gb_string_free(expr_str));
  894. // TODO(bill): is this a good enough error message?
  895. error(operand->expr,
  896. "Cannot assign overloaded procedure '%s' to '%s' in %.*s",
  897. expr_str,
  898. op_type_str,
  899. LIT(context_name));
  900. operand->mode = Addressing_Invalid;
  901. }
  902. convert_to_typed(c, operand, type);
  903. return;
  904. }
  905. if (check_is_assignable_to(c, operand, type)) {
  906. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  907. add_type_info_type(c, operand->type);
  908. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  909. }
  910. } else {
  911. gbString expr_str = expr_to_string(operand->expr);
  912. gbString op_type_str = type_to_string(operand->type);
  913. gbString type_str = type_to_string(type);
  914. defer (gb_string_free(type_str));
  915. defer (gb_string_free(op_type_str));
  916. defer (gb_string_free(expr_str));
  917. switch (operand->mode) {
  918. case Addressing_Builtin:
  919. // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use
  920. error(operand->expr,
  921. "Cannot assign built-in procedure '%s' in %.*s",
  922. expr_str,
  923. LIT(context_name));
  924. break;
  925. case Addressing_Type:
  926. error(operand->expr,
  927. "Cannot assign '%s' which is a type in %.*s",
  928. op_type_str,
  929. LIT(context_name));
  930. break;
  931. default:
  932. // TODO(bill): is this a good enough error message?
  933. {
  934. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  935. gbString type_extra = gb_string_make(heap_allocator(), "");
  936. defer (gb_string_free(op_type_extra));
  937. defer (gb_string_free(type_extra));
  938. isize on = gb_string_length(op_type_str);
  939. isize tn = gb_string_length(type_str);
  940. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  941. AstPackage *op_pkg = get_package_of_type(operand->type);
  942. AstPackage *type_pkg = get_package_of_type(type);
  943. if (op_pkg != nullptr) {
  944. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  945. }
  946. if (type_pkg != nullptr) {
  947. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  948. }
  949. }
  950. ERROR_BLOCK();
  951. error(operand->expr,
  952. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  953. expr_str,
  954. op_type_str, op_type_extra,
  955. type_str, type_extra,
  956. LIT(context_name));
  957. check_assignment_error_suggestion(c, operand, type);
  958. }
  959. break;
  960. }
  961. operand->mode = Addressing_Invalid;
  962. return;
  963. }
  964. }
  965. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  966. Type *gt = *gt_;
  967. GB_ASSERT(gt->kind == Type_Generic);
  968. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  969. GB_ASSERT(e != nullptr);
  970. if (e->kind == Entity_TypeName) {
  971. *gt_ = nullptr;
  972. *dst_count = source_count;
  973. e->kind = Entity_Constant;
  974. e->Constant.value = exact_value_i64(source_count);
  975. e->type = t_untyped_integer;
  976. return true;
  977. } else if (e->kind == Entity_Constant) {
  978. *gt_ = nullptr;
  979. if (e->Constant.value.kind != ExactValue_Integer) {
  980. return false;
  981. }
  982. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  983. if (count != source_count) {
  984. return false;
  985. }
  986. *dst_count = source_count;
  987. return true;
  988. }
  989. return false;
  990. }
  991. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  992. Operand o = {Addressing_Value};
  993. o.type = source;
  994. switch (poly->kind) {
  995. case Type_Basic:
  996. if (compound) return are_types_identical(poly, source);
  997. return check_is_assignable_to(c, &o, poly);
  998. case Type_Named: {
  999. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1000. return true;
  1001. }
  1002. if (compound || !is_type_generic(poly)) {
  1003. return are_types_identical(poly, source);
  1004. }
  1005. return check_is_assignable_to(c, &o, poly);
  1006. }
  1007. case Type_Generic: {
  1008. if (poly->Generic.specialized != nullptr) {
  1009. Type *s = poly->Generic.specialized;
  1010. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1011. return false;
  1012. }
  1013. }
  1014. if (modify_type) {
  1015. Type *ds = default_type(source);
  1016. gb_memmove(poly, ds, gb_size_of(Type));
  1017. }
  1018. return true;
  1019. }
  1020. case Type_Pointer:
  1021. if (source->kind == Type_Pointer) {
  1022. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem);
  1023. if (level > 0) {
  1024. return true;
  1025. }
  1026. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1027. } else if (source->kind == Type_MultiPointer) {
  1028. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1029. if (level > 0) {
  1030. return true;
  1031. }
  1032. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1033. }
  1034. return false;
  1035. case Type_MultiPointer:
  1036. if (source->kind == Type_MultiPointer) {
  1037. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1038. if (level > 0) {
  1039. return true;
  1040. }
  1041. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1042. } else if (source->kind == Type_Pointer) {
  1043. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1044. if (level > 0) {
  1045. return true;
  1046. }
  1047. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1048. }
  1049. return false;
  1050. case Type_Array:
  1051. if (source->kind == Type_Array) {
  1052. if (poly->Array.generic_count != nullptr) {
  1053. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1054. return false;
  1055. }
  1056. }
  1057. if (poly->Array.count == source->Array.count) {
  1058. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1059. }
  1060. } else if (source->kind == Type_EnumeratedArray) {
  1061. if (poly->Array.generic_count != nullptr) {
  1062. Type *gt = poly->Array.generic_count;
  1063. GB_ASSERT(gt->kind == Type_Generic);
  1064. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1065. GB_ASSERT(e != nullptr);
  1066. if (e->kind == Entity_TypeName) {
  1067. Type *index = source->EnumeratedArray.index;
  1068. Type *it = base_type(index);
  1069. if (it->kind != Type_Enum) {
  1070. return false;
  1071. }
  1072. poly->kind = Type_EnumeratedArray;
  1073. poly->cached_size = -1;
  1074. poly->cached_align = -1;
  1075. poly->flags.exchange(source->flags);
  1076. poly->failure = false;
  1077. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1078. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1079. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1080. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1081. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1082. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1083. e->kind = Entity_TypeName;
  1084. e->TypeName.is_type_alias = true;
  1085. e->type = index;
  1086. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1087. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1088. }
  1089. }
  1090. }
  1091. }
  1092. return false;
  1093. case Type_EnumeratedArray:
  1094. if (source->kind == Type_EnumeratedArray) {
  1095. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1096. return false;
  1097. }
  1098. if (poly->EnumeratedArray.op) {
  1099. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1100. return false;
  1101. }
  1102. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1103. return false;
  1104. }
  1105. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1106. return false;
  1107. }
  1108. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1109. }
  1110. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1111. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1112. return index || elem;
  1113. }
  1114. return false;
  1115. case Type_DynamicArray:
  1116. if (source->kind == Type_DynamicArray) {
  1117. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1118. }
  1119. return false;
  1120. case Type_Slice:
  1121. if (source->kind == Type_Slice) {
  1122. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1123. }
  1124. return false;
  1125. case Type_Enum:
  1126. return false;
  1127. case Type_BitSet:
  1128. if (source->kind == Type_BitSet) {
  1129. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1130. return false;
  1131. }
  1132. if (poly->BitSet.underlying == nullptr) {
  1133. if (modify_type) {
  1134. poly->BitSet.underlying = source->BitSet.underlying;
  1135. }
  1136. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1137. return false;
  1138. }
  1139. return true;
  1140. }
  1141. return false;
  1142. case Type_Union:
  1143. if (source->kind == Type_Union) {
  1144. TypeUnion *x = &poly->Union;
  1145. TypeUnion *y = &source->Union;
  1146. if (x->variants.count != y->variants.count) {
  1147. return false;
  1148. }
  1149. for_array(i, x->variants) {
  1150. Type *a = x->variants[i];
  1151. Type *b = y->variants[i];
  1152. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1153. if (!ok) return false;
  1154. }
  1155. return true;
  1156. }
  1157. return false;
  1158. case Type_Struct:
  1159. if (source->kind == Type_Struct) {
  1160. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1161. poly->Struct.soa_kind != StructSoa_None) {
  1162. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1163. if (ok) switch (source->Struct.soa_kind) {
  1164. case StructSoa_Fixed:
  1165. default:
  1166. GB_PANIC("Unhandled SOA Kind");
  1167. break;
  1168. case StructSoa_Slice:
  1169. if (modify_type) {
  1170. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1171. gb_memmove(poly, type, gb_size_of(*type));
  1172. }
  1173. break;
  1174. case StructSoa_Dynamic:
  1175. if (modify_type) {
  1176. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1177. gb_memmove(poly, type, gb_size_of(*type));
  1178. }
  1179. break;
  1180. }
  1181. return ok;
  1182. }
  1183. // return check_is_assignable_to(c, &o, poly);
  1184. }
  1185. return false;
  1186. case Type_Tuple:
  1187. GB_PANIC("This should never happen");
  1188. return false;
  1189. case Type_Proc:
  1190. if (source->kind == Type_Proc) {
  1191. // return check_is_assignable_to(c, &o, poly);
  1192. // TODO(bill): Polymorphic type assignment
  1193. #if 1
  1194. TypeProc *x = &poly->Proc;
  1195. TypeProc *y = &source->Proc;
  1196. if (x->calling_convention != y->calling_convention) {
  1197. return false;
  1198. }
  1199. if (x->c_vararg != y->c_vararg) {
  1200. return false;
  1201. }
  1202. if (x->variadic != y->variadic) {
  1203. return false;
  1204. }
  1205. if (x->param_count != y->param_count) {
  1206. return false;
  1207. }
  1208. if (x->result_count != y->result_count) {
  1209. return false;
  1210. }
  1211. for (isize i = 0; i < x->param_count; i++) {
  1212. Entity *a = x->params->Tuple.variables[i];
  1213. Entity *b = y->params->Tuple.variables[i];
  1214. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1215. if (!ok) return false;
  1216. }
  1217. for (isize i = 0; i < x->result_count; i++) {
  1218. Entity *a = x->results->Tuple.variables[i];
  1219. Entity *b = y->results->Tuple.variables[i];
  1220. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1221. if (!ok) return false;
  1222. }
  1223. return true;
  1224. #endif
  1225. }
  1226. return false;
  1227. case Type_Map:
  1228. if (source->kind == Type_Map) {
  1229. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1230. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1231. if (key || value) {
  1232. poly->Map.lookup_result_type = nullptr;
  1233. init_map_internal_types(poly);
  1234. return true;
  1235. }
  1236. }
  1237. return false;
  1238. case Type_Matrix:
  1239. if (source->kind == Type_Matrix) {
  1240. if (poly->Matrix.generic_row_count != nullptr) {
  1241. poly->Matrix.stride_in_bytes = 0;
  1242. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1243. return false;
  1244. }
  1245. }
  1246. if (poly->Matrix.generic_column_count != nullptr) {
  1247. poly->Matrix.stride_in_bytes = 0;
  1248. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1249. return false;
  1250. }
  1251. }
  1252. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1253. poly->Matrix.column_count == source->Matrix.column_count) {
  1254. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1255. }
  1256. }
  1257. return false;
  1258. case Type_SimdVector:
  1259. if (source->kind == Type_SimdVector) {
  1260. if (poly->SimdVector.generic_count != nullptr) {
  1261. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1262. return false;
  1263. }
  1264. }
  1265. if (poly->SimdVector.count == source->SimdVector.count) {
  1266. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1267. }
  1268. }
  1269. return false;
  1270. }
  1271. return false;
  1272. }
  1273. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1274. if (curr->state != EntityState_InProgress) {
  1275. return false;
  1276. }
  1277. for_array(i, *c->type_path) {
  1278. Entity *prev = c->type_path->data[i];
  1279. if (prev == curr) {
  1280. if (report) {
  1281. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1282. for (isize j = i; j < c->type_path->count; j++) {
  1283. Entity *curr = (*c->type_path)[j];
  1284. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1285. }
  1286. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1287. curr->type = t_invalid;
  1288. }
  1289. return true;
  1290. }
  1291. }
  1292. return false;
  1293. }
  1294. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1295. GB_ASSERT(n->kind == Ast_Ident);
  1296. o->mode = Addressing_Invalid;
  1297. o->expr = n;
  1298. String name = n->Ident.token.string;
  1299. Entity *e = scope_lookup(c->scope, name);
  1300. if (e == nullptr) {
  1301. if (is_blank_ident(name)) {
  1302. error(n, "'_' cannot be used as a value");
  1303. } else {
  1304. error(n, "Undeclared name: %.*s", LIT(name));
  1305. }
  1306. o->type = t_invalid;
  1307. o->mode = Addressing_Invalid;
  1308. if (named_type != nullptr) {
  1309. set_base_type(named_type, t_invalid);
  1310. }
  1311. return nullptr;
  1312. }
  1313. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1314. if (e->parent_proc_decl != nullptr &&
  1315. e->parent_proc_decl != c->curr_proc_decl) {
  1316. if (e->kind == Entity_Variable) {
  1317. if ((e->flags & EntityFlag_Static) == 0) {
  1318. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1319. return nullptr;
  1320. }
  1321. } else if (e->kind == Entity_Label) {
  1322. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1323. return nullptr;
  1324. }
  1325. }
  1326. if (e->kind == Entity_ProcGroup) {
  1327. auto *pge = &e->ProcGroup;
  1328. DeclInfo *d = decl_info_of_entity(e);
  1329. check_entity_decl(c, e, d, nullptr);
  1330. Array<Entity *> procs = pge->entities;
  1331. bool skip = false;
  1332. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1333. // NOTE(bill): These should be done
  1334. for (Entity *proc : procs) {
  1335. Type *t = base_type(proc->type);
  1336. if (t == t_invalid) {
  1337. continue;
  1338. }
  1339. Operand x = {};
  1340. x.mode = Addressing_Value;
  1341. x.type = t;
  1342. if (check_is_assignable_to(c, &x, type_hint)) {
  1343. e = proc;
  1344. add_entity_use(c, n, e);
  1345. skip = true;
  1346. break;
  1347. }
  1348. }
  1349. }
  1350. if (!skip) {
  1351. o->mode = Addressing_ProcGroup;
  1352. o->type = t_invalid;
  1353. o->proc_group = e;
  1354. return nullptr;
  1355. }
  1356. }
  1357. add_entity_use(c, n, e);
  1358. if (e->state == EntityState_Unresolved) {
  1359. check_entity_decl(c, e, nullptr, named_type);
  1360. }
  1361. if (e->type == nullptr) {
  1362. // TODO(bill): Which is correct? return or compiler_error?
  1363. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1364. return nullptr;
  1365. }
  1366. e->flags |= EntityFlag_Used;
  1367. Type *type = e->type;
  1368. o->type = type;
  1369. switch (e->kind) {
  1370. case Entity_Constant:
  1371. if (type == t_invalid) {
  1372. o->type = t_invalid;
  1373. return e;
  1374. }
  1375. o->value = e->Constant.value;
  1376. if (o->value.kind == ExactValue_Invalid) {
  1377. return e;
  1378. }
  1379. if (o->value.kind == ExactValue_Procedure) {
  1380. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1381. if (proc != nullptr) {
  1382. o->mode = Addressing_Value;
  1383. o->type = proc->type;
  1384. return proc;
  1385. }
  1386. }
  1387. o->mode = Addressing_Constant;
  1388. break;
  1389. case Entity_Variable:
  1390. e->flags |= EntityFlag_Used;
  1391. if (type == t_invalid) {
  1392. o->type = t_invalid;
  1393. return e;
  1394. }
  1395. o->mode = Addressing_Variable;
  1396. if (e->flags & EntityFlag_Value) {
  1397. o->mode = Addressing_Value;
  1398. }
  1399. break;
  1400. case Entity_Procedure:
  1401. o->mode = Addressing_Value;
  1402. o->value = exact_value_procedure(n);
  1403. break;
  1404. case Entity_Builtin:
  1405. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1406. o->mode = Addressing_Builtin;
  1407. break;
  1408. case Entity_TypeName:
  1409. o->mode = Addressing_Type;
  1410. if (check_cycle(c, e, true)) {
  1411. o->type = t_invalid;
  1412. }
  1413. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1414. o->type = base_type(o->type);
  1415. }
  1416. break;
  1417. case Entity_ImportName:
  1418. if (!allow_import_name) {
  1419. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1420. }
  1421. return e;
  1422. case Entity_LibraryName:
  1423. if (!allow_import_name) {
  1424. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1425. }
  1426. return e;
  1427. case Entity_Label:
  1428. o->mode = Addressing_NoValue;
  1429. break;
  1430. case Entity_Nil:
  1431. o->mode = Addressing_Value;
  1432. break;
  1433. default:
  1434. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1435. break;
  1436. }
  1437. return e;
  1438. }
  1439. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1440. if (o->type == nullptr) {
  1441. gbString str = expr_to_string(o->expr);
  1442. error(o->expr, "Expression has no value '%s'", str);
  1443. gb_string_free(str);
  1444. return false;
  1445. }
  1446. // TODO(bill): Handle errors correctly
  1447. Type *type = base_type(core_array_type(o->type));
  1448. gbString str = nullptr;
  1449. switch (op.kind) {
  1450. case Token_Add:
  1451. case Token_Sub:
  1452. if (!is_type_numeric(type)) {
  1453. str = expr_to_string(o->expr);
  1454. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1455. gb_string_free(str);
  1456. }
  1457. break;
  1458. case Token_Xor:
  1459. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1460. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1461. }
  1462. break;
  1463. case Token_Not:
  1464. if (!is_type_boolean(type)) {
  1465. ERROR_BLOCK();
  1466. str = expr_to_string(o->expr);
  1467. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1468. gb_string_free(str);
  1469. if (is_type_integer(type)) {
  1470. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1471. }
  1472. } else {
  1473. o->type = t_untyped_bool;
  1474. }
  1475. break;
  1476. default:
  1477. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1478. return false;
  1479. }
  1480. return true;
  1481. }
  1482. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1483. Type *main_type = o->type;
  1484. // TODO(bill): Handle errors correctly
  1485. Type *type = base_type(core_array_type(main_type));
  1486. Type *ct = core_type(type);
  1487. switch (op.kind) {
  1488. case Token_Sub:
  1489. case Token_SubEq:
  1490. if (is_type_bit_set(type)) {
  1491. return true;
  1492. } else if (!is_type_numeric(type)) {
  1493. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1494. return false;
  1495. }
  1496. break;
  1497. case Token_Quo:
  1498. case Token_QuoEq:
  1499. if (is_type_matrix(main_type)) {
  1500. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1501. return false;
  1502. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1503. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1504. return false;
  1505. }
  1506. /*fallthrough*/
  1507. case Token_Mul:
  1508. case Token_MulEq:
  1509. case Token_AddEq:
  1510. if (is_type_bit_set(type)) {
  1511. return true;
  1512. } else if (!is_type_numeric(type)) {
  1513. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1514. return false;
  1515. }
  1516. break;
  1517. case Token_Add:
  1518. if (is_type_string(type)) {
  1519. if (o->mode == Addressing_Constant) {
  1520. return true;
  1521. }
  1522. error(op, "String concatenation is only allowed with constant strings");
  1523. return false;
  1524. } else if (is_type_bit_set(type)) {
  1525. return true;
  1526. } else if (!is_type_numeric(type)) {
  1527. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1528. return false;
  1529. }
  1530. break;
  1531. case Token_And:
  1532. case Token_Or:
  1533. case Token_AndEq:
  1534. case Token_OrEq:
  1535. case Token_Xor:
  1536. case Token_XorEq:
  1537. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1538. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1539. return false;
  1540. }
  1541. break;
  1542. case Token_Mod:
  1543. case Token_ModMod:
  1544. case Token_ModEq:
  1545. case Token_ModModEq:
  1546. if (is_type_matrix(main_type)) {
  1547. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1548. return false;
  1549. }
  1550. if (!is_type_integer(type)) {
  1551. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1552. return false;
  1553. } else if (is_type_simd_vector(main_type)) {
  1554. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1555. return false;
  1556. }
  1557. break;
  1558. case Token_AndNot:
  1559. case Token_AndNotEq:
  1560. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1561. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1562. return false;
  1563. }
  1564. break;
  1565. case Token_CmpAnd:
  1566. case Token_CmpOr:
  1567. case Token_CmpAndEq:
  1568. case Token_CmpOrEq:
  1569. if (!is_type_boolean(type)) {
  1570. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1571. return false;
  1572. }
  1573. break;
  1574. default:
  1575. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1576. return false;
  1577. }
  1578. return true;
  1579. }
  1580. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1581. if (in_value.kind == ExactValue_Invalid) {
  1582. // NOTE(bill): There's already been an error
  1583. return true;
  1584. }
  1585. type = core_type(type);
  1586. if (type == t_invalid) {
  1587. return false;
  1588. } else if (is_type_boolean(type)) {
  1589. return in_value.kind == ExactValue_Bool;
  1590. } else if (is_type_string(type)) {
  1591. return in_value.kind == ExactValue_String;
  1592. } else if (is_type_integer(type) || is_type_rune(type)) {
  1593. if (in_value.kind == ExactValue_Bool) {
  1594. return false;
  1595. }
  1596. ExactValue v = exact_value_to_integer(in_value);
  1597. if (v.kind != ExactValue_Integer) {
  1598. return false;
  1599. }
  1600. if (out_value) *out_value = v;
  1601. if (is_type_untyped(type)) {
  1602. return true;
  1603. }
  1604. BigInt i = v.value_integer;
  1605. i64 bit_size = type_size_of(type);
  1606. BigInt umax = {};
  1607. BigInt imin = {};
  1608. BigInt imax = {};
  1609. if (bit_size < 16) {
  1610. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1611. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1612. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1613. } else {
  1614. big_int_from_u64(&umax, 1);
  1615. big_int_from_i64(&imin, 1);
  1616. big_int_from_i64(&imax, 1);
  1617. BigInt bi128 = {};
  1618. BigInt bi127 = {};
  1619. big_int_from_i64(&bi128, 128);
  1620. big_int_from_i64(&bi127, 127);
  1621. big_int_shl_eq(&umax, &bi128);
  1622. mp_decr(&umax);
  1623. big_int_shl_eq(&imin, &bi127);
  1624. big_int_neg(&imin, &imin);
  1625. big_int_shl_eq(&imax, &bi127);
  1626. mp_decr(&imax);
  1627. }
  1628. switch (type->Basic.kind) {
  1629. case Basic_rune:
  1630. case Basic_i8:
  1631. case Basic_i16:
  1632. case Basic_i32:
  1633. case Basic_i64:
  1634. case Basic_i128:
  1635. case Basic_int:
  1636. case Basic_i16le:
  1637. case Basic_i32le:
  1638. case Basic_i64le:
  1639. case Basic_i128le:
  1640. case Basic_i16be:
  1641. case Basic_i32be:
  1642. case Basic_i64be:
  1643. case Basic_i128be:
  1644. {
  1645. // return imin <= i && i <= imax;
  1646. int a = big_int_cmp(&imin, &i);
  1647. int b = big_int_cmp(&i, &imax);
  1648. return (a <= 0) && (b <= 0);
  1649. }
  1650. case Basic_u8:
  1651. case Basic_u16:
  1652. case Basic_u32:
  1653. case Basic_u64:
  1654. case Basic_u128:
  1655. case Basic_uint:
  1656. case Basic_uintptr:
  1657. case Basic_u16le:
  1658. case Basic_u32le:
  1659. case Basic_u64le:
  1660. case Basic_u128le:
  1661. case Basic_u16be:
  1662. case Basic_u32be:
  1663. case Basic_u64be:
  1664. case Basic_u128be:
  1665. {
  1666. // return 0ull <= i && i <= umax;
  1667. int b = big_int_cmp(&i, &umax);
  1668. return !i.sign && (b <= 0);
  1669. }
  1670. case Basic_UntypedInteger:
  1671. return true;
  1672. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1673. }
  1674. } else if (is_type_float(type)) {
  1675. ExactValue v = exact_value_to_float(in_value);
  1676. if (v.kind != ExactValue_Float) {
  1677. return false;
  1678. }
  1679. if (out_value) *out_value = v;
  1680. switch (type->Basic.kind) {
  1681. case Basic_f16:
  1682. case Basic_f32:
  1683. case Basic_f64:
  1684. return true;
  1685. case Basic_f16le:
  1686. case Basic_f16be:
  1687. case Basic_f32le:
  1688. case Basic_f32be:
  1689. case Basic_f64le:
  1690. case Basic_f64be:
  1691. return true;
  1692. case Basic_UntypedFloat:
  1693. return true;
  1694. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1695. }
  1696. } else if (is_type_complex(type)) {
  1697. ExactValue v = exact_value_to_complex(in_value);
  1698. if (v.kind != ExactValue_Complex) {
  1699. return false;
  1700. }
  1701. switch (type->Basic.kind) {
  1702. case Basic_complex32:
  1703. case Basic_complex64:
  1704. case Basic_complex128: {
  1705. ExactValue real = exact_value_real(v);
  1706. ExactValue imag = exact_value_imag(v);
  1707. if (real.kind != ExactValue_Invalid &&
  1708. imag.kind != ExactValue_Invalid) {
  1709. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1710. return true;
  1711. }
  1712. break;
  1713. }
  1714. case Basic_UntypedComplex:
  1715. return true;
  1716. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1717. }
  1718. return false;
  1719. } else if (is_type_quaternion(type)) {
  1720. ExactValue v = exact_value_to_quaternion(in_value);
  1721. if (v.kind != ExactValue_Quaternion) {
  1722. return false;
  1723. }
  1724. switch (type->Basic.kind) {
  1725. case Basic_quaternion64:
  1726. case Basic_quaternion128:
  1727. case Basic_quaternion256: {
  1728. ExactValue real = exact_value_real(v);
  1729. ExactValue imag = exact_value_imag(v);
  1730. ExactValue jmag = exact_value_jmag(v);
  1731. ExactValue kmag = exact_value_kmag(v);
  1732. if (real.kind != ExactValue_Invalid &&
  1733. imag.kind != ExactValue_Invalid) {
  1734. 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));
  1735. return true;
  1736. }
  1737. break;
  1738. }
  1739. case Basic_UntypedComplex:
  1740. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1741. return true;
  1742. case Basic_UntypedQuaternion:
  1743. return true;
  1744. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1745. }
  1746. return false;
  1747. } else if (is_type_pointer(type)) {
  1748. if (in_value.kind == ExactValue_Pointer) {
  1749. return true;
  1750. }
  1751. if (in_value.kind == ExactValue_Integer) {
  1752. return false;
  1753. // return true;
  1754. }
  1755. if (in_value.kind == ExactValue_String) {
  1756. return false;
  1757. }
  1758. if (out_value) *out_value = in_value;
  1759. } else if (is_type_bit_set(type)) {
  1760. if (in_value.kind == ExactValue_Integer) {
  1761. return true;
  1762. }
  1763. }
  1764. return false;
  1765. }
  1766. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1767. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1768. gbString b = type_to_string(type);
  1769. i64 sz = type_size_of(type);
  1770. BigInt *bi = &o->value.value_integer;
  1771. if (is_type_unsigned(type)) {
  1772. if (big_int_is_neg(bi)) {
  1773. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1774. } else {
  1775. BigInt one = big_int_make_u64(1);
  1776. BigInt max_size = big_int_make_u64(1);
  1777. BigInt bits = big_int_make_i64(8*sz);
  1778. big_int_shl_eq(&max_size, &bits);
  1779. big_int_sub_eq(&max_size, &one);
  1780. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1781. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1782. }
  1783. } else {
  1784. BigInt zero = big_int_make_u64(0);
  1785. BigInt one = big_int_make_u64(1);
  1786. BigInt max_size = big_int_make_u64(1);
  1787. BigInt bits = big_int_make_i64(8*sz - 1);
  1788. big_int_shl_eq(&max_size, &bits);
  1789. if (big_int_is_neg(bi)) {
  1790. big_int_neg(&max_size, &max_size);
  1791. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1792. error_line("\tThe minimum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1793. } else {
  1794. big_int_sub_eq(&max_size, &one);
  1795. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1796. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1797. }
  1798. }
  1799. gb_string_free(b);
  1800. return true;
  1801. }
  1802. return false;
  1803. }
  1804. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1805. gbString a = expr_to_string(o->expr);
  1806. gbString b = type_to_string(type);
  1807. defer(
  1808. gb_string_free(b);
  1809. gb_string_free(a);
  1810. );
  1811. Type *src = base_type(o->type);
  1812. Type *dst = base_type(type);
  1813. if (is_type_array(src) && is_type_slice(dst)) {
  1814. Type *s = src->Array.elem;
  1815. Type *d = dst->Slice.elem;
  1816. if (are_types_identical(s, d)) {
  1817. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1818. }
  1819. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1820. Type *s = src->DynamicArray.elem;
  1821. Type *d = dst->Slice.elem;
  1822. if (are_types_identical(s, d)) {
  1823. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1824. }
  1825. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1826. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1827. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1828. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1829. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1830. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1831. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1832. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1833. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1834. return;
  1835. }
  1836. }
  1837. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1838. gbString a = expr_to_string(o->expr);
  1839. gbString b = type_to_string(type);
  1840. defer(
  1841. gb_string_free(b);
  1842. gb_string_free(a);
  1843. );
  1844. Type *src = base_type(o->type);
  1845. Type *dst = base_type(type);
  1846. if (is_type_array(src) && is_type_slice(dst)) {
  1847. Type *s = src->Array.elem;
  1848. Type *d = dst->Slice.elem;
  1849. if (are_types_identical(s, d)) {
  1850. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1851. }
  1852. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1853. if (is_type_uintptr(type)) {
  1854. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1855. } else {
  1856. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1857. i64 x = type_size_of(o->type);
  1858. i64 y = type_size_of(type);
  1859. if (x != y) {
  1860. 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);
  1861. }
  1862. }
  1863. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  1864. if (is_type_uintptr(o->type)) {
  1865. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  1866. } else {
  1867. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  1868. }
  1869. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1870. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1871. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1872. return;
  1873. }
  1874. }
  1875. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  1876. GB_ASSERT(o->mode == Addressing_Constant);
  1877. ExactValue out_value = o->value;
  1878. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  1879. o->value = out_value;
  1880. return true;
  1881. } else {
  1882. o->value = out_value;
  1883. gbString a = expr_to_string(o->expr);
  1884. gbString b = type_to_string(type);
  1885. gbString c = type_to_string(o->type);
  1886. gbString s = exact_value_to_string(o->value);
  1887. defer(
  1888. gb_string_free(s);
  1889. gb_string_free(c);
  1890. gb_string_free(b);
  1891. gb_string_free(a);
  1892. o->mode = Addressing_Invalid;
  1893. );
  1894. ERROR_BLOCK();
  1895. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1896. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1897. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  1898. } else {
  1899. if (are_types_identical(o->type, type)) {
  1900. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  1901. } else {
  1902. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  1903. }
  1904. check_assignment_error_suggestion(ctx, o, type);
  1905. }
  1906. } else {
  1907. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  1908. check_assignment_error_suggestion(ctx, o, type);
  1909. }
  1910. return false;
  1911. }
  1912. }
  1913. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1914. if (o->mode == Addressing_OptionalOk) {
  1915. Ast *expr = unselector_expr(o->expr);
  1916. if (expr->kind != Ast_TypeAssertion) {
  1917. return true;
  1918. }
  1919. ast_node(ta, TypeAssertion, expr);
  1920. TypeAndValue tv = ta->expr->tav;
  1921. if (is_type_pointer(tv.type)) {
  1922. return false;
  1923. }
  1924. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1925. return false;
  1926. }
  1927. if (is_type_any(tv.type)) {
  1928. return false;
  1929. }
  1930. return true;
  1931. }
  1932. if (o->mode == Addressing_MapIndex) {
  1933. return false;
  1934. }
  1935. Ast *expr = unparen_expr(o->expr);
  1936. if (expr->kind == Ast_CompoundLit) {
  1937. return false;
  1938. }
  1939. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  1940. }
  1941. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  1942. switch (op.kind) {
  1943. case Token_And: { // Pointer address
  1944. if (check_is_not_addressable(c, o)) {
  1945. if (ast_node_expect(node, Ast_UnaryExpr)) {
  1946. ast_node(ue, UnaryExpr, node);
  1947. gbString str = expr_to_string(ue->expr);
  1948. defer (gb_string_free(str));
  1949. Entity *e = entity_of_node(o->expr);
  1950. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  1951. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  1952. } else {
  1953. switch (o->mode) {
  1954. case Addressing_Constant:
  1955. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  1956. break;
  1957. case Addressing_SwizzleValue:
  1958. case Addressing_SwizzleVariable:
  1959. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  1960. break;
  1961. default:
  1962. {
  1963. begin_error_block();
  1964. defer (end_error_block());
  1965. error(op, "Cannot take the pointer address of '%s'", str);
  1966. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  1967. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  1968. }
  1969. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  1970. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  1971. }
  1972. }
  1973. break;
  1974. }
  1975. }
  1976. }
  1977. o->mode = Addressing_Invalid;
  1978. return;
  1979. }
  1980. if (o->mode == Addressing_SoaVariable) {
  1981. ast_node(ue, UnaryExpr, node);
  1982. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  1983. ast_node(ie, IndexExpr, ue->expr);
  1984. Type *soa_type = type_of_expr(ie->expr);
  1985. GB_ASSERT(is_type_soa_struct(soa_type));
  1986. o->type = alloc_type_soa_pointer(soa_type);
  1987. } else {
  1988. o->type = alloc_type_pointer(o->type);
  1989. }
  1990. } else {
  1991. o->type = alloc_type_pointer(o->type);
  1992. }
  1993. switch (o->mode) {
  1994. case Addressing_OptionalOk:
  1995. case Addressing_MapIndex:
  1996. o->mode = Addressing_OptionalOkPtr;
  1997. break;
  1998. default:
  1999. o->mode = Addressing_Value;
  2000. break;
  2001. }
  2002. return;
  2003. }
  2004. }
  2005. if (!check_unary_op(c, o, op)) {
  2006. o->mode = Addressing_Invalid;
  2007. return;
  2008. }
  2009. if (o->mode == Addressing_Constant) {
  2010. Type *type = base_type(o->type);
  2011. if (!is_type_constant_type(o->type)) {
  2012. gbString xt = type_to_string(o->type);
  2013. gbString err_str = expr_to_string(node);
  2014. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2015. gb_string_free(err_str);
  2016. gb_string_free(xt);
  2017. o->mode = Addressing_Invalid;
  2018. return;
  2019. }
  2020. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2021. gbString err_str = expr_to_string(node);
  2022. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2023. gb_string_free(err_str);
  2024. o->mode = Addressing_Invalid;
  2025. return;
  2026. }
  2027. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2028. gbString err_str = expr_to_string(node);
  2029. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2030. gb_string_free(err_str);
  2031. o->mode = Addressing_Invalid;
  2032. return;
  2033. }
  2034. i32 precision = 0;
  2035. if (is_type_typed(type)) {
  2036. precision = cast(i32)(8 * type_size_of(type));
  2037. }
  2038. bool is_unsigned = is_type_unsigned(type);
  2039. if (is_type_rune(type)) {
  2040. GB_ASSERT(!is_unsigned);
  2041. }
  2042. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2043. if (is_type_typed(type)) {
  2044. if (node != nullptr) {
  2045. o->expr = node;
  2046. }
  2047. check_is_expressible(c, o, type);
  2048. }
  2049. return;
  2050. }
  2051. o->mode = Addressing_Value;
  2052. }
  2053. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2054. if (t == nullptr) {
  2055. return;
  2056. }
  2057. t = base_type(t);
  2058. if (!is_type_comparable(t)) {
  2059. return;
  2060. }
  2061. switch (t->kind) {
  2062. case Type_Basic:
  2063. switch (t->Basic.kind) {
  2064. case Basic_complex32:
  2065. add_package_dependency(c, "runtime", "complex32_eq");
  2066. add_package_dependency(c, "runtime", "complex32_ne");
  2067. break;
  2068. case Basic_complex64:
  2069. add_package_dependency(c, "runtime", "complex64_eq");
  2070. add_package_dependency(c, "runtime", "complex64_ne");
  2071. break;
  2072. case Basic_complex128:
  2073. add_package_dependency(c, "runtime", "complex128_eq");
  2074. add_package_dependency(c, "runtime", "complex128_ne");
  2075. break;
  2076. case Basic_quaternion64:
  2077. add_package_dependency(c, "runtime", "quaternion64_eq");
  2078. add_package_dependency(c, "runtime", "quaternion64_ne");
  2079. break;
  2080. case Basic_quaternion128:
  2081. add_package_dependency(c, "runtime", "quaternion128_eq");
  2082. add_package_dependency(c, "runtime", "quaternion128_ne");
  2083. break;
  2084. case Basic_quaternion256:
  2085. add_package_dependency(c, "runtime", "quaternion256_eq");
  2086. add_package_dependency(c, "runtime", "quaternion256_ne");
  2087. break;
  2088. case Basic_cstring:
  2089. add_package_dependency(c, "runtime", "cstring_to_string");
  2090. /*fallthrough*/
  2091. case Basic_string:
  2092. add_package_dependency(c, "runtime", "string_eq");
  2093. add_package_dependency(c, "runtime", "string_ne");
  2094. break;
  2095. }
  2096. break;
  2097. case Type_Struct:
  2098. for (Entity *field : t->Struct.fields) {
  2099. add_comparison_procedures_for_fields(c, field->type);
  2100. }
  2101. break;
  2102. }
  2103. }
  2104. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2105. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2106. bool comp = are_types_identical(x->type, y->type);
  2107. switch (op) {
  2108. case Token_CmpEq: /* comp = comp; */ break;
  2109. case Token_NotEq: comp = !comp; break;
  2110. }
  2111. x->mode = Addressing_Constant;
  2112. x->type = t_untyped_bool;
  2113. x->value = exact_value_bool(comp);
  2114. return;
  2115. }
  2116. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2117. add_type_info_type(c, x->type);
  2118. add_type_info_type(c, y->type);
  2119. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2120. x->mode = Addressing_Value;
  2121. x->type = t_untyped_bool;
  2122. return;
  2123. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2124. add_type_info_type(c, x->type);
  2125. add_type_info_type(c, y->type);
  2126. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2127. x->mode = Addressing_Value;
  2128. x->type = t_untyped_bool;
  2129. return;
  2130. }
  2131. TEMPORARY_ALLOCATOR_GUARD();
  2132. gbString err_str = nullptr;
  2133. if (check_is_assignable_to(c, x, y->type) ||
  2134. check_is_assignable_to(c, y, x->type)) {
  2135. Type *err_type = x->type;
  2136. bool defined = false;
  2137. switch (op) {
  2138. case Token_CmpEq:
  2139. case Token_NotEq:
  2140. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2141. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2142. (is_operand_nil(*y) && type_has_nil(x->type));
  2143. break;
  2144. case Token_Lt:
  2145. case Token_Gt:
  2146. case Token_LtEq:
  2147. case Token_GtEq:
  2148. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2149. defined = true;
  2150. } else {
  2151. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2152. }
  2153. break;
  2154. }
  2155. if (!defined) {
  2156. gbString xs = type_to_string(x->type, temporary_allocator());
  2157. gbString ys = type_to_string(y->type, temporary_allocator());
  2158. err_str = gb_string_make(temporary_allocator(),
  2159. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2160. );
  2161. } else {
  2162. Type *comparison_type = x->type;
  2163. if (x->type == err_type && is_operand_nil(*x)) {
  2164. comparison_type = y->type;
  2165. }
  2166. add_comparison_procedures_for_fields(c, comparison_type);
  2167. }
  2168. } else {
  2169. gbString xt, yt;
  2170. if (x->mode == Addressing_ProcGroup) {
  2171. xt = gb_string_make(temporary_allocator(), "procedure group");
  2172. } else {
  2173. xt = type_to_string(x->type);
  2174. }
  2175. if (y->mode == Addressing_ProcGroup) {
  2176. yt = gb_string_make(temporary_allocator(), "procedure group");
  2177. } else {
  2178. yt = type_to_string(y->type);
  2179. }
  2180. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2181. }
  2182. if (err_str != nullptr) {
  2183. error(node, "Cannot compare expression, %s", err_str);
  2184. x->type = t_untyped_bool;
  2185. } else {
  2186. if (x->mode == Addressing_Constant &&
  2187. y->mode == Addressing_Constant) {
  2188. if (is_type_constant_type(x->type)) {
  2189. if (is_type_bit_set(x->type)) {
  2190. switch (op) {
  2191. case Token_CmpEq:
  2192. case Token_NotEq:
  2193. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2194. break;
  2195. case Token_Lt:
  2196. case Token_LtEq:
  2197. {
  2198. ExactValue lhs = x->value;
  2199. ExactValue rhs = y->value;
  2200. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2201. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2202. if (op == Token_Lt) {
  2203. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2204. }
  2205. x->value = res;
  2206. break;
  2207. }
  2208. case Token_Gt:
  2209. case Token_GtEq:
  2210. {
  2211. ExactValue lhs = x->value;
  2212. ExactValue rhs = y->value;
  2213. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2214. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2215. if (op == Token_Gt) {
  2216. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2217. }
  2218. x->value = res;
  2219. break;
  2220. }
  2221. }
  2222. } else {
  2223. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2224. }
  2225. } else {
  2226. x->mode = Addressing_Value;
  2227. }
  2228. } else {
  2229. x->mode = Addressing_Value;
  2230. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2231. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2232. i64 size = 0;
  2233. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2234. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2235. if (is_type_string(x->type) || is_type_string(y->type)) {
  2236. switch (op) {
  2237. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2238. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2239. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2240. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2241. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2242. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2243. }
  2244. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2245. switch (op) {
  2246. case Token_CmpEq:
  2247. switch (8*size) {
  2248. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2249. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2250. }
  2251. break;
  2252. case Token_NotEq:
  2253. switch (8*size) {
  2254. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2255. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2256. }
  2257. break;
  2258. }
  2259. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2260. switch (op) {
  2261. case Token_CmpEq:
  2262. switch (8*size) {
  2263. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2264. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2265. }
  2266. break;
  2267. case Token_NotEq:
  2268. switch (8*size) {
  2269. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2270. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2271. }
  2272. break;
  2273. }
  2274. }
  2275. }
  2276. x->type = t_untyped_bool;
  2277. }
  2278. }
  2279. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2280. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2281. ast_node(be, BinaryExpr, node);
  2282. ExactValue x_val = {};
  2283. if (x->mode == Addressing_Constant) {
  2284. x_val = exact_value_to_integer(x->value);
  2285. }
  2286. bool x_is_untyped = is_type_untyped(x->type);
  2287. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2288. gbString err_str = expr_to_string(x->expr);
  2289. error(node, "Shifted operand '%s' must be an integer", err_str);
  2290. gb_string_free(err_str);
  2291. x->mode = Addressing_Invalid;
  2292. return;
  2293. }
  2294. if (is_type_unsigned(y->type)) {
  2295. } else if (is_type_untyped(y->type)) {
  2296. convert_to_typed(c, y, t_untyped_integer);
  2297. if (y->mode == Addressing_Invalid) {
  2298. x->mode = Addressing_Invalid;
  2299. return;
  2300. }
  2301. } else {
  2302. gbString err_str = expr_to_string(y->expr);
  2303. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2304. gb_string_free(err_str);
  2305. x->mode = Addressing_Invalid;
  2306. return;
  2307. }
  2308. if (x->mode == Addressing_Constant) {
  2309. if (y->mode == Addressing_Constant) {
  2310. ExactValue y_val = exact_value_to_integer(y->value);
  2311. if (y_val.kind != ExactValue_Integer) {
  2312. gbString err_str = expr_to_string(y->expr);
  2313. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2314. gb_string_free(err_str);
  2315. x->mode = Addressing_Invalid;
  2316. return;
  2317. }
  2318. BigInt max_shift = {};
  2319. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2320. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2321. gbString err_str = expr_to_string(y->expr);
  2322. error(node, "Shift amount too large: '%s'", err_str);
  2323. gb_string_free(err_str);
  2324. x->mode = Addressing_Invalid;
  2325. return;
  2326. }
  2327. if (!is_type_integer(x->type)) {
  2328. // NOTE(bill): It could be an untyped float but still representable
  2329. // as an integer
  2330. x->type = t_untyped_integer;
  2331. }
  2332. x->expr = node;
  2333. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2334. if (is_type_typed(x->type)) {
  2335. check_is_expressible(c, x, x->type);
  2336. }
  2337. return;
  2338. }
  2339. TokenPos pos = ast_token(x->expr).pos;
  2340. if (x_is_untyped) {
  2341. if (x->expr != nullptr) {
  2342. x->expr->tav.is_lhs = true;
  2343. }
  2344. x->mode = Addressing_Value;
  2345. if (type_hint) {
  2346. if (is_type_integer(type_hint)) {
  2347. x->type = type_hint;
  2348. } else {
  2349. gbString x_str = expr_to_string(x->expr);
  2350. gbString to_type = type_to_string(type_hint);
  2351. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2352. gb_string_free(x_str);
  2353. gb_string_free(to_type);
  2354. x->mode = Addressing_Invalid;
  2355. }
  2356. }
  2357. // x->value = x_val;
  2358. return;
  2359. }
  2360. }
  2361. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2362. gbString err_str = expr_to_string(y->expr);
  2363. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2364. gb_string_free(err_str);
  2365. }
  2366. // TODO(bill): Should we support shifts for fixed arrays and #simd vectors?
  2367. if (!is_type_integer(x->type)) {
  2368. gbString err_str = expr_to_string(x->expr);
  2369. error(node, "Shift operand '%s' must be an integer", err_str);
  2370. gb_string_free(err_str);
  2371. x->mode = Addressing_Invalid;
  2372. return;
  2373. }
  2374. if (is_type_untyped(y->type)) {
  2375. convert_to_typed(c, y, t_uint);
  2376. }
  2377. x->mode = Addressing_Value;
  2378. }
  2379. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2380. if (check_is_assignable_to(c, operand, y)) {
  2381. return true;
  2382. }
  2383. bool is_constant = operand->mode == Addressing_Constant;
  2384. Type *x = operand->type;
  2385. Type *src = core_type(x);
  2386. Type *dst = core_type(y);
  2387. if (are_types_identical(src, dst)) {
  2388. return true;
  2389. }
  2390. // if (is_type_tuple(src)) {
  2391. // Ast *expr = unparen_expr(operand->expr);
  2392. // if (expr && expr->kind == Ast_CallExpr) {
  2393. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2394. // ast_node(ce, CallExpr, expr);
  2395. // Type *pt = base_type(type_of_expr(ce->proc));
  2396. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2397. // if (pt->Proc.result_count > 0) {
  2398. // Operand op = *operand;
  2399. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2400. // bool ok = check_is_castable_to(c, &op, y);
  2401. // if (ok) {
  2402. // ce->optional_ok_one = true;
  2403. // }
  2404. // return ok;
  2405. // }
  2406. // }
  2407. // }
  2408. // }
  2409. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2410. if (is_type_u8_array(dst)) {
  2411. String s = operand->value.value_string;
  2412. return s.len == dst->Array.count;
  2413. }
  2414. if (is_type_rune_array(dst)) {
  2415. String s = operand->value.value_string;
  2416. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2417. }
  2418. }
  2419. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2420. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2421. return dst->Array.count == src->Array.count;
  2422. }
  2423. }
  2424. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2425. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2426. }
  2427. // Cast between booleans and integers
  2428. if (is_type_boolean(src) || is_type_integer(src)) {
  2429. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2430. return true;
  2431. }
  2432. }
  2433. // Cast between numbers
  2434. if (is_type_integer(src) || is_type_float(src)) {
  2435. if (is_type_integer(dst) || is_type_float(dst)) {
  2436. return true;
  2437. }
  2438. }
  2439. if (is_type_integer(src) && is_type_rune(dst)) {
  2440. return true;
  2441. }
  2442. if (is_type_rune(src) && is_type_integer(dst)) {
  2443. return true;
  2444. }
  2445. if (is_type_complex(src) && is_type_complex(dst)) {
  2446. return true;
  2447. }
  2448. if (is_type_float(src) && is_type_complex(dst)) {
  2449. return true;
  2450. }
  2451. if (is_type_float(src) && is_type_quaternion(dst)) {
  2452. return true;
  2453. }
  2454. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2455. return true;
  2456. }
  2457. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2458. return true;
  2459. }
  2460. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2461. GB_ASSERT(src->kind == Type_Matrix);
  2462. GB_ASSERT(dst->kind == Type_Matrix);
  2463. Operand op = *operand;
  2464. op.type = src->Matrix.elem;
  2465. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2466. return false;
  2467. }
  2468. if (src->Matrix.row_count != src->Matrix.column_count) {
  2469. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2470. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2471. return src_count == dst_count;
  2472. }
  2473. return is_matrix_square(dst) && is_matrix_square(src);
  2474. }
  2475. // Cast between pointers
  2476. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2477. return true;
  2478. }
  2479. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2480. return true;
  2481. }
  2482. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2483. return true;
  2484. }
  2485. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2486. return true;
  2487. }
  2488. // uintptr <-> pointer
  2489. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2490. return true;
  2491. }
  2492. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2493. return true;
  2494. }
  2495. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2496. return true;
  2497. }
  2498. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2499. return true;
  2500. }
  2501. // []byte/[]u8 <-> string (not cstring)
  2502. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2503. return true;
  2504. }
  2505. // cstring -> string
  2506. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2507. if (operand->mode != Addressing_Constant) {
  2508. add_package_dependency(c, "runtime", "cstring_to_string");
  2509. }
  2510. return true;
  2511. }
  2512. // cstring -> ^u8
  2513. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2514. return !is_constant;
  2515. }
  2516. // cstring -> [^]u8
  2517. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2518. return !is_constant;
  2519. }
  2520. // cstring -> rawptr
  2521. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2522. return !is_constant;
  2523. }
  2524. // ^u8 -> cstring
  2525. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2526. return !is_constant;
  2527. }
  2528. // [^]u8 -> cstring
  2529. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2530. return !is_constant;
  2531. }
  2532. // rawptr -> cstring
  2533. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2534. return !is_constant;
  2535. }
  2536. // proc <-> proc
  2537. if (is_type_proc(src) && is_type_proc(dst)) {
  2538. return true;
  2539. }
  2540. // proc -> rawptr
  2541. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2542. return true;
  2543. }
  2544. // rawptr -> proc
  2545. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2546. return true;
  2547. }
  2548. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2549. if (src->SimdVector.count != dst->SimdVector.count) {
  2550. return false;
  2551. }
  2552. Type *elem_src = base_array_type(src);
  2553. Type *elem_dst = base_array_type(dst);
  2554. Operand x = {};
  2555. x.type = elem_src;
  2556. x.mode = Addressing_Value;
  2557. return check_is_castable_to(c, &x, elem_dst);
  2558. }
  2559. if (is_type_simd_vector(dst)) {
  2560. Type *elem = base_array_type(dst);
  2561. if (check_is_castable_to(c, operand, elem)) {
  2562. return true;
  2563. }
  2564. }
  2565. return false;
  2566. }
  2567. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2568. bool is_const_expr = x->mode == Addressing_Constant;
  2569. Type *bt = base_type(type);
  2570. if (is_const_expr && is_type_constant_type(bt)) {
  2571. if (core_type(bt)->kind == Type_Basic) {
  2572. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2573. return true;
  2574. } else if (check_is_castable_to(c, x, type)) {
  2575. if (is_type_pointer(type)) {
  2576. return true;
  2577. }
  2578. }
  2579. } else if (check_is_castable_to(c, x, type)) {
  2580. x->value = {};
  2581. x->mode = Addressing_Value;
  2582. return true;
  2583. }
  2584. } else if (check_is_castable_to(c, x, type)) {
  2585. if (x->mode != Addressing_Constant) {
  2586. x->mode = Addressing_Value;
  2587. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2588. x->mode = Addressing_Value;
  2589. } else if (is_type_union(type)) {
  2590. x->mode = Addressing_Value;
  2591. }
  2592. if (x->mode == Addressing_Value) {
  2593. x->value = {};
  2594. }
  2595. return true;
  2596. }
  2597. return false;
  2598. }
  2599. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2600. if (!is_operand_value(*x)) {
  2601. error(x->expr, "Only values can be casted");
  2602. x->mode = Addressing_Invalid;
  2603. return;
  2604. }
  2605. bool is_const_expr = x->mode == Addressing_Constant;
  2606. bool can_convert = check_cast_internal(c, x, type);
  2607. if (!can_convert) {
  2608. TEMPORARY_ALLOCATOR_GUARD();
  2609. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2610. gbString to_type = type_to_string(type, temporary_allocator());
  2611. gbString from_type = type_to_string(x->type, temporary_allocator());
  2612. x->mode = Addressing_Invalid;
  2613. begin_error_block();
  2614. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2615. if (is_const_expr) {
  2616. gbString val_str = exact_value_to_string(x->value);
  2617. if (is_type_float(x->type) && is_type_integer(type)) {
  2618. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2619. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2620. x->mode = Addressing_Constant;
  2621. x->type = type;
  2622. } else {
  2623. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2624. if (is_type_numeric(type)) {
  2625. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2626. x->mode = Addressing_Constant;
  2627. x->type = type;
  2628. }
  2629. }
  2630. gb_string_free(val_str);
  2631. }
  2632. check_cast_error_suggestion(c, x, type);
  2633. end_error_block();
  2634. return;
  2635. }
  2636. if (is_type_untyped(x->type)) {
  2637. Type *final_type = type;
  2638. if (is_const_expr && !is_type_constant_type(type)) {
  2639. final_type = default_type(x->type);
  2640. }
  2641. update_untyped_expr_type(c, x->expr, final_type, true);
  2642. }
  2643. if (build_context.vet_extra) {
  2644. if (are_types_identical(x->type, type)) {
  2645. gbString str = type_to_string(type);
  2646. warning(x->expr, "Unneeded cast to the same type '%s'", str);
  2647. gb_string_free(str);
  2648. }
  2649. }
  2650. x->type = type;
  2651. }
  2652. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2653. if (!is_operand_value(*o)) {
  2654. error(o->expr, "'transmute' can only be applied to values");
  2655. o->mode = Addressing_Invalid;
  2656. return false;
  2657. }
  2658. // if (o->mode == Addressing_Constant) {
  2659. // gbString expr_str = expr_to_string(o->expr);
  2660. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2661. // gb_string_free(expr_str);
  2662. // o->mode = Addressing_Invalid;
  2663. // o->expr = node;
  2664. // return false;
  2665. // }
  2666. Type *src_t = o->type;
  2667. Type *dst_t = t;
  2668. Type *src_bt = base_type(src_t);
  2669. Type *dst_bt = base_type(dst_t);
  2670. if (is_type_untyped(src_t)) {
  2671. gbString expr_str = expr_to_string(o->expr);
  2672. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2673. gb_string_free(expr_str);
  2674. o->mode = Addressing_Invalid;
  2675. o->expr = node;
  2676. return false;
  2677. }
  2678. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2679. GB_ASSERT(global_error_collector.count != 0);
  2680. o->mode = Addressing_Invalid;
  2681. o->expr = node;
  2682. return false;
  2683. }
  2684. if (src_bt == nullptr || src_bt == t_invalid) {
  2685. // NOTE(bill): this should be an error
  2686. GB_ASSERT(global_error_collector.count != 0);
  2687. o->mode = Addressing_Value;
  2688. o->expr = node;
  2689. o->type = dst_t;
  2690. return true;
  2691. }
  2692. i64 srcz = type_size_of(src_t);
  2693. i64 dstz = type_size_of(dst_t);
  2694. if (srcz != dstz) {
  2695. gbString expr_str = expr_to_string(o->expr);
  2696. gbString type_str = type_to_string(dst_t);
  2697. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2698. gb_string_free(type_str);
  2699. gb_string_free(expr_str);
  2700. o->mode = Addressing_Invalid;
  2701. o->expr = node;
  2702. return false;
  2703. }
  2704. if (build_context.vet_extra) {
  2705. if (are_types_identical(o->type, dst_t)) {
  2706. gbString str = type_to_string(dst_t);
  2707. warning(o->expr, "Unneeded transmute to the same type '%s'", str);
  2708. gb_string_free(str);
  2709. }
  2710. }
  2711. o->expr = node;
  2712. o->type = dst_t;
  2713. if (o->mode == Addressing_Constant) {
  2714. if (are_types_identical(src_bt, dst_bt)) {
  2715. return true;
  2716. }
  2717. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2718. if (types_have_same_internal_endian(src_t, dst_t)) {
  2719. ExactValue src_v = exact_value_to_integer(o->value);
  2720. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2721. BigInt v = src_v.value_integer;
  2722. BigInt smax = {};
  2723. BigInt umax = {};
  2724. big_int_from_u64(&smax, 0);
  2725. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2726. big_int_from_u64(&umax, 1);
  2727. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2728. big_int_shl_eq(&umax, &sz_in_bits);
  2729. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2730. if (big_int_cmp(&v, &smax) >= 0) {
  2731. big_int_sub_eq(&v, &umax);
  2732. }
  2733. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2734. if (big_int_is_neg(&v)) {
  2735. big_int_add_eq(&v, &umax);
  2736. }
  2737. }
  2738. o->value.kind = ExactValue_Integer;
  2739. o->value.value_integer = v;
  2740. return true;
  2741. }
  2742. }
  2743. }
  2744. o->mode = Addressing_Value;
  2745. o->value = {};
  2746. return true;
  2747. }
  2748. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2749. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2750. if (check_is_assignable_to(c, y, x->type)) {
  2751. if (check_binary_op(c, x, op)) {
  2752. return true;
  2753. }
  2754. }
  2755. }
  2756. return false;
  2757. }
  2758. gb_internal bool is_ise_expr(Ast *node) {
  2759. node = unparen_expr(node);
  2760. return node->kind == Ast_ImplicitSelectorExpr;
  2761. }
  2762. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2763. if (use_lhs_as_type_hint) { // RHS in this case
  2764. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2765. }
  2766. return false;
  2767. }
  2768. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2769. Type *xt = base_type(matrix);
  2770. if (type_hint != nullptr) {
  2771. Type *th = base_type(type_hint);
  2772. if (are_types_identical(th, xt)) {
  2773. return type_hint;
  2774. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2775. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2776. // ignore
  2777. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2778. return type_hint;
  2779. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2780. return type_hint;
  2781. }
  2782. }
  2783. }
  2784. return matrix;
  2785. }
  2786. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2787. if (!check_binary_op(c, x, op)) {
  2788. x->mode = Addressing_Invalid;
  2789. return;
  2790. }
  2791. Type *xt = base_type(x->type);
  2792. Type *yt = base_type(y->type);
  2793. if (is_type_matrix(x->type)) {
  2794. GB_ASSERT(xt->kind == Type_Matrix);
  2795. if (op.kind == Token_Mul) {
  2796. if (yt->kind == Type_Matrix) {
  2797. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2798. goto matrix_error;
  2799. }
  2800. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2801. goto matrix_error;
  2802. }
  2803. x->mode = Addressing_Value;
  2804. if (are_types_identical(xt, yt)) {
  2805. if (!is_type_named(x->type) && is_type_named(y->type)) {
  2806. // prefer the named type
  2807. x->type = y->type;
  2808. }
  2809. } else {
  2810. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2811. }
  2812. goto matrix_success;
  2813. } else if (yt->kind == Type_Array) {
  2814. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2815. goto matrix_error;
  2816. }
  2817. if (xt->Matrix.column_count != yt->Array.count) {
  2818. goto matrix_error;
  2819. }
  2820. // Treat arrays as column vectors
  2821. x->mode = Addressing_Value;
  2822. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2823. x->type = y->type;
  2824. } else {
  2825. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2826. }
  2827. goto matrix_success;
  2828. }
  2829. }
  2830. if (!are_types_identical(xt, yt)) {
  2831. goto matrix_error;
  2832. }
  2833. x->mode = Addressing_Value;
  2834. x->type = xt;
  2835. goto matrix_success;
  2836. } else {
  2837. GB_ASSERT(!is_type_matrix(xt));
  2838. GB_ASSERT(is_type_matrix(yt));
  2839. if (op.kind == Token_Mul) {
  2840. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2841. if (xt->kind == Type_Array) {
  2842. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2843. goto matrix_error;
  2844. }
  2845. if (xt->Array.count != yt->Matrix.row_count) {
  2846. goto matrix_error;
  2847. }
  2848. // Treat arrays as row vectors
  2849. x->mode = Addressing_Value;
  2850. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2851. x->type = x->type;
  2852. } else {
  2853. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2854. }
  2855. goto matrix_success;
  2856. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  2857. x->type = check_matrix_type_hint(y->type, type_hint);
  2858. return;
  2859. }
  2860. }
  2861. if (!are_types_identical(xt, yt)) {
  2862. goto matrix_error;
  2863. }
  2864. x->mode = Addressing_Value;
  2865. x->type = xt;
  2866. goto matrix_success;
  2867. }
  2868. matrix_success:
  2869. x->type = check_matrix_type_hint(x->type, type_hint);
  2870. return;
  2871. matrix_error:
  2872. gbString xts = type_to_string(x->type);
  2873. gbString yts = type_to_string(y->type);
  2874. gbString expr_str = expr_to_string(x->expr);
  2875. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2876. gb_string_free(expr_str);
  2877. gb_string_free(yts);
  2878. gb_string_free(xts);
  2879. x->type = t_invalid;
  2880. x->mode = Addressing_Invalid;
  2881. return;
  2882. }
  2883. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2884. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2885. Operand y_ = {}, *y = &y_;
  2886. ast_node(be, BinaryExpr, node);
  2887. defer({
  2888. node->viral_state_flags |= be->left->viral_state_flags;
  2889. node->viral_state_flags |= be->right->viral_state_flags;
  2890. });
  2891. Token op = be->op;
  2892. switch (op.kind) {
  2893. case Token_CmpEq:
  2894. case Token_NotEq: {
  2895. // NOTE(bill): Allow comparisons between types
  2896. if (is_ise_expr(be->left)) {
  2897. // Evalute the right before the left for an '.X' expression
  2898. check_expr_or_type(c, y, be->right, type_hint);
  2899. check_expr_or_type(c, x, be->left, y->type);
  2900. } else {
  2901. check_expr_or_type(c, x, be->left, type_hint);
  2902. check_expr_or_type(c, y, be->right, x->type);
  2903. }
  2904. bool xt = x->mode == Addressing_Type;
  2905. bool yt = y->mode == Addressing_Type;
  2906. // If only one is a type, this is an error
  2907. if (xt ^ yt) {
  2908. GB_ASSERT(xt != yt);
  2909. if (xt) {
  2910. if (!is_type_typeid(y->type)) {
  2911. error_operand_not_expression(x);
  2912. }
  2913. }
  2914. if (yt) {
  2915. if (!is_type_typeid(x->type)) {
  2916. error_operand_not_expression(y);
  2917. }
  2918. }
  2919. }
  2920. break;
  2921. }
  2922. case Token_in:
  2923. case Token_not_in:
  2924. {
  2925. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  2926. check_expr(c, y, be->right);
  2927. Type *rhs_type = type_deref(y->type);
  2928. if (is_type_bit_set(rhs_type)) {
  2929. Type *elem = base_type(rhs_type)->BitSet.elem;
  2930. check_expr_with_type_hint(c, x, be->left, elem);
  2931. } else if (is_type_map(rhs_type)) {
  2932. Type *key = base_type(rhs_type)->Map.key;
  2933. check_expr_with_type_hint(c, x, be->left, key);
  2934. } else {
  2935. check_expr(c, x, be->left);
  2936. }
  2937. if (x->mode == Addressing_Invalid) {
  2938. return;
  2939. }
  2940. if (y->mode == Addressing_Invalid) {
  2941. x->mode = Addressing_Invalid;
  2942. x->expr = y->expr;
  2943. return;
  2944. }
  2945. if (is_type_map(rhs_type)) {
  2946. Type *yt = base_type(rhs_type);
  2947. if (op.kind == Token_in) {
  2948. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  2949. } else {
  2950. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  2951. }
  2952. add_map_get_dependencies(c);
  2953. } else if (is_type_bit_set(rhs_type)) {
  2954. Type *yt = base_type(rhs_type);
  2955. if (op.kind == Token_in) {
  2956. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  2957. } else {
  2958. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  2959. }
  2960. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  2961. ExactValue k = exact_value_to_integer(x->value);
  2962. ExactValue v = exact_value_to_integer(y->value);
  2963. GB_ASSERT(k.kind == ExactValue_Integer);
  2964. GB_ASSERT(v.kind == ExactValue_Integer);
  2965. i64 key = big_int_to_i64(&k.value_integer);
  2966. i64 lower = yt->BitSet.lower;
  2967. i64 upper = yt->BitSet.upper;
  2968. if (lower <= key && key <= upper) {
  2969. i64 bit = 1ll<<key;
  2970. i64 bits = big_int_to_i64(&v.value_integer);
  2971. x->mode = Addressing_Constant;
  2972. x->type = t_untyped_bool;
  2973. if (op.kind == Token_in) {
  2974. x->value = exact_value_bool((bit & bits) != 0);
  2975. } else {
  2976. x->value = exact_value_bool((bit & bits) == 0);
  2977. }
  2978. x->expr = node;
  2979. return;
  2980. } else {
  2981. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  2982. x->mode = Addressing_Invalid;
  2983. }
  2984. }
  2985. } else {
  2986. gbString t = type_to_string(y->type);
  2987. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  2988. gb_string_free(t);
  2989. x->expr = node;
  2990. x->mode = Addressing_Invalid;
  2991. return;
  2992. }
  2993. if (x->mode != Addressing_Invalid) {
  2994. x->mode = Addressing_Value;
  2995. x->type = t_untyped_bool;
  2996. }
  2997. x->expr = node;
  2998. return;
  2999. }
  3000. default:
  3001. if (is_ise_expr(be->left)) {
  3002. // Evalute the right before the left for an '.X' expression
  3003. check_expr_or_type(c, y, be->right, type_hint);
  3004. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3005. check_expr_or_type(c, x, be->left, y->type);
  3006. } else {
  3007. check_expr_with_type_hint(c, x, be->left, type_hint);
  3008. }
  3009. } else {
  3010. check_expr_with_type_hint(c, x, be->left, type_hint);
  3011. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3012. check_expr_with_type_hint(c, y, be->right, x->type);
  3013. } else {
  3014. check_expr_with_type_hint(c, y, be->right, type_hint);
  3015. }
  3016. }
  3017. break;
  3018. }
  3019. if (x->mode == Addressing_Invalid) {
  3020. return;
  3021. }
  3022. if (y->mode == Addressing_Invalid) {
  3023. x->mode = Addressing_Invalid;
  3024. x->expr = y->expr;
  3025. return;
  3026. }
  3027. if (x->mode == Addressing_Builtin) {
  3028. x->mode = Addressing_Invalid;
  3029. error(x->expr, "built-in expression in binary expression");
  3030. return;
  3031. }
  3032. if (y->mode == Addressing_Builtin) {
  3033. x->mode = Addressing_Invalid;
  3034. error(y->expr, "built-in expression in binary expression");
  3035. return;
  3036. }
  3037. if (x->mode == Addressing_ProcGroup) {
  3038. x->mode = Addressing_Invalid;
  3039. if (x->proc_group != nullptr) {
  3040. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3041. } else {
  3042. error(x->expr, "procedure group used in binary expression");
  3043. }
  3044. return;
  3045. }
  3046. if (y->mode == Addressing_ProcGroup) {
  3047. x->mode = Addressing_Invalid;
  3048. if (x->proc_group != nullptr) {
  3049. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3050. } else {
  3051. error(y->expr, "procedure group used in binary expression");
  3052. }
  3053. return;
  3054. }
  3055. if (token_is_shift(op.kind)) {
  3056. check_shift(c, x, y, node, type_hint);
  3057. return;
  3058. }
  3059. convert_to_typed(c, x, y->type);
  3060. if (x->mode == Addressing_Invalid) {
  3061. return;
  3062. }
  3063. convert_to_typed(c, y, x->type);
  3064. if (y->mode == Addressing_Invalid) {
  3065. x->mode = Addressing_Invalid;
  3066. return;
  3067. }
  3068. if (token_is_comparison(op.kind)) {
  3069. check_comparison(c, node, x, y, op.kind);
  3070. return;
  3071. }
  3072. if (check_binary_array_expr(c, op, x, y)) {
  3073. x->mode = Addressing_Value;
  3074. x->type = x->type;
  3075. return;
  3076. }
  3077. if (check_binary_array_expr(c, op, y, x)) {
  3078. x->mode = Addressing_Value;
  3079. x->type = y->type;
  3080. return;
  3081. }
  3082. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3083. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3084. x->expr = node;
  3085. return;
  3086. }
  3087. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3088. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3089. // NOTE(bill, 2022-06-26)
  3090. // Allow any boolean types within `&&` and `||`
  3091. // This is an exception to all other binary expressions since the result
  3092. // of a comparison will always be an untyped boolean, and allowing
  3093. // any boolean between these two simplifies a lot of expressions
  3094. } else if (!are_types_identical(x->type, y->type)) {
  3095. if (x->type != t_invalid &&
  3096. y->type != t_invalid) {
  3097. gbString xt = type_to_string(x->type);
  3098. gbString yt = type_to_string(y->type);
  3099. gbString expr_str = expr_to_string(node);
  3100. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3101. gb_string_free(expr_str);
  3102. gb_string_free(yt);
  3103. gb_string_free(xt);
  3104. }
  3105. x->mode = Addressing_Invalid;
  3106. return;
  3107. }
  3108. if (!check_binary_op(c, x, op)) {
  3109. x->mode = Addressing_Invalid;
  3110. return;
  3111. }
  3112. switch (op.kind) {
  3113. case Token_Quo:
  3114. case Token_Mod:
  3115. case Token_ModMod:
  3116. case Token_QuoEq:
  3117. case Token_ModEq:
  3118. case Token_ModModEq:
  3119. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3120. y->mode == Addressing_Constant) {
  3121. bool fail = false;
  3122. switch (y->value.kind) {
  3123. case ExactValue_Integer:
  3124. if (big_int_is_zero(&y->value.value_integer)) {
  3125. fail = true;
  3126. }
  3127. break;
  3128. case ExactValue_Float:
  3129. if (y->value.value_float == 0.0) {
  3130. fail = true;
  3131. }
  3132. break;
  3133. }
  3134. if (fail) {
  3135. error(y->expr, "Division by zero not allowed");
  3136. x->mode = Addressing_Invalid;
  3137. return;
  3138. }
  3139. }
  3140. break;
  3141. case Token_CmpAnd:
  3142. case Token_CmpOr:
  3143. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3144. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3145. }
  3146. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3147. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3148. }
  3149. break;
  3150. }
  3151. if (x->mode == Addressing_Constant &&
  3152. y->mode == Addressing_Constant) {
  3153. ExactValue a = x->value;
  3154. ExactValue b = y->value;
  3155. if (!is_type_constant_type(x->type)) {
  3156. #if 0
  3157. gbString xt = type_to_string(x->type);
  3158. gbString err_str = expr_to_string(node);
  3159. error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
  3160. gb_string_free(err_str);
  3161. gb_string_free(xt);
  3162. x->mode = Addressing_Invalid;
  3163. #else
  3164. // NOTE(bill, 2021-04-21): The above is literally a useless error message.
  3165. // Why did I add it in the first place?!
  3166. x->mode = Addressing_Value;
  3167. #endif
  3168. return;
  3169. }
  3170. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3171. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3172. }
  3173. if (is_type_bit_set(x->type)) {
  3174. switch (op.kind) {
  3175. case Token_Add: op.kind = Token_Or; break;
  3176. case Token_Sub: op.kind = Token_AndNot; break;
  3177. }
  3178. }
  3179. x->value = exact_binary_operator_value(op.kind, a, b);
  3180. if (is_type_typed(x->type)) {
  3181. if (node != nullptr) {
  3182. x->expr = node;
  3183. }
  3184. check_is_expressible(c, x, x->type);
  3185. }
  3186. return;
  3187. } else if (is_type_string(x->type)) {
  3188. error(node, "String concatenation is only allowed with constant strings");
  3189. x->mode = Addressing_Invalid;
  3190. return;
  3191. }
  3192. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3193. Type *bt = base_type(x->type);
  3194. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3195. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3196. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3197. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3198. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3199. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3200. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3201. }
  3202. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3203. Type *bt = base_type(x->type);
  3204. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3205. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3206. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3207. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3208. }
  3209. }
  3210. x->mode = Addressing_Value;
  3211. }
  3212. gb_internal Operand make_operand_from_node(Ast *node) {
  3213. GB_ASSERT(node != nullptr);
  3214. Operand x = {};
  3215. x.expr = node;
  3216. x.mode = node->tav.mode;
  3217. x.type = node->tav.type;
  3218. x.value = node->tav.value;
  3219. return x;
  3220. }
  3221. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3222. GB_ASSERT(e != nullptr);
  3223. ExprInfo *old = check_get_expr_info(c, e);
  3224. if (old == nullptr) {
  3225. if (type != nullptr && type != t_invalid) {
  3226. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3227. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3228. if (e->kind == Ast_TernaryIfExpr) {
  3229. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3230. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3231. }
  3232. }
  3233. }
  3234. return;
  3235. }
  3236. switch (e->kind) {
  3237. case_ast_node(ue, UnaryExpr, e);
  3238. if (old->value.kind != ExactValue_Invalid) {
  3239. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3240. // They don't need to be updated as they will be updated later and
  3241. // checked at the end of general checking stage.
  3242. break;
  3243. }
  3244. update_untyped_expr_type(c, ue->expr, type, final);
  3245. case_end;
  3246. case_ast_node(be, BinaryExpr, e);
  3247. if (old->value.kind != ExactValue_Invalid) {
  3248. // See above note in UnaryExpr case
  3249. break;
  3250. }
  3251. if (token_is_comparison(be->op.kind)) {
  3252. // NOTE(bill): Do nothing as the types are fine
  3253. } else if (token_is_shift(be->op.kind)) {
  3254. update_untyped_expr_type(c, be->left, type, final);
  3255. } else {
  3256. update_untyped_expr_type(c, be->left, type, final);
  3257. update_untyped_expr_type(c, be->right, type, final);
  3258. }
  3259. case_end;
  3260. case_ast_node(te, TernaryIfExpr, e);
  3261. if (old->value.kind != ExactValue_Invalid) {
  3262. // See above note in UnaryExpr case
  3263. break;
  3264. }
  3265. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3266. // having an untyped value
  3267. Operand x = make_operand_from_node(te->x);
  3268. Operand y = make_operand_from_node(te->y);
  3269. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3270. update_untyped_expr_type(c, te->x, type, final);
  3271. }
  3272. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3273. update_untyped_expr_type(c, te->y, type, final);
  3274. }
  3275. case_end;
  3276. case_ast_node(te, TernaryWhenExpr, e);
  3277. if (old->value.kind != ExactValue_Invalid) {
  3278. // See above note in UnaryExpr case
  3279. break;
  3280. }
  3281. update_untyped_expr_type(c, te->x, type, final);
  3282. update_untyped_expr_type(c, te->y, type, final);
  3283. case_end;
  3284. case_ast_node(ore, OrReturnExpr, e);
  3285. if (old->value.kind != ExactValue_Invalid) {
  3286. // See above note in UnaryExpr case
  3287. break;
  3288. }
  3289. update_untyped_expr_type(c, ore->expr, type, final);
  3290. case_end;
  3291. case_ast_node(oee, OrElseExpr, e);
  3292. if (old->value.kind != ExactValue_Invalid) {
  3293. // See above note in UnaryExpr case
  3294. break;
  3295. }
  3296. update_untyped_expr_type(c, oee->x, type, final);
  3297. update_untyped_expr_type(c, oee->y, type, final);
  3298. case_end;
  3299. case_ast_node(pe, ParenExpr, e);
  3300. update_untyped_expr_type(c, pe->expr, type, final);
  3301. case_end;
  3302. }
  3303. if (!final && is_type_untyped(type)) {
  3304. old->type = base_type(type);
  3305. return;
  3306. }
  3307. // We need to remove it and then give it a new one
  3308. check_remove_expr_info(c, e);
  3309. if (old->is_lhs && !is_type_integer(type)) {
  3310. gbString expr_str = expr_to_string(e);
  3311. gbString type_str = type_to_string(type);
  3312. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3313. gb_string_free(type_str);
  3314. gb_string_free(expr_str);
  3315. return;
  3316. }
  3317. add_type_and_value(c, e, old->mode, type, old->value);
  3318. }
  3319. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3320. GB_ASSERT(e != nullptr);
  3321. ExprInfo *found = check_get_expr_info(c, e);
  3322. if (found) {
  3323. found->value = value;
  3324. }
  3325. }
  3326. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3327. gbString expr_str = expr_to_string(operand->expr);
  3328. gbString type_str = type_to_string(target_type);
  3329. gbString from_type_str = type_to_string(operand->type);
  3330. char const *extra_text = "";
  3331. if (operand->mode == Addressing_Constant) {
  3332. if (big_int_is_zero(&operand->value.value_integer)) {
  3333. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3334. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3335. extra_text = " - Did you want 'nil'?";
  3336. }
  3337. }
  3338. }
  3339. ERROR_BLOCK();
  3340. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3341. if (operand->value.kind == ExactValue_String) {
  3342. String key = operand->value.value_string;
  3343. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3344. Type *et = base_type(target_type);
  3345. check_did_you_mean_type(key, et->Enum.fields, ".");
  3346. }
  3347. }
  3348. gb_string_free(from_type_str);
  3349. gb_string_free(type_str);
  3350. gb_string_free(expr_str);
  3351. operand->mode = Addressing_Invalid;
  3352. }
  3353. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3354. Type *t = core_type(type);
  3355. if (is_type_boolean(t)) {
  3356. // v = exact_value_to_boolean(v);
  3357. } else if (is_type_float(t)) {
  3358. v = exact_value_to_float(v);
  3359. } else if (is_type_integer(t)) {
  3360. v = exact_value_to_integer(v);
  3361. } else if (is_type_pointer(t)) {
  3362. v = exact_value_to_integer(v);
  3363. } else if (is_type_complex(t)) {
  3364. v = exact_value_to_complex(v);
  3365. } else if (is_type_quaternion(t)) {
  3366. v = exact_value_to_quaternion(v);
  3367. }
  3368. return v;
  3369. }
  3370. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3371. GB_ASSERT_NOT_NULL(target_type);
  3372. if (operand->mode == Addressing_Invalid ||
  3373. operand->mode == Addressing_Type ||
  3374. is_type_typed(operand->type) ||
  3375. target_type == t_invalid) {
  3376. return;
  3377. }
  3378. if (is_type_untyped(target_type)) {
  3379. GB_ASSERT(operand->type->kind == Type_Basic);
  3380. GB_ASSERT(target_type->kind == Type_Basic);
  3381. BasicKind x_kind = operand->type->Basic.kind;
  3382. BasicKind y_kind = target_type->Basic.kind;
  3383. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3384. if (x_kind < y_kind) {
  3385. operand->type = target_type;
  3386. update_untyped_expr_type(c, operand->expr, target_type, false);
  3387. }
  3388. } else if (x_kind != y_kind) {
  3389. operand->mode = Addressing_Invalid;
  3390. convert_untyped_error(c, operand, target_type);
  3391. return;
  3392. }
  3393. return;
  3394. }
  3395. Type *t = base_type(target_type);
  3396. if (c->in_enum_type) {
  3397. t = core_type(target_type);
  3398. }
  3399. switch (t->kind) {
  3400. case Type_Basic:
  3401. if (operand->mode == Addressing_Constant) {
  3402. check_is_expressible(c, operand, t);
  3403. if (operand->mode == Addressing_Invalid) {
  3404. return;
  3405. }
  3406. update_untyped_expr_value(c, operand->expr, operand->value);
  3407. } else {
  3408. switch (operand->type->Basic.kind) {
  3409. case Basic_UntypedBool:
  3410. if (!is_type_boolean(target_type)) {
  3411. operand->mode = Addressing_Invalid;
  3412. convert_untyped_error(c, operand, target_type);
  3413. return;
  3414. }
  3415. break;
  3416. case Basic_UntypedInteger:
  3417. case Basic_UntypedFloat:
  3418. case Basic_UntypedComplex:
  3419. case Basic_UntypedQuaternion:
  3420. case Basic_UntypedRune:
  3421. if (!is_type_numeric(target_type)) {
  3422. operand->mode = Addressing_Invalid;
  3423. convert_untyped_error(c, operand, target_type);
  3424. return;
  3425. }
  3426. break;
  3427. case Basic_UntypedNil:
  3428. if (is_type_any(target_type)) {
  3429. // target_type = t_untyped_nil;
  3430. } else if (is_type_cstring(target_type)) {
  3431. // target_type = t_untyped_nil;
  3432. } else if (!type_has_nil(target_type)) {
  3433. operand->mode = Addressing_Invalid;
  3434. convert_untyped_error(c, operand, target_type);
  3435. return;
  3436. }
  3437. break;
  3438. }
  3439. }
  3440. break;
  3441. case Type_Array: {
  3442. Type *elem = base_array_type(t);
  3443. if (check_is_assignable_to(c, operand, elem)) {
  3444. operand->mode = Addressing_Value;
  3445. } else {
  3446. if (operand->value.kind == ExactValue_String) {
  3447. String s = operand->value.value_string;
  3448. if (is_type_u8_array(t)) {
  3449. if (s.len == t->Array.count) {
  3450. break;
  3451. }
  3452. } else if (is_type_rune_array(t)) {
  3453. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3454. if (rune_count == t->Array.count) {
  3455. break;
  3456. }
  3457. }
  3458. }
  3459. operand->mode = Addressing_Invalid;
  3460. convert_untyped_error(c, operand, target_type);
  3461. return;
  3462. }
  3463. break;
  3464. }
  3465. case Type_Matrix: {
  3466. Type *elem = base_array_type(t);
  3467. if (check_is_assignable_to(c, operand, elem)) {
  3468. if (t->Matrix.row_count != t->Matrix.column_count) {
  3469. operand->mode = Addressing_Invalid;
  3470. begin_error_block();
  3471. defer (end_error_block());
  3472. convert_untyped_error(c, operand, target_type);
  3473. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3474. return;
  3475. } else {
  3476. operand->mode = Addressing_Value;
  3477. }
  3478. } else {
  3479. operand->mode = Addressing_Invalid;
  3480. convert_untyped_error(c, operand, target_type);
  3481. return;
  3482. }
  3483. break;
  3484. }
  3485. case Type_Union:
  3486. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3487. TEMPORARY_ALLOCATOR_GUARD();
  3488. isize count = t->Union.variants.count;
  3489. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3490. isize valid_count = 0;
  3491. isize first_success_index = -1;
  3492. for_array(i, t->Union.variants) {
  3493. Type *vt = t->Union.variants[i];
  3494. i64 score = 0;
  3495. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3496. valids[valid_count].index = i;
  3497. valids[valid_count].score = score;
  3498. valid_count += 1;
  3499. if (first_success_index < 0) {
  3500. first_success_index = i;
  3501. }
  3502. }
  3503. }
  3504. if (valid_count > 1) {
  3505. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3506. i64 best_score = valids[0].score;
  3507. for (isize i = 1; i < valid_count; i++) {
  3508. auto v = valids[i];
  3509. if (best_score > v.score) {
  3510. valid_count = i;
  3511. break;
  3512. }
  3513. best_score = v.score;
  3514. }
  3515. first_success_index = valids[0].index;
  3516. }
  3517. gbString type_str = type_to_string(target_type);
  3518. defer (gb_string_free(type_str));
  3519. if (valid_count == 1) {
  3520. operand->mode = Addressing_Value;
  3521. operand->type = t->Union.variants[first_success_index];
  3522. target_type = t->Union.variants[first_success_index];
  3523. break;
  3524. } else if (valid_count > 1) {
  3525. begin_error_block();
  3526. defer (end_error_block());
  3527. GB_ASSERT(first_success_index >= 0);
  3528. operand->mode = Addressing_Invalid;
  3529. convert_untyped_error(c, operand, target_type);
  3530. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3531. i32 j = 0;
  3532. for (i32 i = 0; i < valid_count; i++) {
  3533. ValidIndexAndScore valid = valids[i];
  3534. if (j > 0 && valid_count > 2) error_line(", ");
  3535. if (j == valid_count-1) {
  3536. if (valid_count == 2) error_line(" ");
  3537. error_line("or ");
  3538. }
  3539. gbString str = type_to_string(t->Union.variants[valid.index]);
  3540. error_line("'%s'", str);
  3541. gb_string_free(str);
  3542. j++;
  3543. }
  3544. error_line("\n\n");
  3545. return;
  3546. } else if (is_type_untyped_uninit(operand->type)) {
  3547. target_type = t_untyped_uninit;
  3548. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3549. begin_error_block();
  3550. defer (end_error_block());
  3551. operand->mode = Addressing_Invalid;
  3552. convert_untyped_error(c, operand, target_type);
  3553. if (count > 0) {
  3554. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3555. error_line("\t");
  3556. for (i32 i = 0; i < count; i++) {
  3557. Type *v = t->Union.variants[i];
  3558. if (i > 0 && count > 2) error_line(", ");
  3559. if (i == count-1) {
  3560. if (count == 2) error_line(" ");
  3561. if (count > 1) {
  3562. error_line("or ");
  3563. }
  3564. }
  3565. gbString str = type_to_string(v);
  3566. error_line("'%s'", str);
  3567. gb_string_free(str);
  3568. }
  3569. error_line("\n\n");
  3570. }
  3571. return;
  3572. }
  3573. }
  3574. /* fallthrough */
  3575. default:
  3576. if (is_type_untyped_uninit(operand->type)) {
  3577. target_type = t_untyped_uninit;
  3578. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3579. target_type = t_untyped_nil;
  3580. } else {
  3581. operand->mode = Addressing_Invalid;
  3582. convert_untyped_error(c, operand, target_type);
  3583. return;
  3584. }
  3585. break;
  3586. }
  3587. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3588. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3589. } else {
  3590. target_type = default_type(operand->type);
  3591. }
  3592. }
  3593. update_untyped_expr_type(c, operand->expr, target_type, true);
  3594. operand->type = target_type;
  3595. }
  3596. 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) {
  3597. Operand operand = {Addressing_Invalid};
  3598. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3599. if (operand.mode == Addressing_Invalid) {
  3600. if (value) *value = 0;
  3601. return false;
  3602. }
  3603. Type *index_type = t_int;
  3604. if (type_hint != nullptr) {
  3605. index_type = type_hint;
  3606. }
  3607. convert_to_typed(c, &operand, index_type);
  3608. if (operand.mode == Addressing_Invalid) {
  3609. if (value) *value = 0;
  3610. return false;
  3611. }
  3612. if (type_hint != nullptr) {
  3613. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3614. gbString expr_str = expr_to_string(operand.expr);
  3615. gbString index_type_str = type_to_string(type_hint);
  3616. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3617. gb_string_free(index_type_str);
  3618. gb_string_free(expr_str);
  3619. if (value) *value = 0;
  3620. return false;
  3621. }
  3622. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3623. gbString expr_str = expr_to_string(operand.expr);
  3624. gbString type_str = type_to_string(operand.type);
  3625. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3626. gb_string_free(type_str);
  3627. gb_string_free(expr_str);
  3628. if (value) *value = 0;
  3629. return false;
  3630. }
  3631. if (operand.mode == Addressing_Constant &&
  3632. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3633. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3634. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3635. TEMPORARY_ALLOCATOR_GUARD();
  3636. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3637. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3638. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3639. if (value) *value = 0;
  3640. return false;
  3641. }
  3642. if (max_count >= 0) {
  3643. if (is_type_enum(index_type)) {
  3644. Type *bt = base_type(index_type);
  3645. GB_ASSERT(bt->kind == Type_Enum);
  3646. ExactValue const &lo = *bt->Enum.min_value;
  3647. ExactValue const &hi = *bt->Enum.max_value;
  3648. String lo_str = {};
  3649. String hi_str = {};
  3650. if (bt->Enum.fields.count > 0) {
  3651. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3652. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3653. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3654. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3655. }
  3656. bool out_of_bounds = false;
  3657. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3658. out_of_bounds = true;
  3659. }
  3660. if (out_of_bounds) {
  3661. gbString expr_str = expr_to_string(operand.expr);
  3662. if (lo_str.len > 0) {
  3663. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3664. } else {
  3665. gbString index_type_str = type_to_string(index_type);
  3666. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3667. gb_string_free(index_type_str);
  3668. }
  3669. gb_string_free(expr_str);
  3670. return false;
  3671. }
  3672. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3673. return true;
  3674. } else { // NOTE(bill): Do array bound checking
  3675. i64 v = -1;
  3676. if (i.used <= 1) {
  3677. v = big_int_to_i64(&i);
  3678. }
  3679. if (value) *value = v;
  3680. bool out_of_bounds = false;
  3681. if (v < 0) {
  3682. out_of_bounds = true;
  3683. } else if (open_range) {
  3684. out_of_bounds = v > max_count;
  3685. } else {
  3686. out_of_bounds = v >= max_count;
  3687. }
  3688. if (out_of_bounds) {
  3689. TEMPORARY_ALLOCATOR_GUARD();
  3690. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3691. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3692. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3693. return false;
  3694. }
  3695. return true;
  3696. }
  3697. } else {
  3698. if (value) *value = exact_value_to_i64(operand.value);
  3699. return true;
  3700. }
  3701. }
  3702. // NOTE(bill): It's alright :D
  3703. if (value) *value = -1;
  3704. return true;
  3705. }
  3706. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3707. if (value.kind == ExactValue_String) {
  3708. GB_ASSERT(0 <= index && index < value.value_string.len);
  3709. u8 val = value.value_string[index];
  3710. if (success_) *success_ = true;
  3711. if (finish_) *finish_ = true;
  3712. return exact_value_u64(val);
  3713. }
  3714. if (value.kind != ExactValue_Compound) {
  3715. if (success_) *success_ = true;
  3716. if (finish_) *finish_ = true;
  3717. return value;
  3718. }
  3719. Ast *node = value.value_compound;
  3720. switch (node->kind) {
  3721. case_ast_node(cl, CompoundLit, node);
  3722. if (cl->elems.count == 0) {
  3723. if (success_) *success_ = true;
  3724. if (finish_) *finish_ = true;
  3725. return empty_exact_value;
  3726. }
  3727. if (cl->elems[0]->kind == Ast_FieldValue) {
  3728. if (is_type_struct(node->tav.type)) {
  3729. bool found = false;
  3730. for (Ast *elem : cl->elems) {
  3731. if (elem->kind != Ast_FieldValue) {
  3732. continue;
  3733. }
  3734. ast_node(fv, FieldValue, elem);
  3735. String name = fv->field->Ident.token.string;
  3736. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3737. defer (array_free(&sub_sel.index));
  3738. if (sub_sel.index[0] == index) {
  3739. value = fv->value->tav.value;
  3740. found = true;
  3741. break;
  3742. }
  3743. }
  3744. if (!found) {
  3745. // Use the zero value if it is not found
  3746. value = {};
  3747. }
  3748. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3749. for (Ast *elem : cl->elems) {
  3750. if (elem->kind != Ast_FieldValue) {
  3751. continue;
  3752. }
  3753. ast_node(fv, FieldValue, elem);
  3754. if (is_ast_range(fv->field)) {
  3755. ast_node(ie, BinaryExpr, fv->field);
  3756. TypeAndValue lo_tav = ie->left->tav;
  3757. TypeAndValue hi_tav = ie->right->tav;
  3758. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3759. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3760. TokenKind op = ie->op.kind;
  3761. i64 lo = exact_value_to_i64(lo_tav.value);
  3762. i64 hi = exact_value_to_i64(hi_tav.value);
  3763. i64 corrected_index = index;
  3764. if (is_type_enumerated_array(node->tav.type)) {
  3765. Type *bt = base_type(node->tav.type);
  3766. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3767. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3768. }
  3769. if (op != Token_RangeHalf) {
  3770. if (lo <= corrected_index && corrected_index <= hi) {
  3771. TypeAndValue tav = fv->value->tav;
  3772. if (success_) *success_ = true;
  3773. if (finish_) *finish_ = false;
  3774. return tav.value;
  3775. }
  3776. } else {
  3777. if (lo <= corrected_index && corrected_index < hi) {
  3778. TypeAndValue tav = fv->value->tav;
  3779. if (success_) *success_ = true;
  3780. if (finish_) *finish_ = false;
  3781. return tav.value;
  3782. }
  3783. }
  3784. } else {
  3785. TypeAndValue index_tav = fv->field->tav;
  3786. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3787. ExactValue index_value = index_tav.value;
  3788. if (is_type_enumerated_array(node->tav.type)) {
  3789. Type *bt = base_type(node->tav.type);
  3790. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3791. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3792. }
  3793. i64 field_index = exact_value_to_i64(index_value);
  3794. if (index == field_index) {
  3795. TypeAndValue tav = fv->value->tav;
  3796. if (success_) *success_ = true;
  3797. if (finish_) *finish_ = false;
  3798. return tav.value;;
  3799. }
  3800. }
  3801. }
  3802. }
  3803. } else {
  3804. i32 count = (i32)cl->elems.count;
  3805. if (count < index) {
  3806. if (success_) *success_ = false;
  3807. if (finish_) *finish_ = true;
  3808. return empty_exact_value;
  3809. }
  3810. if (cl->elems.count <= index) {
  3811. if (success_) *success_ = false;
  3812. if (finish_) *finish_ = false;
  3813. return value;
  3814. }
  3815. TypeAndValue tav = cl->elems[index]->tav;
  3816. if (tav.mode == Addressing_Constant) {
  3817. if (success_) *success_ = true;
  3818. if (finish_) *finish_ = false;
  3819. return tav.value;
  3820. } else {
  3821. GB_ASSERT(is_type_untyped_nil(tav.type));
  3822. if (success_) *success_ = true;
  3823. if (finish_) *finish_ = false;
  3824. return tav.value;
  3825. }
  3826. }
  3827. case_end;
  3828. default:
  3829. // TODO(bill): Should this be a general fallback?
  3830. if (success_) *success_ = true;
  3831. if (finish_) *finish_ = true;
  3832. return empty_exact_value;
  3833. }
  3834. if (finish_) *finish_ = false;
  3835. return value;
  3836. }
  3837. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3838. if (operand->mode != Addressing_Constant) {
  3839. if (success_) *success_ = false;
  3840. return empty_exact_value;
  3841. }
  3842. if (sel.indirect) {
  3843. if (success_) *success_ = false;
  3844. return empty_exact_value;
  3845. }
  3846. if (sel.index.count == 0) {
  3847. if (success_) *success_ = false;
  3848. return empty_exact_value;
  3849. }
  3850. ExactValue value = operand->value;
  3851. if (value.kind == ExactValue_Compound) {
  3852. while (sel.index.count > 0) {
  3853. i32 index = sel.index[0];
  3854. sel = sub_selection(sel, 1);
  3855. bool finish = false;
  3856. value = get_constant_field_single(c, value, index, success_, &finish);
  3857. if (finish) {
  3858. return value;
  3859. }
  3860. }
  3861. if (success_) *success_ = true;
  3862. return value;
  3863. } else if (value.kind == ExactValue_Quaternion) {
  3864. // @QuaternionLayout
  3865. Quaternion256 q = *value.value_quaternion;
  3866. GB_ASSERT(sel.index.count == 1);
  3867. switch (sel.index[0]) {
  3868. case 3: // w
  3869. if (success_) *success_ = true;
  3870. return exact_value_float(q.real);
  3871. case 0: // x
  3872. if (success_) *success_ = true;
  3873. return exact_value_float(q.imag);
  3874. case 1: // y
  3875. if (success_) *success_ = true;
  3876. return exact_value_float(q.jmag);
  3877. case 2: // z
  3878. if (success_) *success_ = true;
  3879. return exact_value_float(q.kmag);
  3880. }
  3881. if (success_) *success_ = false;
  3882. return empty_exact_value;
  3883. } else if (value.kind == ExactValue_Complex) {
  3884. // @QuaternionLayout
  3885. Complex128 c = *value.value_complex;
  3886. GB_ASSERT(sel.index.count == 1);
  3887. switch (sel.index[0]) {
  3888. case 0: // real
  3889. if (success_) *success_ = true;
  3890. return exact_value_float(c.real);
  3891. case 1: // imag
  3892. if (success_) *success_ = true;
  3893. return exact_value_float(c.imag);
  3894. }
  3895. if (success_) *success_ = false;
  3896. return empty_exact_value;
  3897. }
  3898. if (success_) *success_ = true;
  3899. return empty_exact_value;
  3900. }
  3901. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  3902. Type *array_type = base_type(type_deref(original_type));
  3903. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  3904. if (array_type->kind == Type_SimdVector) {
  3905. Type *elem_type = array_type->SimdVector.elem;
  3906. return alloc_type_simd_vector(new_count, elem_type);
  3907. }
  3908. Type *elem_type = array_type->Array.elem;
  3909. Type *swizzle_array_type = nullptr;
  3910. Type *bth = base_type(type_deref(type_hint));
  3911. if (bth != nullptr && bth->kind == Type_Array &&
  3912. bth->Array.count == new_count &&
  3913. are_types_identical(bth->Array.elem, elem_type)) {
  3914. swizzle_array_type = type_hint;
  3915. } else {
  3916. i64 max_count = array_type->Array.count;
  3917. if (new_count == max_count) {
  3918. swizzle_array_type = original_type;
  3919. } else {
  3920. swizzle_array_type = alloc_type_array(elem_type, new_count);
  3921. }
  3922. }
  3923. return swizzle_array_type;
  3924. }
  3925. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  3926. bool is_declared = entity != nullptr;
  3927. if (is_declared) {
  3928. if (entity->kind == Entity_Builtin) {
  3929. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  3930. // This means that we should just ignore the found result through it
  3931. *allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  3932. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  3933. is_declared = false;
  3934. }
  3935. }
  3936. return is_declared;
  3937. }
  3938. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  3939. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  3940. if (node->kind == Ast_Ident) {
  3941. String name = node->Ident.token.string;
  3942. return scope_lookup(c->scope, name);
  3943. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  3944. ast_node(se, SelectorExpr, node);
  3945. if (se->token.kind == Token_ArrowRight) {
  3946. return nullptr;
  3947. }
  3948. Ast *op_expr = se->expr;
  3949. Ast *selector = unparen_expr(se->selector);
  3950. if (selector == nullptr) {
  3951. return nullptr;
  3952. }
  3953. if (selector->kind != Ast_Ident) {
  3954. return nullptr;
  3955. }
  3956. Entity *entity = nullptr;
  3957. Entity *expr_entity = nullptr;
  3958. bool check_op_expr = true;
  3959. if (op_expr->kind == Ast_Ident) {
  3960. String op_name = op_expr->Ident.token.string;
  3961. Entity *e = scope_lookup(c->scope, op_name);
  3962. if (e == nullptr) {
  3963. return nullptr;
  3964. }
  3965. add_entity_use(c, op_expr, e);
  3966. expr_entity = e;
  3967. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  3968. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  3969. // It pretty much needs to be in this order and this way
  3970. // If you can clean this up, please do but be really careful
  3971. String import_name = op_name;
  3972. Scope *import_scope = e->ImportName.scope;
  3973. String entity_name = selector->Ident.token.string;
  3974. check_op_expr = false;
  3975. entity = scope_lookup_current(import_scope, entity_name);
  3976. bool allow_builtin = false;
  3977. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  3978. return nullptr;
  3979. }
  3980. check_entity_decl(c, entity, nullptr, nullptr);
  3981. if (entity->kind == Entity_ProcGroup) {
  3982. return entity;
  3983. }
  3984. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  3985. }
  3986. }
  3987. Operand operand = {};
  3988. if (check_op_expr) {
  3989. check_expr_base(c, &operand, op_expr, nullptr);
  3990. if (operand.mode == Addressing_Invalid) {
  3991. return nullptr;
  3992. }
  3993. }
  3994. if (entity == nullptr && selector->kind == Ast_Ident) {
  3995. String field_name = selector->Ident.token.string;
  3996. if (is_type_dynamic_array(type_deref(operand.type))) {
  3997. init_mem_allocator(c->checker);
  3998. }
  3999. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4000. entity = sel.entity;
  4001. }
  4002. if (entity != nullptr) {
  4003. return entity;
  4004. }
  4005. }
  4006. return nullptr;
  4007. }
  4008. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4009. ast_node(se, SelectorExpr, node);
  4010. bool check_op_expr = true;
  4011. Entity *expr_entity = nullptr;
  4012. Entity *entity = nullptr;
  4013. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4014. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4015. error(node, "Illegal use of -> selector shorthand outside of a call");
  4016. operand->mode = Addressing_Invalid;
  4017. operand->expr = node;
  4018. return nullptr;
  4019. }
  4020. operand->expr = node;
  4021. Ast *op_expr = se->expr;
  4022. Ast *selector = unparen_expr(se->selector);
  4023. if (selector == nullptr) {
  4024. operand->mode = Addressing_Invalid;
  4025. operand->expr = node;
  4026. return nullptr;
  4027. }
  4028. if (selector->kind != Ast_Ident) {
  4029. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4030. operand->mode = Addressing_Invalid;
  4031. operand->expr = node;
  4032. return nullptr;
  4033. }
  4034. if (op_expr->kind == Ast_Ident) {
  4035. String op_name = op_expr->Ident.token.string;
  4036. Entity *e = scope_lookup(c->scope, op_name);
  4037. add_entity_use(c, op_expr, e);
  4038. expr_entity = e;
  4039. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4040. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4041. // It pretty much needs to be in this order and this way
  4042. // If you can clean this up, please do but be really careful
  4043. String import_name = op_name;
  4044. Scope *import_scope = e->ImportName.scope;
  4045. String entity_name = selector->Ident.token.string;
  4046. check_op_expr = false;
  4047. entity = scope_lookup_current(import_scope, entity_name);
  4048. bool allow_builtin = false;
  4049. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4050. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4051. operand->mode = Addressing_Invalid;
  4052. operand->expr = node;
  4053. check_did_you_mean_scope(entity_name, import_scope);
  4054. return nullptr;
  4055. }
  4056. check_entity_decl(c, entity, nullptr, nullptr);
  4057. if (entity->kind == Entity_ProcGroup) {
  4058. operand->mode = Addressing_ProcGroup;
  4059. operand->proc_group = entity;
  4060. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4061. return entity;
  4062. }
  4063. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4064. if (!is_entity_exported(entity, allow_builtin)) {
  4065. gbString sel_str = expr_to_string(selector);
  4066. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4067. gb_string_free(sel_str);
  4068. // NOTE(bill): make the state valid still, even if it's "invalid"
  4069. // operand->mode = Addressing_Invalid;
  4070. // operand->expr = node;
  4071. // return nullptr;
  4072. }
  4073. if (entity->kind == Entity_ProcGroup) {
  4074. Array<Entity *> procs = entity->ProcGroup.entities;
  4075. bool skip = false;
  4076. for (Entity *p : procs) {
  4077. Type *t = base_type(p->type);
  4078. if (t == t_invalid) {
  4079. continue;
  4080. }
  4081. Operand x = {};
  4082. x.mode = Addressing_Value;
  4083. x.type = t;
  4084. if (type_hint != nullptr) {
  4085. if (check_is_assignable_to(c, &x, type_hint)) {
  4086. entity = p;
  4087. skip = true;
  4088. break;
  4089. }
  4090. }
  4091. }
  4092. if (!skip) {
  4093. GB_ASSERT(entity != nullptr);
  4094. operand->mode = Addressing_ProcGroup;
  4095. operand->type = t_invalid;
  4096. operand->expr = node;
  4097. operand->proc_group = entity;
  4098. return entity;
  4099. }
  4100. }
  4101. }
  4102. }
  4103. if (check_op_expr) {
  4104. check_expr_base(c, operand, op_expr, nullptr);
  4105. if (operand->mode == Addressing_Invalid) {
  4106. operand->mode = Addressing_Invalid;
  4107. operand->expr = node;
  4108. return nullptr;
  4109. }
  4110. }
  4111. if (entity == nullptr && selector->kind == Ast_Ident) {
  4112. String field_name = selector->Ident.token.string;
  4113. if (is_type_dynamic_array(type_deref(operand->type))) {
  4114. init_mem_allocator(c->checker);
  4115. }
  4116. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4117. entity = sel.entity;
  4118. // NOTE(bill): Add type info needed for fields like 'names'
  4119. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4120. add_type_info_type(c, operand->type);
  4121. }
  4122. if (is_type_enum(operand->type)) {
  4123. add_type_info_type(c, operand->type);
  4124. }
  4125. }
  4126. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  4127. // TODO(bill): Simd_Vector swizzling
  4128. String field_name = selector->Ident.token.string;
  4129. if (1 < field_name.len && field_name.len <= 4) {
  4130. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4131. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4132. bool found_xyzw = false;
  4133. bool found_rgba = false;
  4134. for (isize i = 0; i < field_name.len; i++) {
  4135. bool valid = false;
  4136. for (isize j = 0; j < 4; j++) {
  4137. if (field_name.text[i] == swizzles_xyzw[j]) {
  4138. found_xyzw = true;
  4139. valid = true;
  4140. break;
  4141. }
  4142. if (field_name.text[i] == swizzles_rgba[j]) {
  4143. found_rgba = true;
  4144. valid = true;
  4145. break;
  4146. }
  4147. }
  4148. if (!valid) {
  4149. goto end_of_array_selector_swizzle;
  4150. }
  4151. }
  4152. u8 *swizzles = nullptr;
  4153. u8 index_count = cast(u8)field_name.len;
  4154. if (found_xyzw && found_rgba) {
  4155. gbString op_str = expr_to_string(op_expr);
  4156. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4157. gb_string_free(op_str);
  4158. operand->mode = Addressing_Invalid;
  4159. operand->expr = node;
  4160. return nullptr;
  4161. }
  4162. u8 indices = 0;
  4163. if (found_xyzw) {
  4164. swizzles = swizzles_xyzw;
  4165. } else if (found_rgba) {
  4166. swizzles = swizzles_rgba;
  4167. }
  4168. for (isize i = 0; i < field_name.len; i++) {
  4169. for (isize j = 0; j < 4; j++) {
  4170. if (field_name.text[i] == swizzles[j]) {
  4171. indices |= cast(u8)(j)<<(i*2);
  4172. break;
  4173. }
  4174. }
  4175. }
  4176. Type *original_type = operand->type;
  4177. Type *array_type = base_type(type_deref(original_type));
  4178. GB_ASSERT(array_type->kind == Type_Array);
  4179. i64 array_count = array_type->Array.count;
  4180. for (u8 i = 0; i < index_count; i++) {
  4181. u8 idx = indices>>(i*2) & 3;
  4182. if (idx >= array_count) {
  4183. char c = 0;
  4184. if (found_xyzw) {
  4185. c = swizzles_xyzw[idx];
  4186. } else if (found_rgba) {
  4187. c = swizzles_rgba[idx];
  4188. } else {
  4189. GB_PANIC("unknown swizzle kind");
  4190. }
  4191. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4192. break;
  4193. }
  4194. }
  4195. se->swizzle_count = index_count;
  4196. se->swizzle_indices = indices;
  4197. AddressingMode prev_mode = operand->mode;
  4198. operand->mode = Addressing_SwizzleValue;
  4199. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4200. operand->expr = node;
  4201. switch (prev_mode) {
  4202. case Addressing_Variable:
  4203. case Addressing_SoaVariable:
  4204. case Addressing_SwizzleVariable:
  4205. operand->mode = Addressing_SwizzleVariable;
  4206. break;
  4207. }
  4208. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4209. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4210. return swizzle_entity;
  4211. }
  4212. end_of_array_selector_swizzle:;
  4213. }
  4214. if (entity == nullptr) {
  4215. gbString op_str = expr_to_string(op_expr);
  4216. gbString type_str = type_to_string_shorthand(operand->type);
  4217. gbString sel_str = expr_to_string(selector);
  4218. if (operand->mode == Addressing_Type) {
  4219. if (is_type_polymorphic(operand->type, true)) {
  4220. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4221. } else {
  4222. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4223. }
  4224. } else {
  4225. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4226. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4227. String const &name = selector->Ident.token.string;
  4228. Type *bt = base_type(operand->type);
  4229. if (operand->type->kind == Type_Named &&
  4230. operand->type->Named.type_name &&
  4231. operand->type->Named.type_name->kind == Entity_TypeName &&
  4232. operand->type->Named.type_name->TypeName.objc_metadata) {
  4233. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4234. } else if (bt->kind == Type_Struct) {
  4235. check_did_you_mean_type(name, bt->Struct.fields);
  4236. } else if (bt->kind == Type_Enum) {
  4237. check_did_you_mean_type(name, bt->Enum.fields);
  4238. }
  4239. }
  4240. }
  4241. gb_string_free(sel_str);
  4242. gb_string_free(type_str);
  4243. gb_string_free(op_str);
  4244. operand->mode = Addressing_Invalid;
  4245. operand->expr = node;
  4246. return nullptr;
  4247. }
  4248. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4249. bool success = false;
  4250. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4251. if (success) {
  4252. operand->mode = Addressing_Constant;
  4253. operand->expr = node;
  4254. operand->value = field_value;
  4255. operand->type = entity->type;
  4256. add_entity_use(c, selector, entity);
  4257. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4258. return entity;
  4259. }
  4260. gbString op_str = expr_to_string(op_expr);
  4261. gbString type_str = type_to_string_shorthand(operand->type);
  4262. gbString sel_str = expr_to_string(selector);
  4263. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4264. gb_string_free(sel_str);
  4265. gb_string_free(type_str);
  4266. gb_string_free(op_str);
  4267. operand->mode = Addressing_Invalid;
  4268. operand->expr = node;
  4269. return nullptr;
  4270. }
  4271. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4272. bool success = false;
  4273. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4274. if (success) {
  4275. operand->mode = Addressing_Constant;
  4276. operand->expr = node;
  4277. operand->value = field_value;
  4278. operand->type = entity->type;
  4279. add_entity_use(c, selector, entity);
  4280. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4281. return entity;
  4282. }
  4283. gbString op_str = expr_to_string(op_expr);
  4284. gbString type_str = type_to_string_shorthand(operand->type);
  4285. gbString sel_str = expr_to_string(selector);
  4286. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4287. gb_string_free(sel_str);
  4288. gb_string_free(type_str);
  4289. gb_string_free(op_str);
  4290. operand->mode = Addressing_Invalid;
  4291. operand->expr = node;
  4292. return nullptr;
  4293. }
  4294. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4295. gbString op_str = expr_to_string(op_expr);
  4296. gbString type_str = type_to_string_shorthand(operand->type);
  4297. gbString sel_str = expr_to_string(selector);
  4298. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4299. gb_string_free(sel_str);
  4300. gb_string_free(type_str);
  4301. gb_string_free(op_str);
  4302. operand->mode = Addressing_Invalid;
  4303. operand->expr = node;
  4304. return nullptr;
  4305. }
  4306. add_entity_use(c, selector, entity);
  4307. operand->type = entity->type;
  4308. operand->expr = node;
  4309. switch (entity->kind) {
  4310. case Entity_Constant:
  4311. operand->value = entity->Constant.value;
  4312. operand->mode = Addressing_Constant;
  4313. if (operand->value.kind == ExactValue_Procedure) {
  4314. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4315. if (proc != nullptr) {
  4316. operand->mode = Addressing_Value;
  4317. operand->type = proc->type;
  4318. }
  4319. }
  4320. break;
  4321. case Entity_Variable:
  4322. if (sel.indirect) {
  4323. operand->mode = Addressing_Variable;
  4324. } else if (operand->mode == Addressing_Context) {
  4325. // Do nothing
  4326. } else if (operand->mode == Addressing_MapIndex) {
  4327. operand->mode = Addressing_Value;
  4328. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4329. operand->mode = Addressing_SoaVariable;
  4330. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4331. operand->mode = Addressing_Value;
  4332. } else if (operand->mode == Addressing_SoaVariable) {
  4333. operand->mode = Addressing_Variable;
  4334. } else if (operand->mode != Addressing_Value) {
  4335. operand->mode = Addressing_Variable;
  4336. } else {
  4337. operand->mode = Addressing_Value;
  4338. }
  4339. break;
  4340. case Entity_TypeName:
  4341. operand->mode = Addressing_Type;
  4342. break;
  4343. case Entity_Procedure:
  4344. operand->mode = Addressing_Value;
  4345. operand->value = exact_value_procedure(node);
  4346. break;
  4347. case Entity_Builtin:
  4348. operand->mode = Addressing_Builtin;
  4349. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4350. break;
  4351. case Entity_ProcGroup:
  4352. operand->mode = Addressing_ProcGroup;
  4353. operand->proc_group = entity;
  4354. break;
  4355. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4356. case Entity_Nil:
  4357. operand->mode = Addressing_Value;
  4358. break;
  4359. }
  4360. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4361. return entity;
  4362. }
  4363. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4364. ptr = base_type(ptr);
  4365. if (is_type_pointer(ptr)) {
  4366. if (is_type_rawptr(ptr)) {
  4367. return false;
  4368. }
  4369. if (elem) *elem = ptr->Pointer.elem;
  4370. return true;
  4371. }
  4372. return false;
  4373. }
  4374. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4375. elem = core_type(elem);
  4376. if (is_type_internally_pointer_like(elem)) {
  4377. return true;
  4378. }
  4379. if (elem->kind == Type_BitSet) {
  4380. elem = bit_set_to_int(elem);
  4381. }
  4382. if (elem->kind != Type_Basic) {
  4383. return false;
  4384. }
  4385. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4386. }
  4387. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4388. switch (node->kind) {
  4389. case_ast_node(i, Ident, node);
  4390. String name = i->token.string;
  4391. if (nested) {
  4392. Entity *e = scope_lookup_current(s, name);
  4393. if (e != nullptr) {
  4394. if (out_scope) *out_scope = e->scope;
  4395. return true;
  4396. }
  4397. } else {
  4398. Entity *e = scope_lookup(s, name);
  4399. if (e != nullptr) {
  4400. if (out_scope) *out_scope = e->scope;
  4401. return true;
  4402. }
  4403. }
  4404. case_end;
  4405. case_ast_node(se, SelectorExpr, node);
  4406. Ast *lhs = se->expr;
  4407. Ast *rhs = se->selector;
  4408. Scope *lhs_scope = nullptr;
  4409. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4410. return check_identifier_exists(lhs_scope, rhs, true);
  4411. }
  4412. case_end;
  4413. }
  4414. return false;
  4415. }
  4416. gb_internal isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) {
  4417. if (lhs != nullptr && c->decl != nullptr) {
  4418. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4419. Entity *e = lhs[tuple_index + j];
  4420. if (e != nullptr) {
  4421. DeclInfo *decl = decl_info_of_entity(e);
  4422. if (decl != nullptr) {
  4423. rw_mutex_shared_lock(&decl->deps_mutex);
  4424. rw_mutex_lock(&c->decl->deps_mutex);
  4425. for (Entity *dep : decl->deps) {
  4426. ptr_set_add(&c->decl->deps, dep);
  4427. }
  4428. rw_mutex_unlock(&c->decl->deps_mutex);
  4429. rw_mutex_shared_unlock(&decl->deps_mutex);
  4430. }
  4431. }
  4432. }
  4433. }
  4434. return tuple_count;
  4435. }
  4436. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4437. if (o.type && is_type_no_copy(o.type)) {
  4438. Ast *expr = unparen_expr(o.expr);
  4439. if (expr && o.mode != Addressing_Constant) {
  4440. if (expr->kind == Ast_CallExpr) {
  4441. // Okay
  4442. } else {
  4443. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4444. return true;
  4445. }
  4446. }
  4447. }
  4448. return false;
  4449. }
  4450. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4451. bool optional_ok = false;
  4452. isize tuple_index = 0;
  4453. for (Ast *rhs_expr : rhs) {
  4454. CheckerContext c_ = *ctx;
  4455. CheckerContext *c = &c_;
  4456. Operand o = {};
  4457. Type *type_hint = nullptr;
  4458. if (tuple_index < lhs.count) {
  4459. type_hint = lhs[tuple_index].type;
  4460. }
  4461. check_expr_base(c, &o, rhs_expr, type_hint);
  4462. if (o.mode == Addressing_NoValue) {
  4463. error_operand_no_value(&o);
  4464. o.mode = Addressing_Invalid;
  4465. }
  4466. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4467. if (lhs.count == 2 && rhs.count == 1 &&
  4468. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4469. Ast *expr = unparen_expr(o.expr);
  4470. Operand val0 = o;
  4471. Operand val1 = o;
  4472. val0.mode = Addressing_Value;
  4473. val1.mode = Addressing_Value;
  4474. val1.type = t_untyped_bool;
  4475. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4476. if (expr->kind == Ast_TypeAssertion &&
  4477. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4478. // NOTE(bill): Used only for optimizations in the backend
  4479. if (is_blank_ident(lhs[0].expr)) {
  4480. expr->TypeAssertion.ignores[0] = true;
  4481. }
  4482. if (is_blank_ident(lhs[1].expr)) {
  4483. expr->TypeAssertion.ignores[1] = true;
  4484. }
  4485. }
  4486. array_add(operands, val0);
  4487. array_add(operands, val1);
  4488. optional_ok = true;
  4489. tuple_index += 2;
  4490. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4491. Type *tuple = o.type;
  4492. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4493. Ast *expr = unparen_expr(o.expr);
  4494. if (expr->kind == Ast_CallExpr) {
  4495. expr->CallExpr.optional_ok_one = true;
  4496. }
  4497. Operand val = o;
  4498. val.type = tuple->Tuple.variables[0]->type;
  4499. val.mode = Addressing_Value;
  4500. array_add(operands, val);
  4501. tuple_index += tuple->Tuple.variables.count;
  4502. } else {
  4503. array_add(operands, o);
  4504. tuple_index += 1;
  4505. }
  4506. } else {
  4507. TypeTuple *tuple = &o.type->Tuple;
  4508. for (Entity *e : tuple->variables) {
  4509. o.type = e->type;
  4510. array_add(operands, o);
  4511. check_no_copy_assignment(o, str_lit("assignment"));
  4512. }
  4513. tuple_index += tuple->variables.count;
  4514. }
  4515. }
  4516. return optional_ok;
  4517. }
  4518. typedef u32 UnpackFlags;
  4519. enum UnpackFlag : u32 {
  4520. UnpackFlag_None = 0,
  4521. UnpackFlag_AllowOk = 1<<0,
  4522. UnpackFlag_IsVariadic = 1<<1,
  4523. UnpackFlag_AllowUndef = 1<<2,
  4524. };
  4525. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4526. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4527. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4528. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4529. bool optional_ok = false;
  4530. isize tuple_index = 0;
  4531. for (Ast *rhs : rhs_arguments) {
  4532. if (rhs->kind == Ast_FieldValue) {
  4533. error(rhs, "Invalid use of 'field = value'");
  4534. rhs = rhs->FieldValue.value;
  4535. }
  4536. CheckerContext c_ = *ctx;
  4537. CheckerContext *c = &c_;
  4538. Operand o = {};
  4539. Type *type_hint = nullptr;
  4540. if (lhs != nullptr && tuple_index < lhs_count) {
  4541. // NOTE(bill): override DeclInfo for dependency
  4542. Entity *e = lhs[tuple_index];
  4543. if (e != nullptr) {
  4544. type_hint = e->type;
  4545. if (e->flags & EntityFlag_Ellipsis) {
  4546. GB_ASSERT(is_type_slice(e->type));
  4547. GB_ASSERT(e->type->kind == Type_Slice);
  4548. type_hint = e->type->Slice.elem;
  4549. }
  4550. }
  4551. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4552. // NOTE(bill): override DeclInfo for dependency
  4553. Entity *e = lhs[lhs_count-1];
  4554. if (e != nullptr) {
  4555. type_hint = e->type;
  4556. if (e->flags & EntityFlag_Ellipsis) {
  4557. GB_ASSERT(is_type_slice(e->type));
  4558. GB_ASSERT(e->type->kind == Type_Slice);
  4559. type_hint = e->type->Slice.elem;
  4560. }
  4561. }
  4562. }
  4563. Ast *rhs_expr = unparen_expr(rhs);
  4564. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4565. // NOTE(bill): Just handle this very specific logic here
  4566. o.type = t_untyped_uninit;
  4567. o.mode = Addressing_Value;
  4568. o.expr = rhs;
  4569. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4570. } else {
  4571. check_expr_base(c, &o, rhs, type_hint);
  4572. }
  4573. if (o.mode == Addressing_NoValue) {
  4574. error_operand_no_value(&o);
  4575. o.mode = Addressing_Invalid;
  4576. }
  4577. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4578. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4579. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4580. Ast *expr = unparen_expr(o.expr);
  4581. Operand val0 = o;
  4582. Operand val1 = o;
  4583. val0.mode = Addressing_Value;
  4584. val1.mode = Addressing_Value;
  4585. val1.type = t_untyped_bool;
  4586. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4587. if (expr->kind == Ast_TypeAssertion &&
  4588. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4589. // NOTE(bill): Used only for optimizations in the backend
  4590. if (is_blank_ident(lhs[0]->token)) {
  4591. expr->TypeAssertion.ignores[0] = true;
  4592. }
  4593. if (is_blank_ident(lhs[1]->token)) {
  4594. expr->TypeAssertion.ignores[1] = true;
  4595. }
  4596. }
  4597. array_add(operands, val0);
  4598. array_add(operands, val1);
  4599. optional_ok = true;
  4600. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4601. } else {
  4602. array_add(operands, o);
  4603. tuple_index += 1;
  4604. }
  4605. } else {
  4606. TypeTuple *tuple = &o.type->Tuple;
  4607. for (Entity *e : tuple->variables) {
  4608. o.type = e->type;
  4609. array_add(operands, o);
  4610. }
  4611. isize count = tuple->variables.count;
  4612. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4613. }
  4614. }
  4615. return optional_ok;
  4616. }
  4617. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4618. GB_ASSERT(pt != nullptr);
  4619. GB_ASSERT(pt->kind == Type_Proc);
  4620. isize param_count = 0;
  4621. isize param_count_excluding_defaults = 0;
  4622. bool variadic = pt->Proc.variadic;
  4623. TypeTuple *param_tuple = nullptr;
  4624. if (pt->Proc.params != nullptr) {
  4625. param_tuple = &pt->Proc.params->Tuple;
  4626. param_count = param_tuple->variables.count;
  4627. if (variadic) {
  4628. for (isize i = param_count-1; i >= 0; i--) {
  4629. Entity *e = param_tuple->variables[i];
  4630. if (e->kind == Entity_TypeName) {
  4631. break;
  4632. }
  4633. if (e->kind == Entity_Variable) {
  4634. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4635. param_count--;
  4636. continue;
  4637. }
  4638. }
  4639. break;
  4640. }
  4641. param_count--;
  4642. }
  4643. }
  4644. param_count_excluding_defaults = param_count;
  4645. if (param_tuple != nullptr) {
  4646. for (isize i = param_count-1; i >= 0; i--) {
  4647. Entity *e = param_tuple->variables[i];
  4648. if (e->kind == Entity_TypeName) {
  4649. break;
  4650. }
  4651. if (e->kind == Entity_Variable) {
  4652. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4653. param_count_excluding_defaults--;
  4654. continue;
  4655. }
  4656. }
  4657. break;
  4658. }
  4659. }
  4660. if (param_count_) *param_count_ = param_count;
  4661. return param_count_excluding_defaults;
  4662. }
  4663. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4664. isize param_count = pt->param_count;
  4665. for (isize i = 0; i < param_count; i++) {
  4666. Entity *e = pt->params->Tuple.variables[i];
  4667. String name = e->token.string;
  4668. if (is_blank_ident(name)) {
  4669. continue;
  4670. }
  4671. if (name == parameter_name) {
  4672. return i;
  4673. }
  4674. }
  4675. return -1;
  4676. }
  4677. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4678. type = base_type(type);
  4679. GB_ASSERT(type->kind == Type_Proc);
  4680. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4681. }
  4682. gb_internal CALL_ARGUMENT_CHECKER(check_call_arguments_internal) {
  4683. TEMPORARY_ALLOCATOR_GUARD();
  4684. CallArgumentError err = CallArgumentError_None;
  4685. ast_node(ce, CallExpr, call);
  4686. GB_ASSERT(is_type_proc(proc_type));
  4687. proc_type = base_type(proc_type);
  4688. TypeProc *pt = &proc_type->Proc;
  4689. isize param_count = 0;
  4690. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4691. bool variadic = pt->variadic;
  4692. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4693. i64 score = 0;
  4694. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  4695. Type *final_proc_type = proc_type;
  4696. Entity *gen_entity = nullptr;
  4697. if (vari_expand && !variadic) {
  4698. if (show_error) {
  4699. error(ce->ellipsis,
  4700. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4701. LIT(ce->proc->Ident.token.string));
  4702. }
  4703. err = CallArgumentError_NonVariadicExpand;
  4704. } else if (vari_expand && pt->c_vararg) {
  4705. if (show_error) {
  4706. error(ce->ellipsis,
  4707. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4708. LIT(ce->proc->Ident.token.string));
  4709. }
  4710. err = CallArgumentError_NonVariadicExpand;
  4711. }
  4712. if (ce->split_args) {
  4713. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  4714. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  4715. defer ({
  4716. for (Operand const &o : ordered_operands) {
  4717. if (o.expr != nullptr) {
  4718. call->viral_state_flags |= o.expr->viral_state_flags;
  4719. }
  4720. }
  4721. });
  4722. if (check_order_of_call_arguments(c, proc_type, call, show_error)) {
  4723. return CallArgumentError_OutOfOrderParameters;
  4724. }
  4725. isize positional_operand_count = positional_operands.count;
  4726. if (variadic) {
  4727. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  4728. } else if (positional_operand_count > pt->param_count) {
  4729. err = CallArgumentError_TooManyArguments;
  4730. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4731. if (show_error) {
  4732. gbString proc_str = expr_to_string(ce->proc);
  4733. defer (gb_string_free(proc_str));
  4734. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  4735. }
  4736. return err;
  4737. }
  4738. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  4739. for (isize i = 0; i < positional_operand_count; i++) {
  4740. ordered_operands[i] = positional_operands[i];
  4741. visited[i] = true;
  4742. }
  4743. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  4744. if (named_operands.count != 0) {
  4745. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  4746. for_array(i, ce->split_args->named) {
  4747. Ast *arg = ce->split_args->named[i];
  4748. Operand operand = named_operands[i];
  4749. ast_node(fv, FieldValue, arg);
  4750. if (fv->field->kind != Ast_Ident) {
  4751. if (show_error) {
  4752. gbString expr_str = expr_to_string(fv->field);
  4753. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4754. gb_string_free(expr_str);
  4755. }
  4756. err = CallArgumentError_InvalidFieldValue;
  4757. continue;
  4758. }
  4759. String name = fv->field->Ident.token.string;
  4760. isize param_index = lookup_procedure_parameter(pt, name);
  4761. if (param_index < 0) {
  4762. if (show_error) {
  4763. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4764. }
  4765. err = CallArgumentError_ParameterNotFound;
  4766. continue;
  4767. }
  4768. if (visited[param_index]) {
  4769. if (show_error) {
  4770. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4771. }
  4772. err = CallArgumentError_DuplicateParameter;
  4773. continue;
  4774. }
  4775. Entity *e = pt->params->Tuple.variables[param_index];
  4776. check_assignment(c, &operand, e->type, str_lit("named argument"));
  4777. visited[param_index] = true;
  4778. ordered_operands[param_index] = operand;
  4779. err = CallArgumentError_DuplicateParameter;
  4780. }
  4781. }
  4782. if (variadic) {
  4783. if (visited[pt->variadic_index] &&
  4784. positional_operand_count < positional_operands.count) {
  4785. if (show_error) {
  4786. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  4787. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  4788. }
  4789. err = CallArgumentError_DuplicateParameter;
  4790. } else {
  4791. visited[pt->variadic_index] = true;
  4792. if (vari_expand) {
  4793. GB_ASSERT(variadic_operands.count != 0);
  4794. ordered_operands[pt->variadic_index] = variadic_operands[0];
  4795. } else {
  4796. AstFile *f = call->file();
  4797. // HACK(bill): this is an awful hack
  4798. Operand o = {};
  4799. o.mode = Addressing_Value;
  4800. o.expr = ast_ident(f, make_token_ident("nil"));
  4801. o.expr->Ident.token.pos = ast_token(call).pos;
  4802. if (variadic_operands.count != 0) {
  4803. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  4804. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  4805. if (is_type_polymorphic(vt->type)) {
  4806. o.type = alloc_type_slice(default_type(variadic_operands[0].type));
  4807. } else {
  4808. o.type = vt->type;
  4809. }
  4810. } else {
  4811. o.type = t_untyped_nil;
  4812. }
  4813. ordered_operands[pt->variadic_index] = o;
  4814. }
  4815. }
  4816. }
  4817. for (Operand const &o : ordered_operands) {
  4818. if (o.mode != Addressing_Invalid) {
  4819. check_no_copy_assignment(o, str_lit("procedure call expression"));
  4820. }
  4821. }
  4822. for (isize i = 0; i < pt->param_count; i++) {
  4823. if (!visited[i]) {
  4824. Entity *e = pt->params->Tuple.variables[i];
  4825. if (is_blank_ident(e->token)) {
  4826. continue;
  4827. }
  4828. if (e->kind == Entity_Variable) {
  4829. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4830. score += assign_score_function(1);
  4831. continue;
  4832. }
  4833. }
  4834. if (show_error) {
  4835. if (e->kind == Entity_TypeName) {
  4836. error(call, "Type parameter '%.*s' is missing in procedure call",
  4837. LIT(e->token.string));
  4838. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4839. // Ignore
  4840. } else {
  4841. gbString str = type_to_string(e->type);
  4842. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4843. LIT(e->token.string), str);
  4844. gb_string_free(str);
  4845. }
  4846. }
  4847. err = CallArgumentError_ParameterMissing;
  4848. }
  4849. }
  4850. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  4851. err = CallArgumentError_None;
  4852. if (variadic) {
  4853. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  4854. Type *t = pt->params->Tuple.variables[0]->type;
  4855. if (is_type_polymorphic(t)) {
  4856. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4857. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4858. }
  4859. }
  4860. } else {
  4861. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  4862. PolyProcData poly_proc_data = {};
  4863. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  4864. gen_entity = poly_proc_data.gen_entity;
  4865. Type *gept = base_type(gen_entity->type);
  4866. GB_ASSERT(is_type_proc(gept));
  4867. final_proc_type = gen_entity->type;
  4868. pt = &gept->Proc;
  4869. } else {
  4870. err = CallArgumentError_WrongTypes;
  4871. }
  4872. }
  4873. for (isize i = 0; i < pt->param_count; i++) {
  4874. Operand *o = &ordered_operands[i];
  4875. if (o->mode == Addressing_Invalid) {
  4876. continue;
  4877. }
  4878. Entity *e = pt->params->Tuple.variables[i];
  4879. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  4880. if (e->kind == Entity_TypeName) {
  4881. GB_ASSERT(pt->is_polymorphic);
  4882. if (o->mode != Addressing_Type) {
  4883. if (show_error) {
  4884. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  4885. }
  4886. err = CallArgumentError_WrongTypes;
  4887. }
  4888. if (are_types_identical(e->type, o->type)) {
  4889. score += assign_score_function(1);
  4890. } else {
  4891. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4892. }
  4893. } else {
  4894. i64 s = 0;
  4895. if (!check_is_assignable_to_with_score(c, o, e->type, &s, param_is_variadic)) {
  4896. bool ok = false;
  4897. if (e->flags & EntityFlag_AnyInt) {
  4898. if (is_type_integer(e->type)) {
  4899. ok = check_is_castable_to(c, o, e->type);
  4900. }
  4901. }
  4902. if (ok) {
  4903. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4904. } else {
  4905. if (show_error) {
  4906. check_assignment(c, o, e->type, str_lit("procedure argument"));
  4907. }
  4908. err = CallArgumentError_WrongTypes;
  4909. }
  4910. if (e->flags & EntityFlag_ConstInput) {
  4911. if (o->mode != Addressing_Constant) {
  4912. if (show_error) {
  4913. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4914. }
  4915. err = CallArgumentError_NoneConstantParameter;
  4916. }
  4917. }
  4918. } else if (show_error) {
  4919. check_assignment(c, o, e->type, str_lit("procedure argument"));
  4920. }
  4921. score += s;
  4922. }
  4923. if (o->mode == Addressing_Type && is_type_typeid(e->type)) {
  4924. add_type_info_type(c, o->type);
  4925. add_type_and_value(c, o->expr, Addressing_Value, e->type, exact_value_typeid(o->type));
  4926. } else if (show_error && is_type_untyped(o->type)) {
  4927. update_untyped_expr_type(c, o->expr, e->type, true);
  4928. }
  4929. }
  4930. }
  4931. if (variadic) {
  4932. Type *slice = pt->params->Tuple.variables[pt->variadic_index]->type;
  4933. GB_ASSERT(is_type_slice(slice));
  4934. Type *elem = base_type(slice)->Slice.elem;
  4935. Type *t = elem;
  4936. if (is_type_polymorphic(t)) {
  4937. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  4938. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4939. }
  4940. for_array(operand_index, variadic_operands) {
  4941. Operand &o = variadic_operands[operand_index];
  4942. if (vari_expand) {
  4943. t = slice;
  4944. if (operand_index > 0) {
  4945. if (show_error) {
  4946. error(o.expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  4947. }
  4948. if (data) {
  4949. data->score = score;
  4950. data->result_type = final_proc_type->Proc.results;
  4951. data->gen_entity = gen_entity;
  4952. }
  4953. return CallArgumentError_MultipleVariadicExpand;
  4954. }
  4955. }
  4956. i64 s = 0;
  4957. if (!check_is_assignable_to_with_score(c, &o, t, &s, true)) {
  4958. if (show_error) {
  4959. check_assignment(c, &o, t, str_lit("variadic argument"));
  4960. }
  4961. err = CallArgumentError_WrongTypes;
  4962. } else if (show_error) {
  4963. check_assignment(c, &o, t, str_lit("variadic argument"));
  4964. }
  4965. score += s;
  4966. if (is_type_any(elem)) {
  4967. add_type_info_type(c, o.type);
  4968. }
  4969. if (o.mode == Addressing_Type && is_type_typeid(t)) {
  4970. add_type_info_type(c, o.type);
  4971. add_type_and_value(c, o.expr, Addressing_Value, t, exact_value_typeid(o.type));
  4972. } else if (show_error && is_type_untyped(o.type)) {
  4973. update_untyped_expr_type(c, o.expr, t, true);
  4974. }
  4975. }
  4976. }
  4977. if (data) {
  4978. data->score = score;
  4979. data->result_type = final_proc_type->Proc.results;
  4980. data->gen_entity = gen_entity;
  4981. Ast *proc_lit = nullptr;
  4982. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  4983. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  4984. if (vp && vp->kind == Ast_ProcLit) {
  4985. proc_lit = vp;
  4986. }
  4987. }
  4988. if (proc_lit == nullptr) {
  4989. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  4990. }
  4991. }
  4992. return err;
  4993. }
  4994. if (err) {
  4995. return err;
  4996. }
  4997. auto operands = positional_operands;
  4998. TypeTuple *param_tuple = nullptr;
  4999. if (pt->params != nullptr) {
  5000. param_tuple = &pt->params->Tuple;
  5001. }
  5002. if (operands.count == 0 && param_count_excluding_defaults == 0) {
  5003. err = CallArgumentError_None;
  5004. if (variadic) {
  5005. GB_ASSERT(param_tuple != nullptr && param_tuple->variables.count > 0);
  5006. Type *t = param_tuple->variables[0]->type;
  5007. if (is_type_polymorphic(t)) {
  5008. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5009. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5010. }
  5011. }
  5012. } else {
  5013. i32 error_code = 0;
  5014. if (operands.count < param_count_excluding_defaults) {
  5015. error_code = -1;
  5016. } else if (!variadic && operands.count > param_count) {
  5017. error_code = +1;
  5018. }
  5019. if (error_code != 0) {
  5020. err = CallArgumentError_TooManyArguments;
  5021. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5022. if (error_code < 0) {
  5023. err = CallArgumentError_TooFewArguments;
  5024. err_fmt = "Too few arguments for '%s', expected %td arguments, got %td";
  5025. }
  5026. if (show_error) {
  5027. gbString proc_str = expr_to_string(ce->proc);
  5028. defer (gb_string_free(proc_str));
  5029. error(call, err_fmt, proc_str, param_count_excluding_defaults, operands.count);
  5030. #if 0
  5031. error_line("\t");
  5032. for_array(i, operands) {
  5033. if (i > 0) {
  5034. error_line(", ");
  5035. }
  5036. gbString s = expr_to_string(operands[i].expr);
  5037. error_line("%s", s);
  5038. gb_string_free(s);
  5039. }
  5040. error_line("\n");
  5041. #endif
  5042. }
  5043. } else {
  5044. // NOTE(bill): Generate the procedure type for this generic instance
  5045. if (pt->is_polymorphic && !pt->is_poly_specialized) {
  5046. PolyProcData poly_proc_data = {};
  5047. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &operands, call, &poly_proc_data)) {
  5048. gen_entity = poly_proc_data.gen_entity;
  5049. GB_ASSERT(is_type_proc(gen_entity->type));
  5050. final_proc_type = gen_entity->type;
  5051. } else {
  5052. err = CallArgumentError_WrongTypes;
  5053. }
  5054. }
  5055. GB_ASSERT(is_type_proc(final_proc_type));
  5056. TypeProc *pt = &final_proc_type->Proc;
  5057. GB_ASSERT(pt->params != nullptr);
  5058. auto sig_params = pt->params->Tuple.variables;
  5059. isize operand_index = 0;
  5060. isize max_operand_count = gb_min(param_count, operands.count);
  5061. for (; operand_index < max_operand_count; operand_index++) {
  5062. Entity *e = sig_params[operand_index];
  5063. Type *t = e->type;
  5064. Operand o = operands[operand_index];
  5065. if (o.expr != nullptr) {
  5066. call->viral_state_flags |= o.expr->viral_state_flags;
  5067. }
  5068. if (e->kind == Entity_TypeName) {
  5069. // GB_ASSERT(!variadic);
  5070. if (o.mode == Addressing_Invalid) {
  5071. continue;
  5072. } else if (o.mode != Addressing_Type) {
  5073. if (show_error) {
  5074. error(o.expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5075. }
  5076. err = CallArgumentError_WrongTypes;
  5077. }
  5078. if (are_types_identical(e->type, o.type)) {
  5079. score += assign_score_function(1);
  5080. } else {
  5081. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5082. }
  5083. continue;
  5084. }
  5085. bool param_is_variadic = pt->variadic && pt->variadic_index == operand_index;
  5086. i64 s = 0;
  5087. if (!check_is_assignable_to_with_score(c, &o, t, &s, param_is_variadic)) {
  5088. bool ok = false;
  5089. if (e->flags & EntityFlag_AnyInt) {
  5090. if (is_type_integer(t)) {
  5091. ok = check_is_castable_to(c, &o, t);
  5092. }
  5093. }
  5094. if (ok) {
  5095. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5096. } else {
  5097. if (show_error) {
  5098. check_assignment(c, &o, t, str_lit("argument"));
  5099. }
  5100. // TODO(bill, 2021-05-05): Is this incorrect logic to only fail if there is ambiguity for definite?
  5101. if (o.mode == Addressing_Invalid) {
  5102. err = CallArgumentError_WrongTypes;
  5103. }
  5104. }
  5105. } else if (show_error) {
  5106. check_assignment(c, &o, t, str_lit("argument"));
  5107. }
  5108. score += s;
  5109. if (e->flags & EntityFlag_ConstInput) {
  5110. if (o.mode != Addressing_Constant) {
  5111. if (show_error) {
  5112. error(o.expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5113. }
  5114. err = CallArgumentError_NoneConstantParameter;
  5115. }
  5116. }
  5117. if (o.mode == Addressing_Type && is_type_typeid(e->type)) {
  5118. add_type_info_type(c, o.type);
  5119. add_type_and_value(c, o.expr, Addressing_Value, e->type, exact_value_typeid(o.type));
  5120. } else if (show_error && is_type_untyped(o.type)) {
  5121. update_untyped_expr_type(c, o.expr, t, true);
  5122. }
  5123. }
  5124. if (variadic) {
  5125. bool variadic_expand = false;
  5126. Type *slice = sig_params[param_count]->type;
  5127. GB_ASSERT(is_type_slice(slice));
  5128. Type *elem = base_type(slice)->Slice.elem;
  5129. Type *t = elem;
  5130. if (is_type_polymorphic(t)) {
  5131. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5132. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5133. }
  5134. for (; operand_index < operands.count; operand_index++) {
  5135. Operand o = operands[operand_index];
  5136. if (vari_expand) {
  5137. variadic_expand = true;
  5138. t = slice;
  5139. if (operand_index != param_count) {
  5140. if (show_error) {
  5141. error(o.expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5142. }
  5143. if (data) {
  5144. data->score = score;
  5145. data->result_type = final_proc_type->Proc.results;
  5146. data->gen_entity = gen_entity;
  5147. }
  5148. return CallArgumentError_MultipleVariadicExpand;
  5149. }
  5150. }
  5151. i64 s = 0;
  5152. if (!check_is_assignable_to_with_score(c, &o, t, &s, true)) {
  5153. if (show_error) {
  5154. check_assignment(c, &o, t, str_lit("argument"));
  5155. }
  5156. err = CallArgumentError_WrongTypes;
  5157. } else if (show_error) {
  5158. check_assignment(c, &o, t, str_lit("argument"));
  5159. }
  5160. score += s;
  5161. if (is_type_any(elem)) {
  5162. add_type_info_type(c, o.type);
  5163. }
  5164. if (o.mode == Addressing_Type && is_type_typeid(t)) {
  5165. add_type_info_type(c, o.type);
  5166. add_type_and_value(c, o.expr, Addressing_Value, t, exact_value_typeid(o.type));
  5167. } else if (show_error && is_type_untyped(o.type)) {
  5168. update_untyped_expr_type(c, o.expr, t, true);
  5169. }
  5170. }
  5171. }
  5172. }
  5173. }
  5174. if (data) {
  5175. data->score = score;
  5176. data->result_type = final_proc_type->Proc.results;
  5177. data->gen_entity = gen_entity;
  5178. Ast *proc_lit = nullptr;
  5179. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5180. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5181. if (vp && vp->kind == Ast_ProcLit) {
  5182. proc_lit = vp;
  5183. }
  5184. }
  5185. if (proc_lit == nullptr) {
  5186. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5187. }
  5188. }
  5189. return err;
  5190. }
  5191. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5192. GB_ASSERT(ce != nullptr);
  5193. if (ce->args.count == 0) {
  5194. return false;
  5195. }
  5196. return ce->args[0]->kind == Ast_FieldValue;
  5197. }
  5198. gb_internal CALL_ARGUMENT_CHECKER(check_named_call_arguments) {
  5199. auto operands = positional_operands;
  5200. ast_node(ce, CallExpr, call);
  5201. GB_ASSERT(is_type_proc(proc_type));
  5202. proc_type = base_type(proc_type);
  5203. TypeProc *pt = &proc_type->Proc;
  5204. i64 score = 0;
  5205. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  5206. CallArgumentError err = CallArgumentError_None;
  5207. TEMPORARY_ALLOCATOR_GUARD();
  5208. isize param_count = pt->param_count;
  5209. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5210. auto ordered_operands = array_make<Operand>(temporary_allocator(), param_count);
  5211. defer ({
  5212. for (Operand const &o : ordered_operands) {
  5213. if (o.expr != nullptr) {
  5214. call->viral_state_flags |= o.expr->viral_state_flags;
  5215. }
  5216. }
  5217. });
  5218. if (check_order_of_call_arguments(c, proc_type, call, show_error)) {
  5219. return CallArgumentError_OutOfOrderParameters;
  5220. }
  5221. for_array(i, ce->args) {
  5222. Ast *arg = ce->args[i];
  5223. ast_node(fv, FieldValue, arg);
  5224. if (fv->field->kind != Ast_Ident) {
  5225. if (show_error) {
  5226. gbString expr_str = expr_to_string(fv->field);
  5227. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5228. gb_string_free(expr_str);
  5229. }
  5230. err = CallArgumentError_InvalidFieldValue;
  5231. continue;
  5232. }
  5233. String name = fv->field->Ident.token.string;
  5234. isize index = lookup_procedure_parameter(pt, name);
  5235. if (index < 0) {
  5236. if (show_error) {
  5237. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5238. }
  5239. err = CallArgumentError_ParameterNotFound;
  5240. continue;
  5241. }
  5242. if (visited[index]) {
  5243. if (show_error) {
  5244. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5245. }
  5246. err = CallArgumentError_DuplicateParameter;
  5247. continue;
  5248. }
  5249. visited[index] = true;
  5250. ordered_operands[index] = operands[i];
  5251. }
  5252. // NOTE(bill): Check for default values and missing parameters
  5253. isize param_count_to_check = param_count;
  5254. if (pt->variadic) {
  5255. param_count_to_check--;
  5256. }
  5257. for (isize i = 0; i < param_count_to_check; i++) {
  5258. if (!visited[i]) {
  5259. Entity *e = pt->params->Tuple.variables[i];
  5260. if (is_blank_ident(e->token)) {
  5261. continue;
  5262. }
  5263. if (e->kind == Entity_Variable) {
  5264. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5265. score += assign_score_function(1);
  5266. continue;
  5267. }
  5268. }
  5269. if (show_error) {
  5270. if (e->kind == Entity_TypeName) {
  5271. error(call, "Type parameter '%.*s' is missing in procedure call",
  5272. LIT(e->token.string));
  5273. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5274. // Ignore
  5275. } else {
  5276. gbString str = type_to_string(e->type);
  5277. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5278. LIT(e->token.string), str);
  5279. gb_string_free(str);
  5280. }
  5281. }
  5282. err = CallArgumentError_ParameterMissing;
  5283. }
  5284. }
  5285. Entity *gen_entity = nullptr;
  5286. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5287. PolyProcData poly_proc_data = {};
  5288. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5289. gen_entity = poly_proc_data.gen_entity;
  5290. Type *gept = base_type(gen_entity->type);
  5291. GB_ASSERT(is_type_proc(gept));
  5292. proc_type = gept;
  5293. pt = &gept->Proc;
  5294. } else {
  5295. err = CallArgumentError_WrongTypes;
  5296. }
  5297. }
  5298. for (isize i = 0; i < param_count; i++) {
  5299. Entity *e = pt->params->Tuple.variables[i];
  5300. Operand *o = &ordered_operands[i];
  5301. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5302. if (o->mode == Addressing_Invalid) {
  5303. if (param_is_variadic) {
  5304. Type *slice = e->type;
  5305. GB_ASSERT(is_type_slice(slice));
  5306. Type *elem = base_type(slice)->Slice.elem;
  5307. if (is_type_polymorphic(elem)) {
  5308. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5309. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5310. return err;
  5311. }
  5312. }
  5313. continue;
  5314. }
  5315. if (e->kind == Entity_TypeName) {
  5316. GB_ASSERT(pt->is_polymorphic);
  5317. if (o->mode != Addressing_Type) {
  5318. if (show_error) {
  5319. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5320. }
  5321. err = CallArgumentError_WrongTypes;
  5322. }
  5323. if (are_types_identical(e->type, o->type)) {
  5324. score += assign_score_function(1);
  5325. } else {
  5326. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5327. }
  5328. } else {
  5329. i64 s = 0;
  5330. if (!check_is_assignable_to_with_score(c, o, e->type, &s, param_is_variadic)) {
  5331. bool ok = false;
  5332. if (ok) {
  5333. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5334. } else {
  5335. if (show_error) {
  5336. check_assignment(c, o, e->type, str_lit("procedure argument"));
  5337. }
  5338. err = CallArgumentError_WrongTypes;
  5339. }
  5340. if (e->flags & EntityFlag_ConstInput) {
  5341. if (o->mode != Addressing_Constant) {
  5342. if (show_error) {
  5343. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5344. }
  5345. err = CallArgumentError_NoneConstantParameter;
  5346. }
  5347. }
  5348. } else if (show_error) {
  5349. check_assignment(c, o, e->type, str_lit("procedure argument"));
  5350. }
  5351. score += s;
  5352. }
  5353. if (o->mode == Addressing_Type && is_type_typeid(e->type)) {
  5354. add_type_info_type(c, o->type);
  5355. add_type_and_value(c, o->expr, Addressing_Value, e->type, exact_value_typeid(o->type));
  5356. }
  5357. }
  5358. if (data) {
  5359. data->score = score;
  5360. data->result_type = pt->results;
  5361. data->gen_entity = gen_entity;
  5362. add_type_and_value(c, ce->proc, Addressing_Value, proc_type, {});
  5363. }
  5364. return err;
  5365. }
  5366. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5367. Entity **lhs = nullptr;
  5368. isize lhs_count = -1;
  5369. if (proc_type == nullptr) {
  5370. return nullptr;
  5371. }
  5372. GB_ASSERT(is_type_proc(proc_type));
  5373. TypeProc *pt = &base_type(proc_type)->Proc;
  5374. *is_variadic = pt->variadic;
  5375. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5376. if (pt->params != nullptr) {
  5377. lhs = pt->params->Tuple.variables.data;
  5378. lhs_count = pt->params->Tuple.variables.count;
  5379. }
  5380. } else {
  5381. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5382. if (pt->params == nullptr) {
  5383. lhs_count = 0;
  5384. } else {
  5385. lhs_count = pt->params->Tuple.variables.count;
  5386. }
  5387. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5388. for (isize i = 0; i < lhs_count; i++) {
  5389. Entity *e = pt->params->Tuple.variables[i];
  5390. if (!is_type_polymorphic(e->type)) {
  5391. lhs[i] = e;
  5392. }
  5393. }
  5394. }
  5395. if (lhs_count_) *lhs_count_ = lhs_count;
  5396. return lhs;
  5397. }
  5398. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5399. if (clauses != nullptr) {
  5400. for (Ast *clause : *clauses) {
  5401. Operand o = {};
  5402. check_expr(ctx, &o, clause);
  5403. if (o.mode != Addressing_Constant) {
  5404. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5405. if (print_err && call_expr) error(call_expr, "at caller location");
  5406. return false;
  5407. } else if (o.value.kind != ExactValue_Bool) {
  5408. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5409. if (print_err && call_expr) error(call_expr, "at caller location");
  5410. return false;
  5411. } else if (!o.value.value_bool) {
  5412. if (print_err) {
  5413. ERROR_BLOCK();
  5414. gbString str = expr_to_string(clause);
  5415. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5416. gb_string_free(str);
  5417. if (scope != nullptr) {
  5418. isize print_count = 0;
  5419. for (auto const &entry : scope->elements) {
  5420. Entity *e = entry.value;
  5421. switch (e->kind) {
  5422. case Entity_TypeName: {
  5423. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5424. gbString str = type_to_string(e->type);
  5425. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5426. gb_string_free(str);
  5427. print_count += 1;
  5428. break;
  5429. }
  5430. case Entity_Constant: {
  5431. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5432. gbString str = exact_value_to_string(e->Constant.value);
  5433. if (is_type_untyped(e->type)) {
  5434. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5435. } else {
  5436. gbString t = type_to_string(e->type);
  5437. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5438. gb_string_free(t);
  5439. }
  5440. gb_string_free(str);
  5441. print_count += 1;
  5442. break;
  5443. }
  5444. }
  5445. }
  5446. }
  5447. if (call_expr) error(call_expr, "at caller location");
  5448. }
  5449. return false;
  5450. }
  5451. }
  5452. }
  5453. return true;
  5454. }
  5455. gb_internal CallArgumentError check_order_of_call_arguments(CheckerContext *c, Type *proc_type, Ast *call, bool show_error) {
  5456. CallArgumentError err = CallArgumentError_None;
  5457. if (proc_type == nullptr || !is_type_proc(proc_type)) {
  5458. // ignore for the time being
  5459. return err;
  5460. }
  5461. ast_node(ce, CallExpr, call);
  5462. if (!is_call_expr_field_value(ce)) {
  5463. return err;
  5464. }
  5465. TypeProc *pt = &base_type(proc_type)->Proc;
  5466. isize param_count = pt->param_count;
  5467. TEMPORARY_ALLOCATOR_GUARD();
  5468. auto arg_order_indices = slice_make<isize>(temporary_allocator(), ce->args.count);
  5469. auto visited = slice_make<bool>(temporary_allocator(), param_count);
  5470. for_array(i, ce->args) {
  5471. Ast *arg = ce->args[i];
  5472. ast_node(fv, FieldValue, arg);
  5473. Ast *field = fv->field;
  5474. String name = {};
  5475. if (field != nullptr && field->kind == Ast_Ident) {
  5476. name = field->Ident.token.string;
  5477. } else {
  5478. err = CallArgumentError_InvalidFieldValue;
  5479. if (show_error) {
  5480. gbString s = expr_to_string(arg);
  5481. error(arg, "Invalid parameter name '%s' in procedure call", s);
  5482. gb_string_free(s);
  5483. }
  5484. }
  5485. isize index = lookup_procedure_parameter(pt, name);
  5486. if (index < 0) {
  5487. err = CallArgumentError_InvalidFieldValue;
  5488. if (show_error) {
  5489. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5490. }
  5491. }
  5492. if (visited[index]) {
  5493. err = CallArgumentError_DuplicateParameter;
  5494. if (show_error) {
  5495. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5496. }
  5497. }
  5498. arg_order_indices[i] = index;
  5499. }
  5500. if (err) {
  5501. return err;
  5502. }
  5503. for (isize i = 0; i < arg_order_indices.count-1; i++) {
  5504. isize a = arg_order_indices[i+0];
  5505. isize b = arg_order_indices[i+1];
  5506. GB_ASSERT(a != b);
  5507. if (a > b) {
  5508. err = CallArgumentError_OutOfOrderParameters;
  5509. if (show_error) {
  5510. Ast *arg_a = ce->args[i+0];
  5511. Ast *arg_b = ce->args[i+1];
  5512. isize curr_a_order = a;
  5513. for (isize j = i; j >= 0; j--) {
  5514. isize j_order = arg_order_indices[j];
  5515. if (b < j_order && j_order < curr_a_order) {
  5516. curr_a_order = j_order;
  5517. arg_a = ce->args[j];
  5518. }
  5519. }
  5520. ast_node(fv_a, FieldValue, arg_a);
  5521. ast_node(fv_b, FieldValue, arg_b);
  5522. gbString s_a = expr_to_string(fv_a->field);
  5523. gbString s_b = expr_to_string(fv_b->field);
  5524. error(arg_b, "Parameter names out of order, expected '%s' to be called before '%s'", s_b, s_a);
  5525. gb_string_free(s_b);
  5526. gb_string_free(s_a);
  5527. }
  5528. }
  5529. }
  5530. return err;
  5531. }
  5532. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5533. bool success = true;
  5534. type = base_type(type);
  5535. if (named_args.count > 0) {
  5536. TypeProc *pt = nullptr;
  5537. if (is_type_proc(type)) {
  5538. pt = &type->Proc;
  5539. }
  5540. for_array(i, named_args) {
  5541. Ast *arg = named_args[i];
  5542. if (arg->kind != Ast_FieldValue) {
  5543. if (show_error) {
  5544. error(arg, "Expected a 'field = value'");
  5545. }
  5546. return false;
  5547. }
  5548. ast_node(fv, FieldValue, arg);
  5549. if (fv->field->kind != Ast_Ident) {
  5550. if (show_error) {
  5551. gbString expr_str = expr_to_string(fv->field);
  5552. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5553. gb_string_free(expr_str);
  5554. }
  5555. success = false;
  5556. continue;
  5557. }
  5558. String key = fv->field->Ident.token.string;
  5559. Ast *value = fv->value;
  5560. Type *type_hint = nullptr;
  5561. if (pt) {
  5562. isize param_index = lookup_procedure_parameter(pt, key);
  5563. if (param_index < 0) {
  5564. if (show_error) {
  5565. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5566. }
  5567. success = false;
  5568. continue;
  5569. }
  5570. // bool prev_visited = visited[param_index];
  5571. // if (prev_visited) {
  5572. // error(value, "Duplicate parameter named '%.*s' in procedure call", LIT(key));
  5573. // success = false;
  5574. // }
  5575. Entity *e = pt->params->Tuple.variables[param_index];
  5576. if (!is_type_polymorphic(e->type)) {
  5577. type_hint = e->type;
  5578. }
  5579. }
  5580. Operand o = {};
  5581. check_expr_with_type_hint(c, &o, value, type_hint);
  5582. if (o.mode == Addressing_Invalid) {
  5583. success = false;
  5584. }
  5585. array_add(named_operands, o);
  5586. }
  5587. }
  5588. return success;
  5589. }
  5590. gb_internal CallArgumentData check_call_arguments_new_and_improved_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5591. ast_node(ce, CallExpr, call);
  5592. GB_ASSERT(ce->split_args != nullptr);
  5593. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5594. Slice<Ast *> const &named_args = ce->split_args->named;
  5595. CallArgumentData data = {};
  5596. data.result_type = t_invalid;
  5597. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5598. auto procs = proc_group_entities_cloned(c, *operand);
  5599. if (procs.count > 1) {
  5600. isize max_arg_count = positional_args.count + named_args.count;
  5601. for (Ast *arg : positional_args) {
  5602. // NOTE(bill): The only thing that may have multiple values
  5603. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5604. arg = strip_or_return_expr(arg);
  5605. if (arg && arg->kind == Ast_CallExpr) {
  5606. max_arg_count = ISIZE_MAX;
  5607. break;
  5608. }
  5609. }
  5610. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5611. // NOTE(bill): The only thing that may have multiple values
  5612. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5613. if (arg->kind == Ast_FieldValue) {
  5614. arg = strip_or_return_expr(arg->FieldValue.value);
  5615. if (arg && arg->kind == Ast_CallExpr) {
  5616. max_arg_count = ISIZE_MAX;
  5617. break;
  5618. }
  5619. }
  5620. }
  5621. // ignore named arguments first
  5622. for (Ast *arg : named_args) {
  5623. if (arg->kind != Ast_FieldValue) {
  5624. continue;
  5625. }
  5626. ast_node(fv, FieldValue, arg);
  5627. if (fv->field->kind != Ast_Ident) {
  5628. continue;
  5629. }
  5630. String key = fv->field->Ident.token.string;
  5631. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5632. Type *t = procs[proc_index]->type;
  5633. if (is_type_proc(t)) {
  5634. isize param_index = lookup_procedure_parameter(t, key);
  5635. if (param_index < 0) {
  5636. array_unordered_remove(&procs, proc_index);
  5637. }
  5638. }
  5639. }
  5640. }
  5641. if (procs.count == 0) {
  5642. // if any of the named arguments are wrong, the `procs` will be empty
  5643. // just start from scratch
  5644. array_free(&procs);
  5645. procs = proc_group_entities_cloned(c, *operand);
  5646. }
  5647. // filter by positional argument length
  5648. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5649. Entity *proc = procs[proc_index];
  5650. Type *pt = base_type(proc->type);
  5651. if (!(pt != nullptr && is_type_proc(pt))) {
  5652. proc_index++;
  5653. continue;
  5654. }
  5655. isize param_count = 0;
  5656. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5657. if (param_count_excluding_defaults > max_arg_count) {
  5658. array_unordered_remove(&procs, proc_index);
  5659. continue;
  5660. }
  5661. proc_index++;
  5662. }
  5663. }
  5664. Entity **lhs = nullptr;
  5665. isize lhs_count = -1;
  5666. bool is_variadic = false;
  5667. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5668. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5669. defer (array_free(&positional_operands));
  5670. defer (array_free(&named_operands));
  5671. if (procs.count == 1) {
  5672. Ast *ident = operand->expr;
  5673. while (ident->kind == Ast_SelectorExpr) {
  5674. Ast *s = ident->SelectorExpr.selector;
  5675. ident = s;
  5676. }
  5677. Entity *e = procs[0];
  5678. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5679. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5680. if (!check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5681. return data;
  5682. }
  5683. CallArgumentError err = check_call_arguments_internal(c, call, e->type, e, positional_operands, named_operands, CallArgumentMode_ShowErrors, &data);
  5684. if (err != CallArgumentError_None) {
  5685. // handle error
  5686. }
  5687. Type *proc_type = base_type(operand->type);
  5688. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5689. add_entity_use(c, ident, entity_to_use);
  5690. if (entity_to_use != nullptr) {
  5691. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5692. proc_type = base_type(entity_to_use->type);
  5693. }
  5694. if (proc_type && proc_type->kind == Type_Proc) {
  5695. data.result_type = proc_type->Proc.results;
  5696. add_type_and_value(c, operand->expr, operand->mode, proc_type, operand->value);
  5697. } else if (err == CallArgumentError_None) {
  5698. data.result_type = nullptr;
  5699. }
  5700. if (data.gen_entity != nullptr) {
  5701. Entity *e = data.gen_entity;
  5702. DeclInfo *decl = data.gen_entity->decl_info;
  5703. CheckerContext ctx = *c;
  5704. ctx.scope = decl->scope;
  5705. ctx.decl = decl;
  5706. ctx.proc_name = e->token.string;
  5707. ctx.curr_proc_decl = decl;
  5708. ctx.curr_proc_sig = e->type;
  5709. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5710. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5711. decl->where_clauses_evaluated = true;
  5712. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5713. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5714. }
  5715. }
  5716. return data;
  5717. }
  5718. {
  5719. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5720. // where the same positional parameter has the same type value (and ellipsis)
  5721. bool proc_arg_count_all_equal = true;
  5722. isize proc_arg_count = -1;
  5723. for (Entity *p : procs) {
  5724. Type *pt = base_type(p->type);
  5725. if (pt != nullptr && is_type_proc(pt)) {
  5726. if (proc_arg_count < 0) {
  5727. proc_arg_count = pt->Proc.param_count;
  5728. } else {
  5729. if (proc_arg_count != pt->Proc.param_count) {
  5730. proc_arg_count_all_equal = false;
  5731. break;
  5732. }
  5733. }
  5734. }
  5735. }
  5736. if (proc_arg_count >= 0 && proc_arg_count_all_equal) {
  5737. lhs_count = proc_arg_count;
  5738. if (lhs_count > 0) {
  5739. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5740. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5741. Entity *e = nullptr;
  5742. for (Entity *p : procs) {
  5743. Type *pt = base_type(p->type);
  5744. if (!(pt != nullptr && is_type_proc(pt))) {
  5745. continue;
  5746. }
  5747. if (e == nullptr) {
  5748. e = pt->Proc.params->Tuple.variables[param_index];
  5749. } else {
  5750. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5751. if (e == f) {
  5752. continue;
  5753. }
  5754. if (are_types_identical(e->type, f->type)) {
  5755. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5756. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5757. if (ee == fe) {
  5758. continue;
  5759. }
  5760. }
  5761. // NOTE(bill): Entities are not close enough to be used
  5762. e = nullptr;
  5763. break;
  5764. }
  5765. }
  5766. lhs[param_index] = e;
  5767. }
  5768. }
  5769. }
  5770. }
  5771. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5772. for_array(i, named_args) {
  5773. Ast *arg = named_args[i];
  5774. if (arg->kind != Ast_FieldValue) {
  5775. error(arg, "Expected a 'field = value'");
  5776. return data;
  5777. }
  5778. ast_node(fv, FieldValue, arg);
  5779. if (fv->field->kind != Ast_Ident) {
  5780. gbString expr_str = expr_to_string(fv->field);
  5781. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5782. gb_string_free(expr_str);
  5783. return data;
  5784. }
  5785. String key = fv->field->Ident.token.string;
  5786. Ast *value = fv->value;
  5787. Type *type_hint = nullptr;
  5788. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5789. Entity *e = lhs[lhs_idx];
  5790. if (e != nullptr && e->token.string == key &&
  5791. !is_type_polymorphic(e->type)) {
  5792. type_hint = e->type;
  5793. break;
  5794. }
  5795. }
  5796. Operand o = {};
  5797. check_expr_with_type_hint(c, &o, value, type_hint);
  5798. array_add(&named_operands, o);
  5799. }
  5800. gb_free(heap_allocator(), lhs);
  5801. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5802. defer (array_free(&valids));
  5803. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5804. defer (array_free(&proc_entities));
  5805. for (Entity *proc : procs) {
  5806. array_add(&proc_entities, proc);
  5807. }
  5808. gbString expr_name = expr_to_string(operand->expr);
  5809. defer (gb_string_free(expr_name));
  5810. for_array(i, procs) {
  5811. Entity *p = procs[i];
  5812. Type *pt = base_type(p->type);
  5813. if (pt != nullptr && is_type_proc(pt)) {
  5814. CallArgumentError err = CallArgumentError_None;
  5815. CallArgumentData data = {};
  5816. CheckerContext ctx = *c;
  5817. ctx.no_polymorphic_errors = true;
  5818. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5819. ctx.hide_polymorphic_errors = true;
  5820. err = check_call_arguments_internal(&ctx, call, pt, p, positional_operands, named_operands, CallArgumentMode_NoErrors, &data);
  5821. if (err != CallArgumentError_None) {
  5822. continue;
  5823. }
  5824. isize index = i;
  5825. if (data.gen_entity != nullptr) {
  5826. Entity *e = data.gen_entity;
  5827. DeclInfo *decl = data.gen_entity->decl_info;
  5828. ctx.scope = decl->scope;
  5829. ctx.decl = decl;
  5830. ctx.proc_name = e->token.string;
  5831. ctx.curr_proc_decl = decl;
  5832. ctx.curr_proc_sig = e->type;
  5833. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5834. if (!evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, false)) {
  5835. continue;
  5836. }
  5837. array_add(&proc_entities, data.gen_entity);
  5838. index = proc_entities.count-1;
  5839. }
  5840. ValidIndexAndScore item = {};
  5841. item.index = index;
  5842. item.score = data.score;
  5843. array_add(&valids, item);
  5844. }
  5845. }
  5846. if (valids.count > 1) {
  5847. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  5848. i64 best_score = valids[0].score;
  5849. Entity *best_entity = proc_entities[valids[0].index];
  5850. GB_ASSERT(best_entity != nullptr);
  5851. for (isize i = 1; i < valids.count; i++) {
  5852. if (best_score > valids[i].score) {
  5853. valids.count = i;
  5854. break;
  5855. }
  5856. if (best_entity == proc_entities[valids[i].index]) {
  5857. valids.count = i;
  5858. break;
  5859. }
  5860. }
  5861. }
  5862. auto print_argument_types = [&]() {
  5863. error_line("\tGiven argument types: (");
  5864. isize i = 0;
  5865. for (Operand const &o : positional_operands) {
  5866. if (i++ > 0) error_line(", ");
  5867. gbString type = type_to_string(o.type);
  5868. defer (gb_string_free(type));
  5869. error_line("%s", type);
  5870. }
  5871. for (Operand const &o : named_operands) {
  5872. if (i++ > 0) error_line(", ");
  5873. gbString type = type_to_string(o.type);
  5874. defer (gb_string_free(type));
  5875. if (i < ce->split_args->named.count) {
  5876. Ast *named_field = ce->split_args->named[i];
  5877. ast_node(fv, FieldValue, named_field);
  5878. gbString field = expr_to_string(fv->field);
  5879. defer (gb_string_free(field));
  5880. error_line("%s = %s", field, type);
  5881. } else {
  5882. error_line("%s", type);
  5883. }
  5884. }
  5885. error_line(")\n");
  5886. };
  5887. if (valids.count == 0) {
  5888. begin_error_block();
  5889. defer (end_error_block());
  5890. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5891. if (positional_operands.count == 0 && named_operands.count == 0) {
  5892. error_line("\tNo given arguments\n");
  5893. } else {
  5894. print_argument_types();
  5895. }
  5896. if (procs.count > 0) {
  5897. error_line("Did you mean to use one of the following:\n");
  5898. }
  5899. for (Entity *proc : procs) {
  5900. TokenPos pos = proc->token.pos;
  5901. Type *t = base_type(proc->type);
  5902. if (t == t_invalid) continue;
  5903. GB_ASSERT(t->kind == Type_Proc);
  5904. gbString pt;
  5905. defer (gb_string_free(pt));
  5906. if (t->Proc.node != nullptr) {
  5907. pt = expr_to_string(t->Proc.node);
  5908. } else {
  5909. pt = type_to_string(t);
  5910. }
  5911. String prefix = {};
  5912. String prefix_sep = {};
  5913. if (proc->pkg) {
  5914. prefix = proc->pkg->name;
  5915. prefix_sep = str_lit(".");
  5916. }
  5917. String name = proc->token.string;
  5918. char const *sep = "::";
  5919. if (proc->kind == Entity_Variable) {
  5920. sep = ":=";
  5921. }
  5922. error_line("\t%.*s%.*s%.*s %s %s at %s\n", LIT(prefix), LIT(prefix_sep), LIT(name), sep, pt, token_pos_to_string(pos));
  5923. }
  5924. if (procs.count > 0) {
  5925. error_line("\n");
  5926. }
  5927. data.result_type = t_invalid;
  5928. } else if (valids.count > 1) {
  5929. begin_error_block();
  5930. defer (end_error_block());
  5931. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5932. print_argument_types();
  5933. for (isize i = 0; i < valids.count; i++) {
  5934. Entity *proc = proc_entities[valids[i].index];
  5935. GB_ASSERT(proc != nullptr);
  5936. TokenPos pos = proc->token.pos;
  5937. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5938. gbString pt = nullptr;
  5939. defer (gb_string_free(pt));
  5940. if (t->Proc.node != nullptr) {
  5941. pt = expr_to_string(t->Proc.node);
  5942. } else {
  5943. pt = type_to_string(t);
  5944. }
  5945. String name = proc->token.string;
  5946. char const *sep = "::";
  5947. if (proc->kind == Entity_Variable) {
  5948. sep = ":=";
  5949. }
  5950. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5951. if (proc->decl_info->proc_lit != nullptr) {
  5952. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5953. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5954. if (pl->where_token.kind != Token_Invalid) {
  5955. error_line("\n\t\twhere ");
  5956. for_array(j, pl->where_clauses) {
  5957. Ast *clause = pl->where_clauses[j];
  5958. if (j != 0) {
  5959. error_line("\t\t ");
  5960. }
  5961. gbString str = expr_to_string(clause);
  5962. error_line("%s", str);
  5963. gb_string_free(str);
  5964. if (j != pl->where_clauses.count-1) {
  5965. error_line(",");
  5966. }
  5967. }
  5968. error_line("\n\t");
  5969. }
  5970. }
  5971. error_line("at %s\n", token_pos_to_string(pos));
  5972. }
  5973. data.result_type = t_invalid;
  5974. } else {
  5975. GB_ASSERT(valids.count == 1);
  5976. Ast *ident = operand->expr;
  5977. while (ident->kind == Ast_SelectorExpr) {
  5978. Ast *s = ident->SelectorExpr.selector;
  5979. ident = s;
  5980. }
  5981. Entity *e = proc_entities[valids[0].index];
  5982. GB_ASSERT(e != nullptr);
  5983. Array<Operand> named_operands = {};
  5984. Type *proc_type = e->type;
  5985. CallArgumentData data = {};
  5986. CallArgumentError err = check_call_arguments_internal(c, call, proc_type, e, positional_operands, named_operands, CallArgumentMode_ShowErrors, &data);
  5987. gb_unused(err);
  5988. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5989. add_entity_use(c, ident, entity_to_use);
  5990. if (entity_to_use != nullptr) {
  5991. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5992. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5993. }
  5994. if (data.gen_entity != nullptr) {
  5995. Entity *e = data.gen_entity;
  5996. DeclInfo *decl = data.gen_entity->decl_info;
  5997. CheckerContext ctx = *c;
  5998. ctx.scope = decl->scope;
  5999. ctx.decl = decl;
  6000. ctx.proc_name = e->token.string;
  6001. ctx.curr_proc_decl = decl;
  6002. ctx.curr_proc_sig = e->type;
  6003. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6004. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  6005. decl->where_clauses_evaluated = true;
  6006. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6007. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6008. }
  6009. }
  6010. return data;
  6011. }
  6012. return data;
  6013. }
  6014. gb_internal CallArgumentData check_call_arguments_new_and_improved(CheckerContext *c, Operand *operand, Ast *call) {
  6015. Type *proc_type = nullptr;
  6016. CallArgumentData data = {};
  6017. data.result_type = t_invalid;
  6018. proc_type = base_type(operand->type);
  6019. TypeProc *pt = nullptr;
  6020. if (proc_type) {
  6021. pt = &proc_type->Proc;
  6022. }
  6023. TEMPORARY_ALLOCATOR_GUARD();
  6024. ast_node(ce, CallExpr, call);
  6025. bool any_failure = false;
  6026. // bool vari_expand = (ce->ellipsis.pos.line != 0);
  6027. // Split positional and named args into separate arrays/slices
  6028. Slice<Ast *> positional_args = {};
  6029. Slice<Ast *> named_args = {};
  6030. if (ce->split_args == nullptr) {
  6031. positional_args = ce->args;
  6032. for (isize i = 0; i < ce->args.count; i++) {
  6033. Ast *arg = ce->args.data[i];
  6034. if (arg->kind == Ast_FieldValue) {
  6035. positional_args.count = i;
  6036. break;
  6037. }
  6038. }
  6039. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6040. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6041. split_args->positional = positional_args;
  6042. split_args->named = named_args;
  6043. ce->split_args = split_args;
  6044. } else {
  6045. positional_args = ce->split_args->positional;
  6046. named_args = ce->split_args->named;
  6047. }
  6048. if (operand->mode == Addressing_ProcGroup) {
  6049. return check_call_arguments_new_and_improved_proc_group(c, operand, call);
  6050. }
  6051. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6052. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6053. defer (array_free(&positional_operands));
  6054. defer (array_free(&named_operands));
  6055. Slice<bool> visited = {};
  6056. if (positional_args.count > 0) {
  6057. isize lhs_count = -1;
  6058. bool is_variadic = false;
  6059. Entity **lhs = nullptr;
  6060. if (pt != nullptr) {
  6061. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6062. } else if (operand->mode == Addressing_ProcGroup) {
  6063. // TODO
  6064. }
  6065. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6066. }
  6067. if (named_args.count > 0) {
  6068. for_array(i, named_args) {
  6069. Ast *arg = named_args[i];
  6070. if (arg->kind != Ast_FieldValue) {
  6071. error(arg, "Expected a 'field = value'");
  6072. return data;
  6073. }
  6074. ast_node(fv, FieldValue, arg);
  6075. if (fv->field->kind != Ast_Ident) {
  6076. gbString expr_str = expr_to_string(fv->field);
  6077. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6078. any_failure = true;
  6079. gb_string_free(expr_str);
  6080. continue;
  6081. }
  6082. String key = fv->field->Ident.token.string;
  6083. Ast *value = fv->value;
  6084. isize param_index = lookup_procedure_parameter(pt, key);
  6085. Type *type_hint = nullptr;
  6086. if (param_index >= 0) {
  6087. Entity *e = pt->params->Tuple.variables[param_index];
  6088. type_hint = e->type;
  6089. }
  6090. Operand o = {};
  6091. check_expr_with_type_hint(c, &o, value, type_hint);
  6092. if (o.mode == Addressing_Invalid) {
  6093. any_failure = true;
  6094. }
  6095. array_add(&named_operands, o);
  6096. }
  6097. }
  6098. if (!any_failure) {
  6099. Ast *ident = operand->expr;
  6100. while (ident->kind == Ast_SelectorExpr) {
  6101. Ast *s = ident->SelectorExpr.selector;
  6102. ident = s;
  6103. }
  6104. Entity *e = entity_of_node(ident);
  6105. TokenPos pos = ast_token(call).pos;
  6106. CallArgumentError err = check_call_arguments_internal(c, call, proc_type, e, positional_operands, named_operands, CallArgumentMode_ShowErrors, &data);
  6107. gb_unused(err);
  6108. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6109. add_entity_use(c, ident, entity_to_use);
  6110. if (entity_to_use != nullptr) {
  6111. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  6112. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  6113. }
  6114. if (data.gen_entity != nullptr) {
  6115. Entity *e = data.gen_entity;
  6116. DeclInfo *decl = data.gen_entity->decl_info;
  6117. CheckerContext ctx = *c;
  6118. ctx.scope = decl->scope;
  6119. ctx.decl = decl;
  6120. ctx.proc_name = e->token.string;
  6121. ctx.curr_proc_decl = decl;
  6122. ctx.curr_proc_sig = e->type;
  6123. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6124. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  6125. decl->where_clauses_evaluated = true;
  6126. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6127. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6128. }
  6129. if (is_type_proc(data.gen_entity->type)) {
  6130. Type *t = base_type(entity_to_use->type);
  6131. // GB_ASSERT_MSG(!is_type_polymorphic(t), "%s", expr_to_string(call));
  6132. data.result_type = t->Proc.results;
  6133. }
  6134. }
  6135. } else if (pt) {
  6136. data.result_type = pt->results;
  6137. }
  6138. return data;
  6139. }
  6140. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6141. if (operand->mode == Addressing_ProcGroup) {
  6142. Array<Entity *> procs = proc_group_entities(c, *operand);
  6143. bool all_non_poly = true;
  6144. for (Entity *e : procs) {
  6145. if (is_type_polymorphic(e->type)) {
  6146. all_non_poly = false;
  6147. break;
  6148. }
  6149. }
  6150. if (true) {
  6151. return check_call_arguments_new_and_improved(c, operand, call);
  6152. }
  6153. } else {
  6154. return check_call_arguments_new_and_improved(c, operand, call);
  6155. }
  6156. ast_node(ce, CallExpr, call);
  6157. CallArgumentCheckerType *call_checker = check_call_arguments_internal;
  6158. Array<Operand> operands = {};
  6159. defer (array_free(&operands));
  6160. Type *result_type = t_invalid;
  6161. Type *proc_type = base_type(operand->type);
  6162. Slice<Ast *> const &args = ce->args;
  6163. if (is_call_expr_field_value(ce)) {
  6164. Type *ptype = nullptr;
  6165. bool single_case = true;
  6166. if (operand->mode == Addressing_ProcGroup) {
  6167. single_case = false;
  6168. Array<Entity *> procs = proc_group_entities(c, *operand);
  6169. if (procs.count == 1) {
  6170. ptype = procs[0]->type;
  6171. single_case = true;
  6172. }
  6173. } else {
  6174. ptype = proc_type;
  6175. }
  6176. if (check_order_of_call_arguments(c, ptype, call, true)) {
  6177. CallArgumentData data = {};
  6178. data.result_type = t_invalid;
  6179. if (ptype && is_type_proc(ptype) && !is_type_polymorphic(ptype)) {
  6180. data.result_type = reduce_tuple_to_single_type(ptype->Proc.results);
  6181. }
  6182. return data;
  6183. }
  6184. call_checker = check_named_call_arguments;
  6185. operands = array_make<Operand>(heap_allocator(), args.count);
  6186. // NOTE(bill): This is give type hints for the named parameters
  6187. // in order to improve the type inference system
  6188. StringMap<Type *> type_hint_map = {}; // Key: String
  6189. string_map_init(&type_hint_map, 2*args.count);
  6190. defer (string_map_destroy(&type_hint_map));
  6191. if (single_case) {
  6192. Type *bptype = base_type(ptype);
  6193. if (is_type_proc(bptype)) {
  6194. TypeProc *pt = &bptype->Proc;
  6195. TypeTuple *param_tuple = nullptr;
  6196. if (pt->params != nullptr) {
  6197. param_tuple = &pt->params->Tuple;
  6198. }
  6199. if (param_tuple != nullptr) {
  6200. for (Entity *e : param_tuple->variables) {
  6201. if (is_blank_ident(e->token)) {
  6202. continue;
  6203. }
  6204. string_map_set(&type_hint_map, e->token.string, e->type);
  6205. }
  6206. }
  6207. }
  6208. } else {
  6209. Array<Entity *> procs = proc_group_entities(c, *operand);
  6210. for (Entity *proc : procs) {
  6211. Type *proc_type = base_type(proc->type);
  6212. if (is_type_proc(proc_type)) {
  6213. TypeProc *pt = &proc_type->Proc;
  6214. TypeTuple *param_tuple = nullptr;
  6215. if (pt->params != nullptr) {
  6216. param_tuple = &pt->params->Tuple;
  6217. }
  6218. if (param_tuple == nullptr) {
  6219. continue;
  6220. }
  6221. for (Entity *e : param_tuple->variables) {
  6222. if (is_blank_ident(e->token)) {
  6223. continue;
  6224. }
  6225. StringHashKey key = string_hash_string(e->token.string);
  6226. Type **found = string_map_get(&type_hint_map, key);
  6227. if (found) {
  6228. Type *t = *found;
  6229. if (t == nullptr) {
  6230. // NOTE(bill): Ambiguous named parameter across all types
  6231. continue;
  6232. }
  6233. if (are_types_identical(t, e->type)) {
  6234. // NOTE(bill): No need to set again
  6235. } else {
  6236. // NOTE(bill): Ambiguous named parameter across all types so set it to a nullptr
  6237. string_map_set(&type_hint_map, key, cast(Type *)nullptr);
  6238. }
  6239. } else {
  6240. string_map_set(&type_hint_map, key, e->type);
  6241. }
  6242. }
  6243. }
  6244. }
  6245. }
  6246. for_array(i, args) {
  6247. Ast *arg = args[i];
  6248. ast_node(fv, FieldValue, arg);
  6249. Ast *field = fv->field;
  6250. Type *type_hint = nullptr;
  6251. if (field != nullptr && field->kind == Ast_Ident) {
  6252. String key = field->Ident.token.string;
  6253. Type **found = string_map_get(&type_hint_map, key);
  6254. if (found) {
  6255. type_hint = *found;
  6256. }
  6257. }
  6258. check_expr_or_type(c, &operands[i], fv->value, type_hint);
  6259. }
  6260. } else {
  6261. operands = array_make<Operand>(heap_allocator(), 0, 2*args.count);
  6262. Entity **lhs = nullptr;
  6263. isize lhs_count = -1;
  6264. bool is_variadic = false;
  6265. if (proc_type != nullptr && is_type_proc(proc_type)) {
  6266. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6267. }
  6268. if (operand->mode != Addressing_ProcGroup) {
  6269. check_unpack_arguments(c, lhs, lhs_count, &operands, args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6270. }
  6271. }
  6272. for (Operand const &o : operands) {
  6273. check_no_copy_assignment(o, str_lit("procedure call expression"));
  6274. }
  6275. if (operand->mode == Addressing_ProcGroup) {
  6276. check_entity_decl(c, operand->proc_group, nullptr, nullptr);
  6277. auto procs = proc_group_entities_cloned(c, *operand);
  6278. if (procs.count > 1) {
  6279. isize max_arg_count = args.count;
  6280. for (Ast *arg : args) {
  6281. // NOTE(bill): The only thing that may have multiple values
  6282. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6283. arg = strip_or_return_expr(arg);
  6284. if (arg && arg->kind == Ast_CallExpr) {
  6285. max_arg_count = ISIZE_MAX;
  6286. break;
  6287. }
  6288. }
  6289. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  6290. Entity *proc = procs[proc_index];
  6291. Type *pt = base_type(proc->type);
  6292. if (!(pt != nullptr && is_type_proc(pt))) {
  6293. proc_index++;
  6294. continue;
  6295. }
  6296. isize param_count = 0;
  6297. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  6298. if (param_count_excluding_defaults > max_arg_count) {
  6299. array_unordered_remove(&procs, proc_index);
  6300. } else {
  6301. proc_index++;
  6302. }
  6303. }
  6304. }
  6305. if (procs.count == 1) {
  6306. Ast *ident = operand->expr;
  6307. while (ident->kind == Ast_SelectorExpr) {
  6308. Ast *s = ident->SelectorExpr.selector;
  6309. ident = s;
  6310. }
  6311. Entity *e = procs[0];
  6312. Entity **lhs = nullptr;
  6313. isize lhs_count = -1;
  6314. bool is_variadic = false;
  6315. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  6316. check_unpack_arguments(c, lhs, lhs_count, &operands, args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6317. Array<Operand> named_operands = {};
  6318. CallArgumentData data = {};
  6319. CallArgumentError err = call_checker(c, call, e->type, e, operands, named_operands, CallArgumentMode_ShowErrors, &data);
  6320. if (err != CallArgumentError_None) {
  6321. // handle error
  6322. }
  6323. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6324. add_entity_use(c, ident, entity_to_use);
  6325. if (entity_to_use != nullptr) {
  6326. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  6327. }
  6328. return data;
  6329. }
  6330. Entity **lhs = nullptr;
  6331. isize lhs_count = -1;
  6332. {
  6333. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6334. // where the same positional parameter has the same type value (and ellipsis)
  6335. bool proc_arg_count_all_equal = true;
  6336. isize proc_arg_count = -1;
  6337. for (Entity *p : procs) {
  6338. Type *pt = base_type(p->type);
  6339. if (pt != nullptr && is_type_proc(pt)) {
  6340. if (proc_arg_count < 0) {
  6341. proc_arg_count = pt->Proc.param_count;
  6342. } else {
  6343. if (proc_arg_count != pt->Proc.param_count) {
  6344. proc_arg_count_all_equal = false;
  6345. break;
  6346. }
  6347. }
  6348. }
  6349. }
  6350. if (proc_arg_count >= 0 && proc_arg_count_all_equal) {
  6351. lhs_count = proc_arg_count;
  6352. if (lhs_count > 0) {
  6353. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6354. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6355. Entity *e = nullptr;
  6356. for (Entity *p : procs) {
  6357. Type *pt = base_type(p->type);
  6358. if (pt != nullptr && is_type_proc(pt)) {
  6359. if (e == nullptr) {
  6360. e = pt->Proc.params->Tuple.variables[param_index];
  6361. } else {
  6362. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6363. if (e == f) {
  6364. continue;
  6365. }
  6366. if (are_types_identical(e->type, f->type)) {
  6367. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6368. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6369. if (ee == fe) {
  6370. continue;
  6371. }
  6372. }
  6373. // NOTE(bill): Entities are not close enough to be used
  6374. e = nullptr;
  6375. break;
  6376. }
  6377. }
  6378. }
  6379. lhs[param_index] = e;
  6380. }
  6381. }
  6382. }
  6383. }
  6384. check_unpack_arguments(c, lhs, lhs_count, &operands, args, UnpackFlag_None);
  6385. if (lhs != nullptr) {
  6386. gb_free(heap_allocator(), lhs);
  6387. }
  6388. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6389. defer (array_free(&valids));
  6390. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6391. defer (array_free(&proc_entities));
  6392. for (Entity *proc : procs) {
  6393. array_add(&proc_entities, proc);
  6394. }
  6395. gbString expr_name = expr_to_string(operand->expr);
  6396. defer (gb_string_free(expr_name));
  6397. for_array(i, procs) {
  6398. Entity *p = procs[i];
  6399. Type *pt = base_type(p->type);
  6400. if (pt != nullptr && is_type_proc(pt)) {
  6401. CallArgumentError err = CallArgumentError_None;
  6402. CallArgumentData data = {};
  6403. CheckerContext ctx = *c;
  6404. ctx.no_polymorphic_errors = true;
  6405. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6406. ctx.hide_polymorphic_errors = true;
  6407. Array<Operand> named_operands = {};
  6408. err = call_checker(&ctx, call, pt, p, operands, named_operands, CallArgumentMode_NoErrors, &data);
  6409. if (err != CallArgumentError_None) {
  6410. continue;
  6411. }
  6412. isize index = i;
  6413. if (data.gen_entity != nullptr) {
  6414. Entity *e = data.gen_entity;
  6415. DeclInfo *decl = data.gen_entity->decl_info;
  6416. ctx.scope = decl->scope;
  6417. ctx.decl = decl;
  6418. ctx.proc_name = e->token.string;
  6419. ctx.curr_proc_decl = decl;
  6420. ctx.curr_proc_sig = e->type;
  6421. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6422. if (!evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, false)) {
  6423. continue;
  6424. }
  6425. array_add(&proc_entities, data.gen_entity);
  6426. index = proc_entities.count-1;
  6427. }
  6428. ValidIndexAndScore item = {};
  6429. item.index = index;
  6430. item.score = data.score;
  6431. array_add(&valids, item);
  6432. }
  6433. }
  6434. if (valids.count > 1) {
  6435. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  6436. i64 best_score = valids[0].score;
  6437. Entity *best_entity = proc_entities[valids[0].index];
  6438. GB_ASSERT(best_entity != nullptr);
  6439. for (isize i = 1; i < valids.count; i++) {
  6440. if (best_score > valids[i].score) {
  6441. valids.count = i;
  6442. break;
  6443. }
  6444. if (best_entity == proc_entities[valids[i].index]) {
  6445. valids.count = i;
  6446. break;
  6447. }
  6448. }
  6449. }
  6450. if (valids.count == 0) {
  6451. begin_error_block();
  6452. defer (end_error_block());
  6453. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6454. if (operands.count == 0) {
  6455. error_line("\tNo given arguments\n");
  6456. } else {
  6457. error_line("\tGiven argument types: (");
  6458. for_array(i, operands) {
  6459. Operand o = operands[i];
  6460. if (i > 0) error_line(", ");
  6461. gbString type = type_to_string(o.type);
  6462. defer (gb_string_free(type));
  6463. error_line("%s", type);
  6464. }
  6465. error_line(")\n");
  6466. }
  6467. if (procs.count > 0) {
  6468. error_line("Did you mean to use one of the following:\n");
  6469. }
  6470. for (Entity *proc : procs) {
  6471. TokenPos pos = proc->token.pos;
  6472. Type *t = base_type(proc->type);
  6473. if (t == t_invalid) continue;
  6474. GB_ASSERT(t->kind == Type_Proc);
  6475. gbString pt;
  6476. defer (gb_string_free(pt));
  6477. if (t->Proc.node != nullptr) {
  6478. pt = expr_to_string(t->Proc.node);
  6479. } else {
  6480. pt = type_to_string(t);
  6481. }
  6482. String prefix = {};
  6483. String prefix_sep = {};
  6484. if (proc->pkg) {
  6485. prefix = proc->pkg->name;
  6486. prefix_sep = str_lit(".");
  6487. }
  6488. String name = proc->token.string;
  6489. char const *sep = "::";
  6490. if (proc->kind == Entity_Variable) {
  6491. sep = ":=";
  6492. }
  6493. error_line("\t%.*s%.*s%.*s %s %s at %s\n", LIT(prefix), LIT(prefix_sep), LIT(name), sep, pt, token_pos_to_string(pos));
  6494. }
  6495. if (procs.count > 0) {
  6496. error_line("\n");
  6497. }
  6498. result_type = t_invalid;
  6499. } else if (valids.count > 1) {
  6500. begin_error_block();
  6501. defer (end_error_block());
  6502. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6503. error_line("\tGiven argument types: (");
  6504. for_array(i, operands) {
  6505. Operand o = operands[i];
  6506. if (i > 0) error_line(", ");
  6507. gbString type = type_to_string(o.type);
  6508. defer (gb_string_free(type));
  6509. error_line("%s", type);
  6510. }
  6511. error_line(")\n");
  6512. for (isize i = 0; i < valids.count; i++) {
  6513. Entity *proc = proc_entities[valids[i].index];
  6514. GB_ASSERT(proc != nullptr);
  6515. TokenPos pos = proc->token.pos;
  6516. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6517. gbString pt = nullptr;
  6518. defer (gb_string_free(pt));
  6519. if (t->Proc.node != nullptr) {
  6520. pt = expr_to_string(t->Proc.node);
  6521. } else {
  6522. pt = type_to_string(t);
  6523. }
  6524. String name = proc->token.string;
  6525. char const *sep = "::";
  6526. if (proc->kind == Entity_Variable) {
  6527. sep = ":=";
  6528. }
  6529. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6530. if (proc->decl_info->proc_lit != nullptr) {
  6531. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6532. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6533. if (pl->where_token.kind != Token_Invalid) {
  6534. error_line("\n\t\twhere ");
  6535. for_array(j, pl->where_clauses) {
  6536. Ast *clause = pl->where_clauses[j];
  6537. if (j != 0) {
  6538. error_line("\t\t ");
  6539. }
  6540. gbString str = expr_to_string(clause);
  6541. error_line("%s", str);
  6542. gb_string_free(str);
  6543. if (j != pl->where_clauses.count-1) {
  6544. error_line(",");
  6545. }
  6546. }
  6547. error_line("\n\t");
  6548. }
  6549. }
  6550. error_line("at %s\n", token_pos_to_string(pos));
  6551. }
  6552. result_type = t_invalid;
  6553. } else {
  6554. GB_ASSERT(valids.count == 1);
  6555. Ast *ident = operand->expr;
  6556. while (ident->kind == Ast_SelectorExpr) {
  6557. Ast *s = ident->SelectorExpr.selector;
  6558. ident = s;
  6559. }
  6560. Entity *e = proc_entities[valids[0].index];
  6561. GB_ASSERT(e != nullptr);
  6562. Array<Operand> named_operands = {};
  6563. proc_type = e->type;
  6564. CallArgumentData data = {};
  6565. CallArgumentError err = call_checker(c, call, proc_type, e, operands, named_operands, CallArgumentMode_ShowErrors, &data);
  6566. gb_unused(err);
  6567. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6568. add_entity_use(c, ident, entity_to_use);
  6569. if (entity_to_use != nullptr) {
  6570. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  6571. }
  6572. if (data.gen_entity != nullptr) {
  6573. Entity *e = data.gen_entity;
  6574. DeclInfo *decl = data.gen_entity->decl_info;
  6575. CheckerContext ctx = *c;
  6576. ctx.scope = decl->scope;
  6577. ctx.decl = decl;
  6578. ctx.proc_name = e->token.string;
  6579. ctx.curr_proc_decl = decl;
  6580. ctx.curr_proc_sig = e->type;
  6581. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6582. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  6583. decl->where_clauses_evaluated = true;
  6584. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6585. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6586. }
  6587. }
  6588. return data;
  6589. }
  6590. } else {
  6591. Ast *ident = operand->expr;
  6592. while (ident->kind == Ast_SelectorExpr) {
  6593. Ast *s = ident->SelectorExpr.selector;
  6594. ident = s;
  6595. }
  6596. Entity *e = entity_of_node(ident);
  6597. Array<Operand> named_operands = {};
  6598. CallArgumentData data = {};
  6599. CallArgumentError err = call_checker(c, call, proc_type, e, operands, named_operands, CallArgumentMode_ShowErrors, &data);
  6600. gb_unused(err);
  6601. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6602. add_entity_use(c, ident, entity_to_use);
  6603. if (entity_to_use != nullptr) {
  6604. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  6605. }
  6606. if (data.gen_entity != nullptr) {
  6607. Entity *e = data.gen_entity;
  6608. DeclInfo *decl = data.gen_entity->decl_info;
  6609. CheckerContext ctx = *c;
  6610. ctx.scope = decl->scope;
  6611. ctx.decl = decl;
  6612. ctx.proc_name = e->token.string;
  6613. ctx.curr_proc_decl = decl;
  6614. ctx.curr_proc_sig = e->type;
  6615. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6616. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  6617. decl->where_clauses_evaluated = true;
  6618. if (ok && (data.gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6619. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6620. }
  6621. }
  6622. return data;
  6623. }
  6624. CallArgumentData data = {};
  6625. data.result_type = t_invalid;
  6626. return data;
  6627. }
  6628. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6629. if (!is_type_polymorphic_record(t)) {
  6630. return -1;
  6631. }
  6632. TypeTuple *params = get_record_polymorphic_params(t);
  6633. if (params == nullptr) {
  6634. return -1;
  6635. }
  6636. for_array(i, params->variables) {
  6637. Entity *e = params->variables[i];
  6638. String name = e->token.string;
  6639. if (is_blank_ident(name)) {
  6640. continue;
  6641. }
  6642. if (name == parameter_name) {
  6643. return i;
  6644. }
  6645. }
  6646. return -1;
  6647. }
  6648. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6649. ast_node(ce, CallExpr, call);
  6650. Type *original_type = operand->type;
  6651. GB_ASSERT(is_type_polymorphic_record(original_type));
  6652. bool show_error = true;
  6653. Array<Operand> operands = {};
  6654. defer (array_free(&operands));
  6655. bool named_fields = false;
  6656. {
  6657. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6658. auto prev_type_path = c->type_path;
  6659. c->type_path = new_checker_type_path();
  6660. defer ({
  6661. destroy_checker_type_path(c->type_path);
  6662. c->type_path = prev_type_path;
  6663. });
  6664. if (is_call_expr_field_value(ce)) {
  6665. named_fields = true;
  6666. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6667. for_array(i, ce->args) {
  6668. Ast *arg = ce->args[i];
  6669. ast_node(fv, FieldValue, arg);
  6670. if (fv->field->kind == Ast_Ident) {
  6671. String name = fv->field->Ident.token.string;
  6672. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6673. if (index >= 0) {
  6674. TypeTuple *params = get_record_polymorphic_params(original_type);
  6675. Entity *e = params->variables[i];
  6676. if (e->kind == Entity_Constant) {
  6677. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6678. continue;
  6679. }
  6680. }
  6681. }
  6682. check_expr_or_type(c, &operands[i], fv->value);
  6683. }
  6684. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6685. if (vari_expand) {
  6686. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6687. }
  6688. } else {
  6689. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6690. Entity **lhs = nullptr;
  6691. isize lhs_count = -1;
  6692. TypeTuple *params = get_record_polymorphic_params(original_type);
  6693. if (params != nullptr) {
  6694. lhs = params->variables.data;
  6695. lhs_count = params->variables.count;
  6696. }
  6697. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6698. }
  6699. }
  6700. CallArgumentError err = CallArgumentError_None;
  6701. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6702. isize param_count = tuple->variables.count;
  6703. isize minimum_param_count = param_count;
  6704. for (; minimum_param_count > 0; minimum_param_count--) {
  6705. Entity *e = tuple->variables[minimum_param_count-1];
  6706. if (e->kind != Entity_Constant) {
  6707. break;
  6708. }
  6709. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6710. break;
  6711. }
  6712. }
  6713. Array<Operand> ordered_operands = operands;
  6714. if (!named_fields) {
  6715. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6716. array_copy(&ordered_operands, operands, 0);
  6717. } else {
  6718. TEMPORARY_ALLOCATOR_GUARD();
  6719. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6720. // LEAK(bill)
  6721. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6722. for_array(i, ce->args) {
  6723. Ast *arg = ce->args[i];
  6724. ast_node(fv, FieldValue, arg);
  6725. if (fv->field->kind != Ast_Ident) {
  6726. if (show_error) {
  6727. gbString expr_str = expr_to_string(fv->field);
  6728. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6729. gb_string_free(expr_str);
  6730. }
  6731. err = CallArgumentError_InvalidFieldValue;
  6732. continue;
  6733. }
  6734. String name = fv->field->Ident.token.string;
  6735. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6736. if (index < 0) {
  6737. if (show_error) {
  6738. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6739. }
  6740. err = CallArgumentError_ParameterNotFound;
  6741. continue;
  6742. }
  6743. if (visited[index]) {
  6744. if (show_error) {
  6745. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6746. }
  6747. err = CallArgumentError_DuplicateParameter;
  6748. continue;
  6749. }
  6750. visited[index] = true;
  6751. ordered_operands[index] = operands[i];
  6752. }
  6753. for (isize i = 0; i < param_count; i++) {
  6754. if (!visited[i]) {
  6755. Entity *e = tuple->variables[i];
  6756. if (is_blank_ident(e->token)) {
  6757. continue;
  6758. }
  6759. if (show_error) {
  6760. if (e->kind == Entity_TypeName) {
  6761. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6762. LIT(e->token.string));
  6763. } else {
  6764. gbString str = type_to_string(e->type);
  6765. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6766. LIT(e->token.string), str);
  6767. gb_string_free(str);
  6768. }
  6769. }
  6770. err = CallArgumentError_ParameterMissing;
  6771. }
  6772. }
  6773. }
  6774. if (err != 0) {
  6775. operand->mode = Addressing_Invalid;
  6776. return err;
  6777. }
  6778. while (ordered_operands.count > 0) {
  6779. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6780. break;
  6781. }
  6782. array_pop(&ordered_operands);
  6783. }
  6784. if (minimum_param_count != param_count) {
  6785. if (param_count < ordered_operands.count) {
  6786. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6787. err = CallArgumentError_TooManyArguments;
  6788. } else if (minimum_param_count > ordered_operands.count) {
  6789. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6790. err = CallArgumentError_TooFewArguments;
  6791. }
  6792. } else {
  6793. if (param_count < ordered_operands.count) {
  6794. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6795. err = CallArgumentError_TooManyArguments;
  6796. } else if (param_count > ordered_operands.count) {
  6797. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6798. err = CallArgumentError_TooFewArguments;
  6799. }
  6800. }
  6801. if (err != 0) {
  6802. return err;
  6803. }
  6804. if (minimum_param_count != param_count) {
  6805. array_resize(&ordered_operands, param_count);
  6806. isize missing_count = 0;
  6807. // NOTE(bill): Replace missing operands with the default values (if possible)
  6808. for_array(i, ordered_operands) {
  6809. Operand *o = &ordered_operands[i];
  6810. if (o->expr == nullptr) {
  6811. Entity *e = tuple->variables[i];
  6812. if (e->kind == Entity_Constant) {
  6813. missing_count += 1;
  6814. o->mode = Addressing_Constant;
  6815. o->type = default_type(e->type);
  6816. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6817. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6818. o->value = e->Constant.param_value.value;
  6819. }
  6820. } else if (e->kind == Entity_TypeName) {
  6821. missing_count += 1;
  6822. o->mode = Addressing_Type;
  6823. o->type = e->type;
  6824. o->expr = e->identifier;
  6825. }
  6826. }
  6827. }
  6828. }
  6829. isize oo_count = gb_min(param_count, ordered_operands.count);
  6830. i64 score = 0;
  6831. for (isize i = 0; i < oo_count; i++) {
  6832. Entity *e = tuple->variables[i];
  6833. Operand *o = &ordered_operands[i];
  6834. if (o->mode == Addressing_Invalid) {
  6835. continue;
  6836. }
  6837. if (e->kind == Entity_TypeName) {
  6838. if (o->mode != Addressing_Type) {
  6839. if (show_error) {
  6840. gbString expr = expr_to_string(o->expr);
  6841. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6842. gb_string_free(expr);
  6843. }
  6844. err = CallArgumentError_WrongTypes;
  6845. }
  6846. if (are_types_identical(e->type, o->type)) {
  6847. score += assign_score_function(1);
  6848. } else {
  6849. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6850. }
  6851. } else {
  6852. i64 s = 0;
  6853. if (o->type->kind == Type_Generic) {
  6854. // Polymorphic name!
  6855. score += assign_score_function(1);
  6856. continue;
  6857. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6858. if (show_error) {
  6859. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6860. }
  6861. err = CallArgumentError_WrongTypes;
  6862. }
  6863. o->type = e->type;
  6864. if (o->mode != Addressing_Constant) {
  6865. bool valid = false;
  6866. if (is_type_proc(o->type)) {
  6867. Entity *proc_entity = entity_from_expr(o->expr);
  6868. valid = proc_entity != nullptr;
  6869. }
  6870. if (!valid) {
  6871. if (show_error) {
  6872. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6873. }
  6874. err = CallArgumentError_NoneConstantParameter;
  6875. }
  6876. }
  6877. score += s;
  6878. }
  6879. // NOTE(bill): Add type info the parameters
  6880. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6881. // add_type_info_type(c, o->type);
  6882. }
  6883. if (show_error && err) {
  6884. return err;
  6885. }
  6886. {
  6887. bool failure = false;
  6888. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  6889. if (found_entity) {
  6890. operand->mode = Addressing_Type;
  6891. operand->type = found_entity->type;
  6892. return err;
  6893. }
  6894. String generated_name = make_string_c(expr_to_string(call));
  6895. CheckerContext ctx = *c;
  6896. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6897. ctx.scope = polymorphic_record_parent_scope(original_type);
  6898. GB_ASSERT(ctx.scope != nullptr);
  6899. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6900. Type *bt = base_type(original_type);
  6901. if (bt->kind == Type_Struct) {
  6902. Ast *node = clone_ast(bt->Struct.node);
  6903. Type *struct_type = alloc_type_struct();
  6904. struct_type->Struct.node = node;
  6905. struct_type->Struct.polymorphic_parent = original_type;
  6906. set_base_type(named_type, struct_type);
  6907. check_open_scope(&ctx, node);
  6908. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6909. check_close_scope(&ctx);
  6910. } else if (bt->kind == Type_Union) {
  6911. Ast *node = clone_ast(bt->Union.node);
  6912. Type *union_type = alloc_type_union();
  6913. union_type->Union.node = node;
  6914. union_type->Union.polymorphic_parent = original_type;
  6915. set_base_type(named_type, union_type);
  6916. check_open_scope(&ctx, node);
  6917. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6918. check_close_scope(&ctx);
  6919. } else {
  6920. GB_PANIC("Unsupported parametric polymorphic record type");
  6921. }
  6922. operand->mode = Addressing_Type;
  6923. operand->type = named_type;
  6924. }
  6925. return err;
  6926. }
  6927. // returns true on failure
  6928. gb_internal bool check_call_parameter_mixture(Operand *operand, Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6929. bool failure = false;
  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. failure = true;
  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. failure = true;
  6953. }
  6954. }
  6955. }
  6956. }
  6957. return failure;
  6958. }
  6959. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (check_call_parameter_mixture(operand, 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 == "assert" ||
  6972. name == "panic" ||
  6973. name == "defined" ||
  6974. name == "config" ||
  6975. name == "load" ||
  6976. name == "load_hash" ||
  6977. name == "load_or"
  6978. ) {
  6979. operand->mode = Addressing_Builtin;
  6980. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6981. operand->expr = proc;
  6982. operand->type = t_invalid;
  6983. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6984. } else {
  6985. error(proc, "Unknown directive: #%.*s", LIT(name));
  6986. operand->expr = proc;
  6987. operand->type = t_invalid;
  6988. operand->mode = Addressing_Invalid;
  6989. return Expr_Expr;
  6990. }
  6991. if (inlining != ProcInlining_none) {
  6992. error(call, "Inlining operators are not allowed on built-in procedures");
  6993. }
  6994. } else {
  6995. if (proc != nullptr) {
  6996. check_expr_or_type(c, operand, proc);
  6997. } else {
  6998. GB_ASSERT(operand->expr != nullptr);
  6999. }
  7000. }
  7001. if (operand->mode == Addressing_Invalid) {
  7002. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  7003. for (Ast *arg : args) {
  7004. if (arg->kind == Ast_FieldValue) {
  7005. arg = arg->FieldValue.value;
  7006. }
  7007. check_expr_base(c, operand, arg, nullptr);
  7008. }
  7009. operand->mode = Addressing_Invalid;
  7010. operand->expr = call;
  7011. return Expr_Stmt;
  7012. }
  7013. if (operand->mode == Addressing_Type) {
  7014. Type *t = operand->type;
  7015. if (is_type_polymorphic_record(t)) {
  7016. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  7017. if (!is_type_named(t)) {
  7018. gbString s = expr_to_string(operand->expr);
  7019. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  7020. gb_string_free(s);
  7021. operand->mode = Addressing_Invalid;
  7022. operand->type = t_invalid;;
  7023. return Expr_Expr;
  7024. }
  7025. auto err = check_polymorphic_record_type(c, operand, call);
  7026. if (err == 0) {
  7027. Ast *ident = operand->expr;
  7028. while (ident->kind == Ast_SelectorExpr) {
  7029. Ast *s = ident->SelectorExpr.selector;
  7030. ident = s;
  7031. }
  7032. Type *ot = operand->type;
  7033. GB_ASSERT(ot->kind == Type_Named);
  7034. Entity *e = ot->Named.type_name;
  7035. add_entity_use(c, ident, e);
  7036. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  7037. } else {
  7038. operand->mode = Addressing_Invalid;
  7039. operand->type = t_invalid;
  7040. }
  7041. } else {
  7042. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  7043. operand->mode = Addressing_Invalid;
  7044. isize arg_count = args.count;
  7045. switch (arg_count) {
  7046. case 0:
  7047. {
  7048. gbString str = type_to_string(t);
  7049. error(call, "Missing argument in conversion to '%s'", str);
  7050. gb_string_free(str);
  7051. } break;
  7052. default:
  7053. {
  7054. gbString str = type_to_string(t);
  7055. error(call, "Too many arguments in conversion to '%s'", str);
  7056. gb_string_free(str);
  7057. } break;
  7058. case 1: {
  7059. Ast *arg = args[0];
  7060. if (arg->kind == Ast_FieldValue) {
  7061. error(call, "'field = value' cannot be used in a type conversion");
  7062. arg = arg->FieldValue.value;
  7063. // NOTE(bill): Carry on the cast regardless
  7064. }
  7065. check_expr_with_type_hint(c, operand, arg, t);
  7066. if (operand->mode != Addressing_Invalid) {
  7067. if (is_type_polymorphic(t)) {
  7068. error(call, "A polymorphic type cannot be used in a type conversion");
  7069. } else {
  7070. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7071. // as it assumes it is determining the type
  7072. check_cast(c, operand, t);
  7073. }
  7074. }
  7075. operand->type = t;
  7076. operand->expr = call;
  7077. if (operand->mode != Addressing_Invalid) {
  7078. update_untyped_expr_type(c, arg, t, false);
  7079. }
  7080. break;
  7081. }
  7082. }
  7083. }
  7084. return Expr_Expr;
  7085. }
  7086. if (operand->mode == Addressing_Builtin) {
  7087. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7088. i32 id = operand->builtin_id;
  7089. Entity *e = entity_of_node(operand->expr);
  7090. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7091. warning(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7092. }
  7093. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7094. operand->mode = Addressing_Invalid;
  7095. operand->type = t_invalid;
  7096. }
  7097. operand->expr = call;
  7098. return builtin_procs[id].kind;
  7099. }
  7100. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7101. Entity *initial_entity = entity_of_node(operand->expr);
  7102. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7103. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7104. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7105. if (c->decl) {
  7106. c->decl->defer_used += 1;
  7107. }
  7108. }
  7109. }
  7110. if (operand->mode != Addressing_ProcGroup) {
  7111. Type *proc_type = base_type(operand->type);
  7112. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7113. bool valid_mode = is_operand_value(*operand);
  7114. if (!valid_type || !valid_mode) {
  7115. Ast *e = operand->expr;
  7116. gbString str = expr_to_string(e);
  7117. gbString type_str = type_to_string(operand->type);
  7118. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7119. gb_string_free(type_str);
  7120. gb_string_free(str);
  7121. operand->mode = Addressing_Invalid;
  7122. operand->expr = call;
  7123. return Expr_Stmt;
  7124. }
  7125. }
  7126. CallArgumentData data = check_call_arguments(c, operand, call);
  7127. Type *result_type = data.result_type;
  7128. gb_zero_item(operand);
  7129. operand->expr = call;
  7130. if (result_type == t_invalid) {
  7131. operand->mode = Addressing_Invalid;
  7132. operand->type = t_invalid;
  7133. return Expr_Stmt;
  7134. }
  7135. Type *pt = base_type(operand->type);
  7136. if (pt == nullptr) {
  7137. pt = t_invalid;
  7138. }
  7139. if (pt == t_invalid) {
  7140. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7141. pt = type_of_expr(operand->expr->CallExpr.proc);
  7142. }
  7143. if (pt == t_invalid && data.gen_entity) {
  7144. pt = data.gen_entity->type;
  7145. }
  7146. }
  7147. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7148. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7149. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7150. }
  7151. }
  7152. if (result_type == nullptr) {
  7153. operand->mode = Addressing_NoValue;
  7154. } else {
  7155. GB_ASSERT(is_type_tuple(result_type));
  7156. isize count = result_type->Tuple.variables.count;
  7157. switch (count) {
  7158. case 0:
  7159. operand->mode = Addressing_NoValue;
  7160. break;
  7161. case 1:
  7162. operand->mode = Addressing_Value;
  7163. operand->type = result_type->Tuple.variables[0]->type;
  7164. break;
  7165. default:
  7166. operand->mode = Addressing_Value;
  7167. operand->type = result_type;
  7168. break;
  7169. }
  7170. }
  7171. switch (inlining) {
  7172. case ProcInlining_inline:
  7173. if (proc != nullptr) {
  7174. Entity *e = entity_from_expr(proc);
  7175. if (e != nullptr && e->kind == Entity_Procedure) {
  7176. DeclInfo *decl = e->decl_info;
  7177. if (decl->proc_lit) {
  7178. ast_node(pl, ProcLit, decl->proc_lit);
  7179. if (pl->inlining == ProcInlining_no_inline) {
  7180. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  7181. }
  7182. }
  7183. }
  7184. }
  7185. break;
  7186. case ProcInlining_no_inline:
  7187. break;
  7188. }
  7189. operand->expr = call;
  7190. {
  7191. Type *type = nullptr;
  7192. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7193. type = type_of_expr(operand->expr->CallExpr.proc);
  7194. }
  7195. if (type == nullptr) {
  7196. type = pt;
  7197. }
  7198. type = base_type(type);
  7199. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  7200. operand->mode = Addressing_OptionalOk;
  7201. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7202. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7203. operand->expr->CallExpr.optional_ok_one = true;
  7204. }
  7205. }
  7206. }
  7207. return Expr_Expr;
  7208. }
  7209. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7210. check_expr_base(c, o, e, t);
  7211. check_not_tuple(c, o);
  7212. char const *err_str = nullptr;
  7213. switch (o->mode) {
  7214. case Addressing_NoValue:
  7215. err_str = "used as a value";
  7216. break;
  7217. case Addressing_Type:
  7218. if (t == nullptr || !is_type_typeid(t)) {
  7219. err_str = "is not an expression but a type, in this context it is ambiguous";
  7220. }
  7221. break;
  7222. case Addressing_Builtin:
  7223. err_str = "must be called";
  7224. break;
  7225. }
  7226. if (err_str != nullptr) {
  7227. gbString str = expr_to_string(e);
  7228. error(e, "'%s' %s", str, err_str);
  7229. gb_string_free(str);
  7230. o->mode = Addressing_Invalid;
  7231. }
  7232. }
  7233. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7234. switch (t->kind) {
  7235. case Type_Basic:
  7236. if (t->Basic.kind == Basic_string) {
  7237. if (o->mode == Addressing_Constant) {
  7238. *max_count = o->value.value_string.len;
  7239. }
  7240. if (o->mode != Addressing_Constant) {
  7241. o->mode = Addressing_Value;
  7242. }
  7243. o->type = t_u8;
  7244. return true;
  7245. } else if (t->Basic.kind == Basic_UntypedString) {
  7246. if (o->mode == Addressing_Constant) {
  7247. *max_count = o->value.value_string.len;
  7248. o->type = t_u8;
  7249. return true;
  7250. }
  7251. return false;
  7252. }
  7253. break;
  7254. case Type_MultiPointer:
  7255. o->type = t->MultiPointer.elem;
  7256. if (o->mode != Addressing_Constant) {
  7257. o->mode = Addressing_Variable;
  7258. }
  7259. return true;
  7260. case Type_Array:
  7261. *max_count = t->Array.count;
  7262. if (indirection) {
  7263. o->mode = Addressing_Variable;
  7264. } else if (o->mode != Addressing_Variable &&
  7265. o->mode != Addressing_Constant) {
  7266. o->mode = Addressing_Value;
  7267. }
  7268. o->type = t->Array.elem;
  7269. return true;
  7270. case Type_EnumeratedArray:
  7271. *max_count = t->EnumeratedArray.count;
  7272. if (indirection) {
  7273. o->mode = Addressing_Variable;
  7274. } else if (o->mode != Addressing_Variable &&
  7275. o->mode != Addressing_Constant) {
  7276. o->mode = Addressing_Value;
  7277. }
  7278. o->type = t->EnumeratedArray.elem;
  7279. return true;
  7280. case Type_Matrix:
  7281. *max_count = t->Matrix.column_count;
  7282. if (indirection) {
  7283. o->mode = Addressing_Variable;
  7284. } else if (o->mode != Addressing_Variable) {
  7285. o->mode = Addressing_Value;
  7286. }
  7287. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7288. return true;
  7289. case Type_Slice:
  7290. o->type = t->Slice.elem;
  7291. if (o->mode != Addressing_Constant) {
  7292. o->mode = Addressing_Variable;
  7293. }
  7294. return true;
  7295. case Type_RelativeSlice:
  7296. {
  7297. Type *slice_type = base_type(t->RelativeSlice.slice_type);
  7298. GB_ASSERT(slice_type->kind == Type_Slice);
  7299. o->type = slice_type->Slice.elem;
  7300. if (o->mode != Addressing_Constant) {
  7301. o->mode = Addressing_Variable;
  7302. }
  7303. }
  7304. return true;
  7305. case Type_DynamicArray:
  7306. o->type = t->DynamicArray.elem;
  7307. if (o->mode != Addressing_Constant) {
  7308. o->mode = Addressing_Variable;
  7309. }
  7310. return true;
  7311. case Type_Struct:
  7312. if (t->Struct.soa_kind != StructSoa_None) {
  7313. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7314. *max_count = t->Struct.soa_count;
  7315. }
  7316. o->type = t->Struct.soa_elem;
  7317. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  7318. o->mode = Addressing_SoaVariable;
  7319. } else {
  7320. o->mode = Addressing_Value;
  7321. }
  7322. return true;
  7323. }
  7324. return false;
  7325. }
  7326. if (is_type_pointer(original_type) && indirection) {
  7327. Type *ptr = base_type(original_type);
  7328. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  7329. o->type = ptr->Pointer.elem;
  7330. o->mode = Addressing_Value;
  7331. return true;
  7332. }
  7333. }
  7334. return false;
  7335. }
  7336. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7337. if (is_type_untyped_uninit(x)) {
  7338. return true;
  7339. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7340. return true;
  7341. } else if (is_type_untyped_uninit(y)) {
  7342. return true;
  7343. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7344. return true;
  7345. }
  7346. return are_types_identical(x, y);
  7347. }
  7348. 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) {
  7349. if (!is_ast_range(node)) {
  7350. return false;
  7351. }
  7352. ast_node(ie, BinaryExpr, node);
  7353. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7354. if (x->mode == Addressing_Invalid) {
  7355. return false;
  7356. }
  7357. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7358. if (y->mode == Addressing_Invalid) {
  7359. return false;
  7360. }
  7361. convert_to_typed(c, x, y->type);
  7362. if (x->mode == Addressing_Invalid) {
  7363. return false;
  7364. }
  7365. convert_to_typed(c, y, x->type);
  7366. if (y->mode == Addressing_Invalid) {
  7367. return false;
  7368. }
  7369. convert_to_typed(c, x, default_type(y->type));
  7370. if (x->mode == Addressing_Invalid) {
  7371. return false;
  7372. }
  7373. convert_to_typed(c, y, default_type(x->type));
  7374. if (y->mode == Addressing_Invalid) {
  7375. return false;
  7376. }
  7377. if (!are_types_identical(x->type, y->type)) {
  7378. if (x->type != t_invalid &&
  7379. y->type != t_invalid) {
  7380. gbString xt = type_to_string(x->type);
  7381. gbString yt = type_to_string(y->type);
  7382. gbString expr_str = expr_to_string(x->expr);
  7383. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7384. gb_string_free(expr_str);
  7385. gb_string_free(yt);
  7386. gb_string_free(xt);
  7387. }
  7388. return false;
  7389. }
  7390. Type *type = x->type;
  7391. if (is_for_loop) {
  7392. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7393. error(ie->op, "Only numerical types are allowed within interval expressions");
  7394. return false;
  7395. }
  7396. } else {
  7397. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7398. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7399. return false;
  7400. }
  7401. }
  7402. if (x->mode == Addressing_Constant &&
  7403. y->mode == Addressing_Constant) {
  7404. ExactValue a = x->value;
  7405. ExactValue b = y->value;
  7406. GB_ASSERT(are_types_identical(x->type, y->type));
  7407. TokenKind op = Token_Lt;
  7408. switch (ie->op.kind) {
  7409. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7410. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7411. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7412. default: error(ie->op, "Invalid range operator"); break;
  7413. }
  7414. bool ok = compare_exact_values(op, a, b);
  7415. if (!ok) {
  7416. // TODO(bill): Better error message
  7417. error(ie->op, "Invalid interval range");
  7418. return false;
  7419. }
  7420. ExactValue inline_for_depth = exact_value_sub(b, a);
  7421. if (ie->op.kind != Token_RangeHalf) {
  7422. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7423. }
  7424. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7425. } else if (inline_for_depth_ != nullptr) {
  7426. error(ie->op, "Interval expressions must be constant");
  7427. return false;
  7428. }
  7429. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7430. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7431. return true;
  7432. }
  7433. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7434. if (is_operand_nil(*o)) {
  7435. return true;
  7436. }
  7437. Ast *expr = unparen_expr(o->expr);
  7438. if (expr != nullptr) {
  7439. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7440. if (e != nullptr && e->kind == Entity_Procedure) {
  7441. return true;
  7442. }
  7443. if (expr->kind == Ast_ProcLit) {
  7444. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7445. return true;
  7446. }
  7447. }
  7448. return o->mode == Addressing_Constant;
  7449. }
  7450. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7451. if (is_type_enum(th)) {
  7452. Type *enum_type = base_type(th);
  7453. GB_ASSERT(enum_type->kind == Type_Enum);
  7454. String name = ise->selector->Ident.token.string;
  7455. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7456. if (e == nullptr) {
  7457. return false;
  7458. }
  7459. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7460. GB_ASSERT(e->kind == Entity_Constant);
  7461. o->value = e->Constant.value;
  7462. o->mode = Addressing_Constant;
  7463. o->type = e->type;
  7464. return true;
  7465. }
  7466. if (is_type_union(th)) {
  7467. TEMPORARY_ALLOCATOR_GUARD();
  7468. Type *union_type = base_type(th);
  7469. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7470. for (Type *vt : union_type->Union.variants) {
  7471. Operand x = {};
  7472. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7473. array_add(&operands, x);
  7474. }
  7475. }
  7476. if (operands.count == 1) {
  7477. *o = operands[0];
  7478. return true;
  7479. }
  7480. }
  7481. return false;
  7482. }
  7483. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7484. ast_node(ise, ImplicitSelectorExpr, node);
  7485. o->type = t_invalid;
  7486. o->expr = node;
  7487. o->mode = Addressing_Invalid;
  7488. Type *th = type_hint;
  7489. if (th == nullptr) {
  7490. gbString str = expr_to_string(node);
  7491. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7492. gb_string_free(str);
  7493. return Expr_Expr;
  7494. }
  7495. o->type = th;
  7496. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7497. if (!ok) {
  7498. String name = ise->selector->Ident.token.string;
  7499. if (is_type_enum(th)) {
  7500. Type *bt = base_type(th);
  7501. GB_ASSERT(bt->kind == Type_Enum);
  7502. gbString typ = type_to_string(th);
  7503. defer (gb_string_free(typ));
  7504. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7505. check_did_you_mean_type(name, bt->Enum.fields);
  7506. } else {
  7507. gbString typ = type_to_string(th);
  7508. gbString str = expr_to_string(node);
  7509. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7510. gb_string_free(str);
  7511. gb_string_free(typ);
  7512. }
  7513. }
  7514. o->expr = node;
  7515. return Expr_Expr;
  7516. }
  7517. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  7518. switch (x->mode) {
  7519. case Addressing_MapIndex:
  7520. case Addressing_OptionalOk:
  7521. case Addressing_OptionalOkPtr:
  7522. if (val_type_) *val_type_ = x->type;
  7523. break;
  7524. default:
  7525. if (ok_type_) *ok_type_ = x->type;
  7526. return;
  7527. }
  7528. Ast *expr = unparen_expr(x->expr);
  7529. if (expr->kind == Ast_CallExpr) {
  7530. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7531. if (is_type_proc(pt)) {
  7532. Type *tuple = pt->Proc.results;
  7533. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7534. if (pt->Proc.result_count >= 2) {
  7535. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7536. }
  7537. expr->CallExpr.optional_ok_one = false;
  7538. x->type = tuple;
  7539. return;
  7540. }
  7541. }
  7542. Type *tuple = make_optional_ok_type(x->type);
  7543. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7544. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7545. x->type = tuple;
  7546. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7547. }
  7548. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7549. ast_node(ie, MatrixIndexExpr, node);
  7550. check_expr(c, o, ie->expr);
  7551. node->viral_state_flags |= ie->expr->viral_state_flags;
  7552. if (o->mode == Addressing_Invalid) {
  7553. o->expr = node;
  7554. return;
  7555. }
  7556. Type *t = base_type(type_deref(o->type));
  7557. bool is_ptr = is_type_pointer(o->type);
  7558. bool is_const = o->mode == Addressing_Constant;
  7559. if (t->kind != Type_Matrix) {
  7560. gbString str = expr_to_string(o->expr);
  7561. gbString type_str = type_to_string(o->type);
  7562. defer (gb_string_free(str));
  7563. defer (gb_string_free(type_str));
  7564. if (is_const) {
  7565. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7566. } else {
  7567. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7568. }
  7569. o->mode = Addressing_Invalid;
  7570. o->expr = node;
  7571. return;
  7572. }
  7573. o->type = t->Matrix.elem;
  7574. if (is_ptr) {
  7575. o->mode = Addressing_Variable;
  7576. } else if (o->mode != Addressing_Variable) {
  7577. o->mode = Addressing_Value;
  7578. }
  7579. if (ie->row_index == nullptr) {
  7580. gbString str = expr_to_string(o->expr);
  7581. error(o->expr, "Missing row index for '%s'", str);
  7582. gb_string_free(str);
  7583. o->mode = Addressing_Invalid;
  7584. o->expr = node;
  7585. return;
  7586. }
  7587. if (ie->column_index == nullptr) {
  7588. gbString str = expr_to_string(o->expr);
  7589. error(o->expr, "Missing column index for '%s'", str);
  7590. gb_string_free(str);
  7591. o->mode = Addressing_Invalid;
  7592. o->expr = node;
  7593. return;
  7594. }
  7595. i64 row_count = t->Matrix.row_count;
  7596. i64 column_count = t->Matrix.column_count;
  7597. i64 row_index = 0;
  7598. i64 column_index = 0;
  7599. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7600. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7601. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7602. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7603. }
  7604. gb_unused(row_ok);
  7605. gb_unused(column_ok);
  7606. }
  7607. struct TypeAndToken {
  7608. Type *type;
  7609. Token token;
  7610. };
  7611. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7612. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7613. if (operand.mode != Addressing_Constant) {
  7614. return;
  7615. }
  7616. if (operand.value.kind == ExactValue_Invalid) {
  7617. return;
  7618. }
  7619. uintptr key = hash_exact_value(operand.value);
  7620. TypeAndToken *found = map_get(seen, key);
  7621. if (found != nullptr) {
  7622. TEMPORARY_ALLOCATOR_GUARD();
  7623. isize count = multi_map_count(seen, key);
  7624. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7625. multi_map_get_all(seen, key, taps);
  7626. for (isize i = 0; i < count; i++) {
  7627. TypeAndToken tap = taps[i];
  7628. if (!are_types_identical(operand.type, tap.type)) {
  7629. continue;
  7630. }
  7631. TokenPos pos = tap.token.pos;
  7632. if (use_expr) {
  7633. gbString expr_str = expr_to_string(operand.expr);
  7634. error(operand.expr,
  7635. "Duplicate case '%s'\n"
  7636. "\tprevious case at %s",
  7637. expr_str,
  7638. token_pos_to_string(pos));
  7639. gb_string_free(expr_str);
  7640. } else {
  7641. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7642. }
  7643. return;
  7644. }
  7645. }
  7646. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7647. multi_map_insert(seen, key, tap);
  7648. }
  7649. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7650. if (is_type_enum(x.type)) {
  7651. // TODO(bill): Fix this logic so it's fast!!!
  7652. i64 v0 = exact_value_to_i64(lhs.value);
  7653. i64 v1 = exact_value_to_i64(rhs.value);
  7654. Operand v = {};
  7655. v.mode = Addressing_Constant;
  7656. v.type = x.type;
  7657. v.expr = x.expr;
  7658. Type *bt = base_type(x.type);
  7659. GB_ASSERT(bt->kind == Type_Enum);
  7660. for (i64 vi = v0; vi <= v1; vi++) {
  7661. if (upper_op != Token_LtEq && vi == v1) {
  7662. break;
  7663. }
  7664. bool found = false;
  7665. for (Entity *f : bt->Enum.fields) {
  7666. GB_ASSERT(f->kind == Entity_Constant);
  7667. i64 fv = exact_value_to_i64(f->Constant.value);
  7668. if (fv == vi) {
  7669. found = true;
  7670. break;
  7671. }
  7672. }
  7673. if (found) {
  7674. v.value = exact_value_i64(vi);
  7675. add_constant_switch_case(ctx, seen, v);
  7676. }
  7677. }
  7678. } else {
  7679. add_constant_switch_case(ctx, seen, lhs);
  7680. if (upper_op == Token_LtEq) {
  7681. add_constant_switch_case(ctx, seen, rhs);
  7682. }
  7683. }
  7684. }
  7685. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7686. add_constant_switch_case(ctx, seen, x);
  7687. }
  7688. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7689. ast_node(bd, BasicDirective, node);
  7690. ExprKind kind = Expr_Expr;
  7691. o->mode = Addressing_Constant;
  7692. String name = bd->name.string;
  7693. if (name == "file") {
  7694. o->type = t_untyped_string;
  7695. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  7696. } else if (name == "line") {
  7697. o->type = t_untyped_integer;
  7698. o->value = exact_value_i64(bd->token.pos.line);
  7699. } else if (name == "procedure") {
  7700. if (c->curr_proc_decl == nullptr) {
  7701. error(node, "#procedure may only be used within procedures");
  7702. o->type = t_untyped_string;
  7703. o->value = exact_value_string(str_lit(""));
  7704. } else {
  7705. o->type = t_untyped_string;
  7706. o->value = exact_value_string(c->proc_name);
  7707. }
  7708. } else if (name == "caller_location") {
  7709. init_core_source_code_location(c->checker);
  7710. error(node, "#caller_location may only be used as a default argument parameter");
  7711. o->type = t_source_code_location;
  7712. o->mode = Addressing_Value;
  7713. } else {
  7714. if (name == "location") {
  7715. init_core_source_code_location(c->checker);
  7716. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  7717. o->type = t_source_code_location;
  7718. o->mode = Addressing_Value;
  7719. } else if (
  7720. name == "assert" ||
  7721. name == "defined" ||
  7722. name == "config" ||
  7723. name == "load" ||
  7724. name == "load_hash" ||
  7725. name == "load_or"
  7726. ) {
  7727. error(node, "'#%.*s' must be used as a call", LIT(name));
  7728. o->type = t_invalid;
  7729. o->mode = Addressing_Invalid;
  7730. } else {
  7731. error(node, "Unknown directive: #%.*s", LIT(name));
  7732. o->type = t_invalid;
  7733. o->mode = Addressing_Invalid;
  7734. }
  7735. }
  7736. return kind;
  7737. }
  7738. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7739. ExprKind kind = Expr_Expr;
  7740. Operand cond = {Addressing_Invalid};
  7741. ast_node(te, TernaryIfExpr, node);
  7742. check_expr(c, &cond, te->cond);
  7743. node->viral_state_flags |= te->cond->viral_state_flags;
  7744. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7745. error(te->cond, "Non-boolean condition in ternary if expression");
  7746. }
  7747. Operand x = {Addressing_Invalid};
  7748. Operand y = {Addressing_Invalid};
  7749. check_expr_or_type(c, &x, te->x, type_hint);
  7750. node->viral_state_flags |= te->x->viral_state_flags;
  7751. if (te->y != nullptr) {
  7752. Type *th = type_hint;
  7753. if (type_hint == nullptr && is_type_typed(x.type)) {
  7754. th = x.type;
  7755. }
  7756. check_expr_or_type(c, &y, te->y, th);
  7757. node->viral_state_flags |= te->y->viral_state_flags;
  7758. } else {
  7759. error(node, "A ternary expression must have an else clause");
  7760. return kind;
  7761. }
  7762. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7763. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7764. gbString type_string = expr_to_string(type_expr);
  7765. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7766. gb_string_free(type_string);
  7767. return kind;
  7768. }
  7769. if (x.type == nullptr || x.type == t_invalid ||
  7770. y.type == nullptr || y.type == t_invalid) {
  7771. return kind;
  7772. }
  7773. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7774. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7775. if (x.mode == Addressing_Invalid) {
  7776. return kind;
  7777. }
  7778. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7779. if (y.mode == Addressing_Invalid) {
  7780. x.mode = Addressing_Invalid;
  7781. return kind;
  7782. }
  7783. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7784. // x: union{f32} = f32(123) if cond else nil
  7785. if (type_hint && !is_type_any(type_hint) && !ternary_compare_types(x.type, y.type)) {
  7786. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7787. check_cast(c, &x, type_hint);
  7788. check_cast(c, &y, type_hint);
  7789. }
  7790. }
  7791. if (!ternary_compare_types(x.type, y.type)) {
  7792. gbString its = type_to_string(x.type);
  7793. gbString ets = type_to_string(y.type);
  7794. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7795. gb_string_free(ets);
  7796. gb_string_free(its);
  7797. return kind;
  7798. }
  7799. o->type = x.type;
  7800. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7801. o->type = y.type;
  7802. }
  7803. o->mode = Addressing_Value;
  7804. o->expr = node;
  7805. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7806. if (check_cast_internal(c, &x, type_hint) &&
  7807. check_cast_internal(c, &y, type_hint)) {
  7808. convert_to_typed(c, o, type_hint);
  7809. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7810. o->type = type_hint;
  7811. }
  7812. }
  7813. return kind;
  7814. }
  7815. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7816. ExprKind kind = Expr_Expr;
  7817. Operand cond = {};
  7818. ast_node(te, TernaryWhenExpr, node);
  7819. check_expr(c, &cond, te->cond);
  7820. node->viral_state_flags |= te->cond->viral_state_flags;
  7821. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7822. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7823. return kind;
  7824. }
  7825. if (cond.value.value_bool) {
  7826. check_expr_or_type(c, o, te->x, type_hint);
  7827. node->viral_state_flags |= te->x->viral_state_flags;
  7828. } else {
  7829. if (te->y != nullptr) {
  7830. check_expr_or_type(c, o, te->y, type_hint);
  7831. node->viral_state_flags |= te->y->viral_state_flags;
  7832. } else {
  7833. error(node, "A ternary when expression must have an else clause");
  7834. return kind;
  7835. }
  7836. }
  7837. return kind;
  7838. }
  7839. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7840. ast_node(oe, OrElseExpr, node);
  7841. String name = oe->token.string;
  7842. Ast *arg = oe->x;
  7843. Ast *default_value = oe->y;
  7844. Operand x = {};
  7845. Operand y = {};
  7846. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7847. if (is_load_directive_call(arg)) {
  7848. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7849. // Allow for chaining of '#load(path) or_else #load(path)'
  7850. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7851. bool y_is_diverging = false;
  7852. check_expr_base(c, &y, default_value, x.type);
  7853. switch (y.mode) {
  7854. case Addressing_NoValue:
  7855. if (is_diverging_expr(y.expr)) {
  7856. // Allow
  7857. y.mode = Addressing_Value;
  7858. y_is_diverging = true;
  7859. } else {
  7860. error_operand_no_value(&y);
  7861. y.mode = Addressing_Invalid;
  7862. }
  7863. break;
  7864. case Addressing_Type:
  7865. error_operand_not_expression(&y);
  7866. y.mode = Addressing_Invalid;
  7867. break;
  7868. }
  7869. if (y.mode == Addressing_Invalid) {
  7870. o->mode = Addressing_Value;
  7871. o->type = t_invalid;
  7872. o->expr = node;
  7873. return Expr_Expr;
  7874. }
  7875. if (!y_is_diverging) {
  7876. check_assignment(c, &y, x.type, name);
  7877. if (y.mode != Addressing_Constant) {
  7878. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7879. }
  7880. }
  7881. }
  7882. if (res == LoadDirective_Success) {
  7883. *o = x;
  7884. } else {
  7885. *o = y;
  7886. }
  7887. o->expr = node;
  7888. return Expr_Expr;
  7889. }
  7890. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7891. if (x.mode == Addressing_Invalid) {
  7892. o->mode = Addressing_Value;
  7893. o->type = t_invalid;
  7894. o->expr = node;
  7895. return Expr_Expr;
  7896. }
  7897. bool y_is_diverging = false;
  7898. check_expr_base(c, &y, default_value, x.type);
  7899. switch (y.mode) {
  7900. case Addressing_NoValue:
  7901. if (is_diverging_expr(y.expr)) {
  7902. // Allow
  7903. y.mode = Addressing_Value;
  7904. y_is_diverging = true;
  7905. } else {
  7906. error_operand_no_value(&y);
  7907. y.mode = Addressing_Invalid;
  7908. }
  7909. break;
  7910. case Addressing_Type:
  7911. error_operand_not_expression(&y);
  7912. y.mode = Addressing_Invalid;
  7913. break;
  7914. }
  7915. if (y.mode == Addressing_Invalid) {
  7916. o->mode = Addressing_Value;
  7917. o->type = t_invalid;
  7918. o->expr = node;
  7919. return Expr_Expr;
  7920. }
  7921. Type *left_type = nullptr;
  7922. Type *right_type = nullptr;
  7923. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7924. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7925. if (left_type != nullptr) {
  7926. if (!y_is_diverging) {
  7927. check_assignment(c, &y, left_type, name);
  7928. }
  7929. } else {
  7930. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7931. }
  7932. if (left_type == nullptr) {
  7933. left_type = t_invalid;
  7934. }
  7935. o->mode = Addressing_Value;
  7936. o->type = left_type;
  7937. o->expr = node;
  7938. return Expr_Expr;
  7939. }
  7940. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7941. ast_node(re, OrReturnExpr, node);
  7942. String name = re->token.string;
  7943. Operand x = {};
  7944. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7945. if (x.mode == Addressing_Invalid) {
  7946. o->mode = Addressing_Value;
  7947. o->type = t_invalid;
  7948. o->expr = node;
  7949. return Expr_Expr;
  7950. }
  7951. Type *left_type = nullptr;
  7952. Type *right_type = nullptr;
  7953. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7954. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7955. if (right_type == nullptr) {
  7956. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7957. } else {
  7958. Type *proc_type = base_type(c->curr_proc_sig);
  7959. GB_ASSERT(proc_type->kind == Type_Proc);
  7960. Type *result_type = proc_type->Proc.results;
  7961. if (result_type == nullptr) {
  7962. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7963. } else {
  7964. GB_ASSERT(result_type->kind == Type_Tuple);
  7965. auto const &vars = result_type->Tuple.variables;
  7966. Type *end_type = vars[vars.count-1]->type;
  7967. if (vars.count > 1) {
  7968. if (!proc_type->Proc.has_named_results) {
  7969. 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));
  7970. }
  7971. }
  7972. Operand rhs = {};
  7973. rhs.type = right_type;
  7974. rhs.mode = Addressing_Value;
  7975. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7976. // NOTE(bill): allow implicit conversion between boolean types
  7977. // within 'or_return' to improve the experience using third-party code
  7978. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7979. // TODO(bill): better error message
  7980. gbString a = type_to_string(right_type);
  7981. gbString b = type_to_string(end_type);
  7982. gbString ret_type = type_to_string(result_type);
  7983. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7984. if (vars.count == 1) {
  7985. error_line("\tProcedure return value type: %s\n", ret_type);
  7986. } else {
  7987. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7988. }
  7989. gb_string_free(ret_type);
  7990. gb_string_free(b);
  7991. gb_string_free(a);
  7992. }
  7993. }
  7994. }
  7995. o->expr = node;
  7996. o->type = left_type;
  7997. if (left_type != nullptr) {
  7998. o->mode = Addressing_Value;
  7999. } else {
  8000. o->mode = Addressing_NoValue;
  8001. }
  8002. if (c->curr_proc_sig == nullptr) {
  8003. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8004. }
  8005. if (c->in_defer) {
  8006. error(node, "'or_return' cannot be used within a defer statement");
  8007. }
  8008. return Expr_Expr;
  8009. }
  8010. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8011. Type *bt = base_type(type);
  8012. StringSet fields_visited = {};
  8013. defer (string_set_destroy(&fields_visited));
  8014. StringMap<String> fields_visited_through_raw_union = {};
  8015. defer (string_map_destroy(&fields_visited_through_raw_union));
  8016. for (Ast *elem : elems) {
  8017. if (elem->kind != Ast_FieldValue) {
  8018. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8019. continue;
  8020. }
  8021. ast_node(fv, FieldValue, elem);
  8022. if (fv->field->kind != Ast_Ident) {
  8023. gbString expr_str = expr_to_string(fv->field);
  8024. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8025. gb_string_free(expr_str);
  8026. continue;
  8027. }
  8028. String name = fv->field->Ident.token.string;
  8029. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8030. bool is_unknown = sel.entity == nullptr;
  8031. if (is_unknown) {
  8032. error(fv->field, "Unknown field '%.*s' in structure literal", LIT(name));
  8033. continue;
  8034. }
  8035. Entity *field = bt->Struct.fields[sel.index[0]];
  8036. add_entity_use(c, fv->field, field);
  8037. if (string_set_update(&fields_visited, name)) {
  8038. if (sel.index.count > 1) {
  8039. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8040. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8041. } else {
  8042. error(fv->field, "Duplicate or reused field '%.*s' in structure literal", LIT(sel.entity->token.string));
  8043. }
  8044. } else {
  8045. error(fv->field, "Duplicate field '%.*s' in structure literal", LIT(field->token.string));
  8046. }
  8047. continue;
  8048. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8049. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8050. continue;
  8051. }
  8052. if (sel.indirect) {
  8053. error(fv->field, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a structure literal", cast(int)sel.index.count-1, LIT(name));
  8054. continue;
  8055. }
  8056. if (sel.index.count > 1) {
  8057. if (is_constant) {
  8058. Type *ft = type;
  8059. for (i32 index : sel.index) {
  8060. Type *bt = base_type(ft);
  8061. switch (bt->kind) {
  8062. case Type_Struct:
  8063. if (bt->Struct.is_raw_union) {
  8064. is_constant = false;
  8065. break;
  8066. }
  8067. ft = bt->Struct.fields[index]->type;
  8068. break;
  8069. case Type_Array:
  8070. ft = bt->Array.elem;
  8071. break;
  8072. default:
  8073. GB_PANIC("invalid type: %s", type_to_string(ft));
  8074. break;
  8075. }
  8076. }
  8077. if (is_constant &&
  8078. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8079. is_constant = false;
  8080. }
  8081. }
  8082. Type *nested_ft = bt;
  8083. for (i32 index : sel.index) {
  8084. Type *bt = base_type(nested_ft);
  8085. switch (bt->kind) {
  8086. case Type_Struct:
  8087. if (bt->Struct.is_raw_union) {
  8088. for (Entity *re : bt->Struct.fields) {
  8089. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8090. }
  8091. }
  8092. nested_ft = bt->Struct.fields[index]->type;
  8093. break;
  8094. case Type_Array:
  8095. nested_ft = bt->Array.elem;
  8096. break;
  8097. default:
  8098. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8099. break;
  8100. }
  8101. }
  8102. field = sel.entity;
  8103. }
  8104. Operand o = {};
  8105. check_expr_or_type(c, &o, fv->value, field->type);
  8106. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8107. is_constant = false;
  8108. }
  8109. if (is_constant) {
  8110. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8111. }
  8112. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8113. }
  8114. }
  8115. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8116. ExprKind kind = Expr_Expr;
  8117. ast_node(cl, CompoundLit, node);
  8118. Type *type = type_hint;
  8119. if (type != nullptr && is_type_untyped(type)) {
  8120. type = nullptr;
  8121. }
  8122. bool is_to_be_determined_array_count = false;
  8123. bool is_constant = true;
  8124. if (cl->type != nullptr) {
  8125. type = nullptr;
  8126. // [?]Type
  8127. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  8128. Ast *count = cl->type->ArrayType.count;
  8129. if (count->kind == Ast_UnaryExpr &&
  8130. count->UnaryExpr.op.kind == Token_Question) {
  8131. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  8132. is_to_be_determined_array_count = true;
  8133. }
  8134. if (cl->elems.count > 0) {
  8135. if (cl->type->ArrayType.tag != nullptr) {
  8136. Ast *tag = cl->type->ArrayType.tag;
  8137. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8138. String name = tag->BasicDirective.name.string;
  8139. if (name == "soa") {
  8140. error(node, "#soa arrays are not supported for compound literals");
  8141. return kind;
  8142. }
  8143. }
  8144. }
  8145. }
  8146. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  8147. if (cl->elems.count > 0) {
  8148. Ast *tag = cl->type->DynamicArrayType.tag;
  8149. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8150. String name = tag->BasicDirective.name.string;
  8151. if (name == "soa") {
  8152. error(node, "#soa arrays are not supported for compound literals");
  8153. return kind;
  8154. }
  8155. }
  8156. }
  8157. if (type == nullptr) {
  8158. type = check_type(c, cl->type);
  8159. }
  8160. }
  8161. if (type == nullptr) {
  8162. error(node, "Missing type in compound literal");
  8163. return kind;
  8164. }
  8165. Type *t = base_type(type);
  8166. if (is_type_polymorphic(t)) {
  8167. gbString str = type_to_string(type);
  8168. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8169. o->expr = node;
  8170. o->type = type;
  8171. gb_string_free(str);
  8172. return kind;
  8173. }
  8174. switch (t->kind) {
  8175. case Type_Struct: {
  8176. if (cl->elems.count == 0) {
  8177. break; // NOTE(bill): No need to init
  8178. }
  8179. if (t->Struct.is_raw_union) {
  8180. if (cl->elems.count > 0) {
  8181. // NOTE: unions cannot be constant
  8182. is_constant = false;
  8183. if (cl->elems[0]->kind != Ast_FieldValue) {
  8184. gbString type_str = type_to_string(type);
  8185. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8186. gb_string_free(type_str);
  8187. } else {
  8188. if (cl->elems.count != 1) {
  8189. gbString type_str = type_to_string(type);
  8190. 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);
  8191. gb_string_free(type_str);
  8192. } else {
  8193. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8194. }
  8195. }
  8196. }
  8197. break;
  8198. }
  8199. isize field_count = t->Struct.fields.count;
  8200. isize min_field_count = t->Struct.fields.count;
  8201. for (isize i = min_field_count-1; i >= 0; i--) {
  8202. Entity *e = t->Struct.fields[i];
  8203. GB_ASSERT(e->kind == Entity_Variable);
  8204. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8205. min_field_count--;
  8206. } else {
  8207. break;
  8208. }
  8209. }
  8210. if (cl->elems[0]->kind == Ast_FieldValue) {
  8211. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8212. } else {
  8213. bool seen_field_value = false;
  8214. for_array(index, cl->elems) {
  8215. Entity *field = nullptr;
  8216. Ast *elem = cl->elems[index];
  8217. if (elem->kind == Ast_FieldValue) {
  8218. seen_field_value = true;
  8219. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8220. continue;
  8221. } else if (seen_field_value) {
  8222. error(elem, "Value elements cannot be used after a 'field = value'");
  8223. continue;
  8224. }
  8225. if (index >= field_count) {
  8226. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8227. break;
  8228. }
  8229. if (field == nullptr) {
  8230. field = t->Struct.fields[index];
  8231. }
  8232. Operand o = {};
  8233. check_expr_or_type(c, &o, elem, field->type);
  8234. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8235. is_constant = false;
  8236. }
  8237. if (is_constant) {
  8238. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8239. }
  8240. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8241. }
  8242. if (cl->elems.count < field_count) {
  8243. if (min_field_count < field_count) {
  8244. if (cl->elems.count < min_field_count) {
  8245. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8246. }
  8247. } else {
  8248. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8249. }
  8250. }
  8251. }
  8252. break;
  8253. }
  8254. case Type_Slice:
  8255. case Type_Array:
  8256. case Type_DynamicArray:
  8257. case Type_SimdVector:
  8258. case Type_Matrix:
  8259. {
  8260. Type *elem_type = nullptr;
  8261. String context_name = {};
  8262. i64 max_type_count = -1;
  8263. if (t->kind == Type_Slice) {
  8264. elem_type = t->Slice.elem;
  8265. context_name = str_lit("slice literal");
  8266. } else if (t->kind == Type_Array) {
  8267. elem_type = t->Array.elem;
  8268. context_name = str_lit("array literal");
  8269. if (!is_to_be_determined_array_count) {
  8270. max_type_count = t->Array.count;
  8271. }
  8272. } else if (t->kind == Type_DynamicArray) {
  8273. elem_type = t->DynamicArray.elem;
  8274. context_name = str_lit("dynamic array literal");
  8275. is_constant = false;
  8276. if (!build_context.no_dynamic_literals) {
  8277. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8278. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8279. }
  8280. } else if (t->kind == Type_SimdVector) {
  8281. elem_type = t->SimdVector.elem;
  8282. context_name = str_lit("simd vector literal");
  8283. max_type_count = t->SimdVector.count;
  8284. } else if (t->kind == Type_Matrix) {
  8285. elem_type = t->Matrix.elem;
  8286. context_name = str_lit("matrix literal");
  8287. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8288. } else {
  8289. GB_PANIC("unreachable");
  8290. }
  8291. i64 max = 0;
  8292. Type *bet = base_type(elem_type);
  8293. if (!elem_type_can_be_constant(bet)) {
  8294. is_constant = false;
  8295. }
  8296. if (bet == t_invalid) {
  8297. break;
  8298. }
  8299. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8300. RangeCache rc = range_cache_make(heap_allocator());
  8301. defer (range_cache_destroy(&rc));
  8302. for (Ast *elem : cl->elems) {
  8303. if (elem->kind != Ast_FieldValue) {
  8304. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8305. continue;
  8306. }
  8307. ast_node(fv, FieldValue, elem);
  8308. if (is_ast_range(fv->field)) {
  8309. Token op = fv->field->BinaryExpr.op;
  8310. Operand x = {};
  8311. Operand y = {};
  8312. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8313. if (!ok) {
  8314. continue;
  8315. }
  8316. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8317. error(x.expr, "Expected a constant integer as an array field");
  8318. continue;
  8319. }
  8320. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8321. error(y.expr, "Expected a constant integer as an array field");
  8322. continue;
  8323. }
  8324. i64 lo = exact_value_to_i64(x.value);
  8325. i64 hi = exact_value_to_i64(y.value);
  8326. i64 max_index = hi;
  8327. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8328. hi -= 1;
  8329. } else { // .. (inclusive)
  8330. max_index += 1;
  8331. }
  8332. bool new_range = range_cache_add_range(&rc, lo, hi);
  8333. if (!new_range) {
  8334. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8335. continue;
  8336. }
  8337. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8338. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8339. continue;
  8340. }
  8341. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8342. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8343. continue;
  8344. }
  8345. if (max < hi) {
  8346. max = max_index;
  8347. }
  8348. Operand operand = {};
  8349. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8350. check_assignment(c, &operand, elem_type, context_name);
  8351. is_constant = is_constant && operand.mode == Addressing_Constant;
  8352. } else {
  8353. Operand op_index = {};
  8354. check_expr(c, &op_index, fv->field);
  8355. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8356. error(elem, "Expected a constant integer as an array field");
  8357. continue;
  8358. }
  8359. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8360. i64 index = exact_value_to_i64(op_index.value);
  8361. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8362. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8363. continue;
  8364. }
  8365. bool new_index = range_cache_add_index(&rc, index);
  8366. if (!new_index) {
  8367. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8368. continue;
  8369. }
  8370. if (max < index+1) {
  8371. max = index+1;
  8372. }
  8373. Operand operand = {};
  8374. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8375. check_assignment(c, &operand, elem_type, context_name);
  8376. is_constant = is_constant && operand.mode == Addressing_Constant;
  8377. }
  8378. }
  8379. cl->max_count = max;
  8380. } else {
  8381. isize index = 0;
  8382. for (; index < cl->elems.count; index++) {
  8383. Ast *e = cl->elems[index];
  8384. if (e == nullptr) {
  8385. error(node, "Invalid literal element");
  8386. continue;
  8387. }
  8388. if (e->kind == Ast_FieldValue) {
  8389. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8390. continue;
  8391. }
  8392. if (0 <= max_type_count && max_type_count <= index) {
  8393. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8394. }
  8395. Operand operand = {};
  8396. check_expr_with_type_hint(c, &operand, e, elem_type);
  8397. check_assignment(c, &operand, elem_type, context_name);
  8398. is_constant = is_constant && operand.mode == Addressing_Constant;
  8399. }
  8400. if (max < index) {
  8401. max = index;
  8402. }
  8403. }
  8404. if (t->kind == Type_Array) {
  8405. if (is_to_be_determined_array_count) {
  8406. t->Array.count = max;
  8407. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8408. if (0 < max && max < t->Array.count) {
  8409. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8410. }
  8411. }
  8412. }
  8413. if (t->kind == Type_SimdVector) {
  8414. if (!is_constant) {
  8415. // error(node, "Expected all constant elements for a simd vector");
  8416. }
  8417. }
  8418. if (t->kind == Type_DynamicArray) {
  8419. if (build_context.no_dynamic_literals && cl->elems.count) {
  8420. error(node, "Compound literals of dynamic types have been disabled");
  8421. }
  8422. }
  8423. if (t->kind == Type_Matrix) {
  8424. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8425. if (0 < max && max < max_type_count) {
  8426. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8427. }
  8428. }
  8429. }
  8430. break;
  8431. }
  8432. case Type_EnumeratedArray:
  8433. {
  8434. Type *elem_type = t->EnumeratedArray.elem;
  8435. Type *index_type = t->EnumeratedArray.index;
  8436. String context_name = str_lit("enumerated array literal");
  8437. i64 max_type_count = t->EnumeratedArray.count;
  8438. gbString index_type_str = type_to_string(index_type);
  8439. defer (gb_string_free(index_type_str));
  8440. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8441. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8442. String total_lo_string = {};
  8443. String total_hi_string = {};
  8444. GB_ASSERT(is_type_enum(index_type));
  8445. {
  8446. Type *bt = base_type(index_type);
  8447. GB_ASSERT(bt->kind == Type_Enum);
  8448. for (Entity *f : bt->Enum.fields) {
  8449. if (f->kind != Entity_Constant) {
  8450. continue;
  8451. }
  8452. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8453. total_lo_string = f->token.string;
  8454. }
  8455. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8456. total_hi_string = f->token.string;
  8457. }
  8458. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8459. break;
  8460. }
  8461. }
  8462. }
  8463. i64 max = 0;
  8464. Type *bet = base_type(elem_type);
  8465. if (!elem_type_can_be_constant(bet)) {
  8466. is_constant = false;
  8467. }
  8468. if (bet == t_invalid) {
  8469. break;
  8470. }
  8471. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8472. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8473. defer (map_destroy(&seen));
  8474. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8475. RangeCache rc = range_cache_make(heap_allocator());
  8476. defer (range_cache_destroy(&rc));
  8477. for (Ast *elem : cl->elems) {
  8478. if (elem->kind != Ast_FieldValue) {
  8479. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8480. continue;
  8481. }
  8482. ast_node(fv, FieldValue, elem);
  8483. if (is_ast_range(fv->field)) {
  8484. Token op = fv->field->BinaryExpr.op;
  8485. Operand x = {};
  8486. Operand y = {};
  8487. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8488. if (!ok) {
  8489. continue;
  8490. }
  8491. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8492. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8493. continue;
  8494. }
  8495. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8496. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8497. continue;
  8498. }
  8499. i64 lo = exact_value_to_i64(x.value);
  8500. i64 hi = exact_value_to_i64(y.value);
  8501. i64 max_index = hi;
  8502. if (op.kind == Token_RangeHalf) {
  8503. hi -= 1;
  8504. }
  8505. bool new_range = range_cache_add_range(&rc, lo, hi);
  8506. if (!new_range) {
  8507. gbString lo_str = expr_to_string(x.expr);
  8508. gbString hi_str = expr_to_string(y.expr);
  8509. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8510. gb_string_free(hi_str);
  8511. gb_string_free(lo_str);
  8512. continue;
  8513. }
  8514. // NOTE(bill): These are sanity checks for invalid enum values
  8515. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8516. gbString lo_str = expr_to_string(x.expr);
  8517. 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));
  8518. gb_string_free(lo_str);
  8519. continue;
  8520. }
  8521. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8522. gbString hi_str = expr_to_string(y.expr);
  8523. 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));
  8524. gb_string_free(hi_str);
  8525. continue;
  8526. }
  8527. if (max < hi) {
  8528. max = max_index;
  8529. }
  8530. Operand operand = {};
  8531. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8532. check_assignment(c, &operand, elem_type, context_name);
  8533. is_constant = is_constant && operand.mode == Addressing_Constant;
  8534. TokenKind upper_op = Token_LtEq;
  8535. if (op.kind == Token_RangeHalf) {
  8536. upper_op = Token_Lt;
  8537. }
  8538. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8539. } else {
  8540. Operand op_index = {};
  8541. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8542. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8543. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8544. continue;
  8545. }
  8546. i64 index = exact_value_to_i64(op_index.value);
  8547. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8548. gbString idx_str = expr_to_string(op_index.expr);
  8549. 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));
  8550. gb_string_free(idx_str);
  8551. continue;
  8552. }
  8553. bool new_index = range_cache_add_index(&rc, index);
  8554. if (!new_index) {
  8555. gbString idx_str = expr_to_string(op_index.expr);
  8556. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8557. gb_string_free(idx_str);
  8558. continue;
  8559. }
  8560. if (max < index+1) {
  8561. max = index+1;
  8562. }
  8563. Operand operand = {};
  8564. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8565. check_assignment(c, &operand, elem_type, context_name);
  8566. is_constant = is_constant && operand.mode == Addressing_Constant;
  8567. add_to_seen_map(c, &seen, op_index);
  8568. }
  8569. }
  8570. cl->max_count = max;
  8571. } else {
  8572. isize index = 0;
  8573. for (; index < cl->elems.count; index++) {
  8574. Ast *e = cl->elems[index];
  8575. if (e == nullptr) {
  8576. error(node, "Invalid literal element");
  8577. continue;
  8578. }
  8579. if (e->kind == Ast_FieldValue) {
  8580. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8581. continue;
  8582. }
  8583. if (0 <= max_type_count && max_type_count <= index) {
  8584. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8585. }
  8586. Operand operand = {};
  8587. check_expr_with_type_hint(c, &operand, e, elem_type);
  8588. check_assignment(c, &operand, elem_type, context_name);
  8589. is_constant = is_constant && operand.mode == Addressing_Constant;
  8590. }
  8591. if (max < index) {
  8592. max = index;
  8593. }
  8594. }
  8595. bool was_error = false;
  8596. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8597. if (0 < max && max < t->EnumeratedArray.count) {
  8598. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8599. was_error = true;
  8600. } else {
  8601. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8602. was_error = true;
  8603. }
  8604. }
  8605. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8606. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8607. TEMPORARY_ALLOCATOR_GUARD();
  8608. Type *et = base_type(index_type);
  8609. GB_ASSERT(et->kind == Type_Enum);
  8610. auto fields = et->Enum.fields;
  8611. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8612. for (Entity *f : fields) {
  8613. if (f->kind != Entity_Constant) {
  8614. continue;
  8615. }
  8616. ExactValue v = f->Constant.value;
  8617. auto found = map_get(&seen, hash_exact_value(v));
  8618. if (!found) {
  8619. array_add(&unhandled, f);
  8620. }
  8621. }
  8622. if (unhandled.count > 0) {
  8623. begin_error_block();
  8624. defer (end_error_block());
  8625. if (unhandled.count == 1) {
  8626. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8627. } else {
  8628. error(node, "Unhandled enumerated array cases:");
  8629. for_array(i, unhandled) {
  8630. Entity *f = unhandled[i];
  8631. error_line("\t%.*s\n", LIT(f->token.string));
  8632. }
  8633. }
  8634. error_line("\n");
  8635. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8636. }
  8637. }
  8638. break;
  8639. }
  8640. case Type_Basic: {
  8641. if (!is_type_any(t)) {
  8642. if (cl->elems.count != 0) {
  8643. gbString s = type_to_string(t);
  8644. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8645. gb_string_free(s);
  8646. is_constant = false;
  8647. }
  8648. break;
  8649. }
  8650. if (cl->elems.count == 0) {
  8651. break; // NOTE(bill): No need to init
  8652. }
  8653. { // Checker values
  8654. Type *field_types[2] = {t_rawptr, t_typeid};
  8655. isize field_count = 2;
  8656. if (cl->elems[0]->kind == Ast_FieldValue) {
  8657. bool fields_visited[2] = {};
  8658. for_array(i, cl->elems) {
  8659. Ast *elem = cl->elems[i];
  8660. if (elem->kind != Ast_FieldValue) {
  8661. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8662. continue;
  8663. }
  8664. ast_node(fv, FieldValue, elem);
  8665. if (fv->field->kind != Ast_Ident) {
  8666. gbString expr_str = expr_to_string(fv->field);
  8667. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8668. gb_string_free(expr_str);
  8669. continue;
  8670. }
  8671. String name = fv->field->Ident.token.string;
  8672. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8673. if (sel.entity == nullptr) {
  8674. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8675. continue;
  8676. }
  8677. isize index = sel.index[0];
  8678. if (fields_visited[index]) {
  8679. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8680. continue;
  8681. }
  8682. fields_visited[index] = true;
  8683. check_expr(c, o, fv->value);
  8684. // NOTE(bill): 'any' literals can never be constant
  8685. is_constant = false;
  8686. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8687. }
  8688. } else {
  8689. for_array(index, cl->elems) {
  8690. Ast *elem = cl->elems[index];
  8691. if (elem->kind == Ast_FieldValue) {
  8692. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8693. continue;
  8694. }
  8695. check_expr(c, o, elem);
  8696. if (index >= field_count) {
  8697. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8698. break;
  8699. }
  8700. // NOTE(bill): 'any' literals can never be constant
  8701. is_constant = false;
  8702. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8703. }
  8704. if (cl->elems.count < field_count) {
  8705. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8706. }
  8707. }
  8708. }
  8709. break;
  8710. }
  8711. case Type_Map: {
  8712. if (cl->elems.count == 0) {
  8713. break;
  8714. }
  8715. is_constant = false;
  8716. { // Checker values
  8717. bool key_is_typeid = is_type_typeid(t->Map.key);
  8718. bool value_is_typeid = is_type_typeid(t->Map.value);
  8719. for (Ast *elem : cl->elems) {
  8720. if (elem->kind != Ast_FieldValue) {
  8721. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8722. continue;
  8723. }
  8724. ast_node(fv, FieldValue, elem);
  8725. if (key_is_typeid) {
  8726. check_expr_or_type(c, o, fv->field, t->Map.key);
  8727. } else {
  8728. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8729. }
  8730. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8731. if (o->mode == Addressing_Invalid) {
  8732. continue;
  8733. }
  8734. if (value_is_typeid) {
  8735. check_expr_or_type(c, o, fv->value, t->Map.value);
  8736. } else {
  8737. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8738. }
  8739. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8740. }
  8741. }
  8742. if (build_context.no_dynamic_literals && cl->elems.count) {
  8743. error(node, "Compound literals of dynamic types have been disabled");
  8744. } else {
  8745. add_map_reserve_dependencies(c);
  8746. add_map_set_dependencies(c);
  8747. }
  8748. break;
  8749. }
  8750. case Type_BitSet: {
  8751. if (cl->elems.count == 0) {
  8752. break; // NOTE(bill): No need to init
  8753. }
  8754. Type *et = base_type(t->BitSet.elem);
  8755. isize field_count = 0;
  8756. if (et->kind == Type_Enum) {
  8757. field_count = et->Enum.fields.count;
  8758. }
  8759. if (cl->elems[0]->kind == Ast_FieldValue) {
  8760. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8761. is_constant = false;
  8762. } else {
  8763. for (Ast *elem : cl->elems) {
  8764. if (elem->kind == Ast_FieldValue) {
  8765. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8766. continue;
  8767. }
  8768. check_expr_with_type_hint(c, o, elem, et);
  8769. if (is_constant) {
  8770. is_constant = o->mode == Addressing_Constant;
  8771. }
  8772. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8773. if (o->mode == Addressing_Constant) {
  8774. i64 lower = t->BitSet.lower;
  8775. i64 upper = t->BitSet.upper;
  8776. i64 v = exact_value_to_i64(o->value);
  8777. if (lower <= v && v <= upper) {
  8778. // okay
  8779. } else {
  8780. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8781. continue;
  8782. }
  8783. }
  8784. }
  8785. }
  8786. break;
  8787. }
  8788. default: {
  8789. if (cl->elems.count == 0) {
  8790. break; // NOTE(bill): No need to init
  8791. }
  8792. gbString str = type_to_string(type);
  8793. error(node, "Invalid compound literal type '%s'", str);
  8794. gb_string_free(str);
  8795. return kind;
  8796. }
  8797. }
  8798. if (is_constant) {
  8799. o->mode = Addressing_Constant;
  8800. if (is_type_bit_set(type)) {
  8801. // NOTE(bill): Encode as an integer
  8802. Type *bt = base_type(type);
  8803. BigInt bits = {};
  8804. BigInt one = {};
  8805. big_int_from_u64(&one, 1);
  8806. for (Ast *e : cl->elems) {
  8807. GB_ASSERT(e->kind != Ast_FieldValue);
  8808. TypeAndValue tav = e->tav;
  8809. if (tav.mode != Addressing_Constant) {
  8810. continue;
  8811. }
  8812. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8813. i64 v = big_int_to_i64(&tav.value.value_integer);
  8814. i64 lower = bt->BitSet.lower;
  8815. u64 index = cast(u64)(v-lower);
  8816. BigInt bit = {};
  8817. big_int_from_u64(&bit, index);
  8818. big_int_shl(&bit, &one, &bit);
  8819. big_int_or(&bits, &bits, &bit);
  8820. }
  8821. o->value.kind = ExactValue_Integer;
  8822. o->value.value_integer = bits;
  8823. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8824. ExactValue value = exact_value_compound(node);
  8825. Type *bt = core_type(type);
  8826. if (bt->kind == Type_Basic) {
  8827. if (bt->Basic.flags & BasicFlag_Boolean) {
  8828. value = exact_value_bool(false);
  8829. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8830. value = exact_value_i64(0);
  8831. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8832. value = exact_value_i64(0);
  8833. } else if (bt->Basic.flags & BasicFlag_Float) {
  8834. value = exact_value_float(0);
  8835. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8836. value = exact_value_complex(0, 0);
  8837. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8838. value = exact_value_quaternion(0, 0, 0, 0);
  8839. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8840. value = exact_value_pointer(0);
  8841. } else if (bt->Basic.flags & BasicFlag_String) {
  8842. String empty_string = {};
  8843. value = exact_value_string(empty_string);
  8844. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8845. value = exact_value_i64(0);
  8846. }
  8847. }
  8848. o->value = value;
  8849. } else {
  8850. o->value = exact_value_compound(node);
  8851. }
  8852. } else {
  8853. o->mode = Addressing_Value;
  8854. }
  8855. o->type = type;
  8856. return kind;
  8857. }
  8858. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8859. ExprKind kind = Expr_Expr;
  8860. ast_node(ta, TypeAssertion, node);
  8861. check_expr(c, o, ta->expr);
  8862. node->viral_state_flags |= ta->expr->viral_state_flags;
  8863. if (o->mode == Addressing_Invalid) {
  8864. o->expr = node;
  8865. return kind;
  8866. }
  8867. if (o->mode == Addressing_Constant) {
  8868. gbString expr_str = expr_to_string(o->expr);
  8869. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8870. gb_string_free(expr_str);
  8871. o->mode = Addressing_Invalid;
  8872. o->expr = node;
  8873. return kind;
  8874. }
  8875. if (is_type_untyped(o->type)) {
  8876. gbString expr_str = expr_to_string(o->expr);
  8877. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8878. gb_string_free(expr_str);
  8879. o->mode = Addressing_Invalid;
  8880. o->expr = node;
  8881. return kind;
  8882. }
  8883. Type *src = type_deref(o->type);
  8884. Type *bsrc = base_type(src);
  8885. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8886. if (!is_type_union(src)) {
  8887. gbString str = type_to_string(o->type);
  8888. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8889. gb_string_free(str);
  8890. o->mode = Addressing_Invalid;
  8891. o->expr = node;
  8892. return kind;
  8893. }
  8894. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8895. bool allowed = false;
  8896. for (Type *vt : bsrc->Union.variants) {
  8897. if (are_types_identical(vt, type_hint)) {
  8898. allowed = true;
  8899. add_type_info_type(c, vt);
  8900. break;
  8901. }
  8902. }
  8903. if (allowed) {
  8904. add_type_info_type(c, o->type);
  8905. o->type = type_hint;
  8906. o->mode = Addressing_OptionalOk;
  8907. return kind;
  8908. }
  8909. }
  8910. if (bsrc->Union.variants.count != 1) {
  8911. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8912. o->mode = Addressing_Invalid;
  8913. o->expr = node;
  8914. return kind;
  8915. }
  8916. add_type_info_type(c, o->type);
  8917. add_type_info_type(c, bsrc->Union.variants[0]);
  8918. o->type = bsrc->Union.variants[0];
  8919. o->mode = Addressing_OptionalOk;
  8920. } else {
  8921. Type *t = check_type(c, ta->type);
  8922. Type *dst = t;
  8923. if (is_type_union(src)) {
  8924. bool ok = false;
  8925. for (Type *vt : bsrc->Union.variants) {
  8926. if (are_types_identical(vt, dst)) {
  8927. ok = true;
  8928. break;
  8929. }
  8930. }
  8931. if (!ok) {
  8932. gbString expr_str = expr_to_string(o->expr);
  8933. gbString dst_type_str = type_to_string(t);
  8934. defer (gb_string_free(expr_str));
  8935. defer (gb_string_free(dst_type_str));
  8936. if (bsrc->Union.variants.count == 0) {
  8937. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8938. } else {
  8939. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8940. }
  8941. o->mode = Addressing_Invalid;
  8942. o->expr = node;
  8943. return kind;
  8944. }
  8945. add_type_info_type(c, o->type);
  8946. add_type_info_type(c, t);
  8947. o->type = t;
  8948. o->mode = Addressing_OptionalOk;
  8949. } else if (is_type_any(src)) {
  8950. o->type = t;
  8951. o->mode = Addressing_OptionalOk;
  8952. add_type_info_type(c, o->type);
  8953. add_type_info_type(c, t);
  8954. } else {
  8955. gbString str = type_to_string(o->type);
  8956. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8957. gb_string_free(str);
  8958. o->mode = Addressing_Invalid;
  8959. o->expr = node;
  8960. return kind;
  8961. }
  8962. }
  8963. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8964. add_package_dependency(c, "runtime", "type_assertion_check");
  8965. add_package_dependency(c, "runtime", "type_assertion_check2");
  8966. }
  8967. return kind;
  8968. }
  8969. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8970. ast_node(se, SelectorCallExpr, node);
  8971. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8972. // COM APIs is a great example of where this kind of thing is extremely useful
  8973. // General idea:
  8974. //
  8975. // x->y(123) == x.y(x, 123)
  8976. //
  8977. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8978. // Just regenerating a new AST aids things
  8979. //
  8980. // TODO(bill): Is this a good hack or not?
  8981. //
  8982. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8983. if (se->modified_call) {
  8984. // Prevent double evaluation
  8985. o->expr = node;
  8986. o->type = node->tav.type;
  8987. o->value = node->tav.value;
  8988. o->mode = node->tav.mode;
  8989. return Expr_Expr;
  8990. }
  8991. bool allow_arrow_right_selector_expr;
  8992. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8993. c->allow_arrow_right_selector_expr = true;
  8994. Operand x = {};
  8995. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8996. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8997. if (x.mode == Addressing_Invalid || x.type == t_invalid) {
  8998. o->mode = Addressing_Invalid;
  8999. o->type = t_invalid;
  9000. o->expr = node;
  9001. return kind;
  9002. }
  9003. if (!is_type_proc(x.type)) {
  9004. gbString type_str = type_to_string(x.type);
  9005. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9006. gb_string_free(type_str);
  9007. o->mode = Addressing_Invalid;
  9008. o->type = t_invalid;
  9009. o->expr = node;
  9010. return Expr_Stmt;
  9011. }
  9012. ast_node(ce, CallExpr, se->call);
  9013. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9014. Ast *first_arg = x.expr->SelectorExpr.expr;
  9015. GB_ASSERT(first_arg != nullptr);
  9016. Entity *e = entity_of_node(se->expr);
  9017. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9018. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9019. }
  9020. Type *pt = base_type(x.type);
  9021. GB_ASSERT(pt->kind == Type_Proc);
  9022. Type *first_type = nullptr;
  9023. String first_arg_name = {};
  9024. if (pt->Proc.param_count > 0) {
  9025. Entity *f = pt->Proc.params->Tuple.variables[0];
  9026. first_type = f->type;
  9027. first_arg_name = f->token.string;
  9028. }
  9029. if (first_arg_name.len == 0) {
  9030. first_arg_name = str_lit("_");
  9031. }
  9032. if (first_type == nullptr) {
  9033. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9034. o->mode = Addressing_Invalid;
  9035. o->type = t_invalid;
  9036. o->expr = node;
  9037. return Expr_Stmt;
  9038. }
  9039. Operand y = {};
  9040. y.mode = first_arg->tav.mode;
  9041. y.type = first_arg->tav.type;
  9042. y.value = first_arg->tav.value;
  9043. if (check_is_assignable_to(c, &y, first_type)) {
  9044. // Do nothing, it's valid
  9045. } else {
  9046. Operand z = y;
  9047. z.type = type_deref(y.type);
  9048. if (check_is_assignable_to(c, &z, first_type)) {
  9049. // NOTE(bill): AST GENERATION HACK!
  9050. Token op = {Token_Pointer};
  9051. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9052. } else if (y.mode == Addressing_Variable) {
  9053. Operand w = y;
  9054. w.type = alloc_type_pointer(y.type);
  9055. if (check_is_assignable_to(c, &w, first_type)) {
  9056. // NOTE(bill): AST GENERATION HACK!
  9057. Token op = {Token_And};
  9058. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9059. }
  9060. }
  9061. }
  9062. if (ce->args.count > 0) {
  9063. bool fail = false;
  9064. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9065. for (Ast *arg : ce->args) {
  9066. bool mix = false;
  9067. if (first_is_field_value) {
  9068. mix = arg->kind != Ast_FieldValue;
  9069. } else {
  9070. mix = arg->kind == Ast_FieldValue;
  9071. }
  9072. if (mix) {
  9073. fail = true;
  9074. break;
  9075. }
  9076. }
  9077. if (!fail && first_is_field_value) {
  9078. Token op = {Token_Eq};
  9079. AstFile *f = first_arg->file();
  9080. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9081. }
  9082. }
  9083. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9084. modified_args[0] = first_arg;
  9085. slice_copy(&modified_args, ce->args, 1);
  9086. ce->args = modified_args;
  9087. se->modified_call = true;
  9088. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9089. c->allow_arrow_right_selector_expr = true;
  9090. check_expr_base(c, o, se->call, type_hint);
  9091. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9092. o->expr = node;
  9093. return Expr_Expr;
  9094. }
  9095. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9096. ExprKind kind = Expr_Expr;
  9097. ast_node(ie, IndexExpr, node);
  9098. check_expr(c, o, ie->expr);
  9099. node->viral_state_flags |= ie->expr->viral_state_flags;
  9100. if (o->mode == Addressing_Invalid) {
  9101. o->expr = node;
  9102. return kind;
  9103. }
  9104. Type *t = base_type(type_deref(o->type));
  9105. bool is_ptr = is_type_pointer(o->type);
  9106. bool is_const = o->mode == Addressing_Constant;
  9107. if (is_type_map(t)) {
  9108. Operand key = {};
  9109. if (is_type_typeid(t->Map.key)) {
  9110. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9111. } else {
  9112. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9113. }
  9114. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9115. if (key.mode == Addressing_Invalid) {
  9116. o->mode = Addressing_Invalid;
  9117. o->expr = node;
  9118. return kind;
  9119. }
  9120. o->mode = Addressing_MapIndex;
  9121. o->type = t->Map.value;
  9122. o->expr = node;
  9123. add_map_get_dependencies(c);
  9124. add_map_set_dependencies(c);
  9125. return Expr_Expr;
  9126. }
  9127. i64 max_count = -1;
  9128. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9129. if (is_const) {
  9130. if (is_type_array(t)) {
  9131. // OKay
  9132. } else if (is_type_slice(t)) {
  9133. // Okay
  9134. } else if (is_type_enumerated_array(t)) {
  9135. // Okay
  9136. } else if (is_type_string(t)) {
  9137. // Okay
  9138. } else if (is_type_relative_slice(t)) {
  9139. // Okay
  9140. } else if (is_type_matrix(t)) {
  9141. // Okay
  9142. } else {
  9143. valid = false;
  9144. }
  9145. }
  9146. if (!valid) {
  9147. gbString str = expr_to_string(o->expr);
  9148. gbString type_str = type_to_string(o->type);
  9149. defer (gb_string_free(str));
  9150. defer (gb_string_free(type_str));
  9151. if (is_const) {
  9152. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9153. } else {
  9154. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9155. }
  9156. o->mode = Addressing_Invalid;
  9157. o->expr = node;
  9158. return kind;
  9159. }
  9160. if (ie->index == nullptr) {
  9161. gbString str = expr_to_string(o->expr);
  9162. error(o->expr, "Missing index for '%s'", str);
  9163. gb_string_free(str);
  9164. o->mode = Addressing_Invalid;
  9165. o->expr = node;
  9166. return kind;
  9167. }
  9168. Type *index_type_hint = nullptr;
  9169. if (is_type_enumerated_array(t)) {
  9170. Type *bt = base_type(t);
  9171. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9172. index_type_hint = bt->EnumeratedArray.index;
  9173. }
  9174. i64 index = 0;
  9175. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9176. if (is_const) {
  9177. if (index < 0) {
  9178. gbString str = expr_to_string(o->expr);
  9179. error(o->expr, "Cannot index a constant '%s'", str);
  9180. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9181. gb_string_free(str);
  9182. o->mode = Addressing_Invalid;
  9183. o->expr = node;
  9184. return kind;
  9185. } else if (ok) {
  9186. ExactValue value = type_and_value_of_expr(ie->expr).value;
  9187. o->mode = Addressing_Constant;
  9188. bool success = false;
  9189. bool finish = false;
  9190. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9191. if (!success) {
  9192. gbString str = expr_to_string(o->expr);
  9193. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9194. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9195. gb_string_free(str);
  9196. o->mode = Addressing_Invalid;
  9197. o->expr = node;
  9198. return kind;
  9199. }
  9200. }
  9201. }
  9202. if (type_hint != nullptr && is_type_matrix(t)) {
  9203. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9204. // if a type hint exists
  9205. }
  9206. return kind;
  9207. }
  9208. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9209. ExprKind kind = Expr_Stmt;
  9210. ast_node(se, SliceExpr, node);
  9211. check_expr(c, o, se->expr);
  9212. node->viral_state_flags |= se->expr->viral_state_flags;
  9213. if (o->mode == Addressing_Invalid) {
  9214. o->mode = Addressing_Invalid;
  9215. o->expr = node;
  9216. return kind;
  9217. }
  9218. bool valid = false;
  9219. i64 max_count = -1;
  9220. Type *t = base_type(type_deref(o->type));
  9221. switch (t->kind) {
  9222. case Type_Basic:
  9223. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9224. valid = true;
  9225. if (o->mode == Addressing_Constant) {
  9226. max_count = o->value.value_string.len;
  9227. }
  9228. o->type = type_deref(o->type);
  9229. }
  9230. break;
  9231. case Type_Array:
  9232. valid = true;
  9233. max_count = t->Array.count;
  9234. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9235. gbString str = expr_to_string(node);
  9236. error(node, "Cannot slice array '%s', value is not addressable", str);
  9237. gb_string_free(str);
  9238. o->mode = Addressing_Invalid;
  9239. o->expr = node;
  9240. return kind;
  9241. }
  9242. o->type = alloc_type_slice(t->Array.elem);
  9243. break;
  9244. case Type_MultiPointer:
  9245. valid = true;
  9246. o->type = type_deref(o->type);
  9247. break;
  9248. case Type_Slice:
  9249. valid = true;
  9250. o->type = type_deref(o->type);
  9251. break;
  9252. case Type_DynamicArray:
  9253. valid = true;
  9254. o->type = alloc_type_slice(t->DynamicArray.elem);
  9255. break;
  9256. case Type_Struct:
  9257. if (is_type_soa_struct(t)) {
  9258. valid = true;
  9259. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9260. }
  9261. break;
  9262. case Type_RelativeSlice:
  9263. valid = true;
  9264. o->type = t->RelativeSlice.slice_type;
  9265. if (o->mode != Addressing_Variable) {
  9266. gbString str = expr_to_string(node);
  9267. error(node, "Cannot relative slice '%s', as value is not addressable", str);
  9268. gb_string_free(str);
  9269. o->mode = Addressing_Invalid;
  9270. o->expr = node;
  9271. return kind;
  9272. }
  9273. break;
  9274. case Type_EnumeratedArray:
  9275. {
  9276. gbString str = expr_to_string(o->expr);
  9277. gbString type_str = type_to_string(o->type);
  9278. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9279. gb_string_free(type_str);
  9280. gb_string_free(str);
  9281. o->mode = Addressing_Invalid;
  9282. o->expr = node;
  9283. return kind;
  9284. }
  9285. break;
  9286. }
  9287. if (!valid) {
  9288. gbString str = expr_to_string(o->expr);
  9289. gbString type_str = type_to_string(o->type);
  9290. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9291. gb_string_free(type_str);
  9292. gb_string_free(str);
  9293. o->mode = Addressing_Invalid;
  9294. o->expr = node;
  9295. return kind;
  9296. }
  9297. if (se->low == nullptr && se->high != nullptr) {
  9298. // It is okay to continue as it will assume the 1st index is zero
  9299. }
  9300. i64 indices[2] = {};
  9301. Ast *nodes[2] = {se->low, se->high};
  9302. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9303. i64 index = max_count;
  9304. if (nodes[i] != nullptr) {
  9305. i64 capacity = -1;
  9306. if (max_count >= 0) {
  9307. capacity = max_count;
  9308. }
  9309. i64 j = 0;
  9310. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9311. index = j;
  9312. }
  9313. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9314. } else if (i == 0) {
  9315. index = 0;
  9316. }
  9317. indices[i] = index;
  9318. }
  9319. for (isize i = 0; i < gb_count_of(indices); i++) {
  9320. i64 a = indices[i];
  9321. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9322. i64 b = indices[j];
  9323. if (a > b && b >= 0) {
  9324. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9325. }
  9326. }
  9327. }
  9328. if (max_count < 0) {
  9329. if (o->mode == Addressing_Constant) {
  9330. gbString s = expr_to_string(se->expr);
  9331. error(se->expr, "Cannot slice constant value '%s'", s);
  9332. gb_string_free(s);
  9333. }
  9334. }
  9335. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9336. /*
  9337. x[:] -> [^]T
  9338. x[i:] -> [^]T
  9339. x[:n] -> []T
  9340. x[i:n] -> []T
  9341. */
  9342. o->type = alloc_type_slice(t->MultiPointer.elem);
  9343. }
  9344. o->mode = Addressing_Value;
  9345. if (is_type_string(t) && max_count >= 0) {
  9346. bool all_constant = true;
  9347. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9348. if (nodes[i] != nullptr) {
  9349. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9350. if (tav.mode != Addressing_Constant) {
  9351. all_constant = false;
  9352. break;
  9353. }
  9354. }
  9355. }
  9356. if (!all_constant) {
  9357. gbString str = expr_to_string(o->expr);
  9358. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9359. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9360. gb_string_free(str);
  9361. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9362. o->expr = node;
  9363. return kind;
  9364. }
  9365. String s = {};
  9366. if (o->value.kind == ExactValue_String) {
  9367. s = o->value.value_string;
  9368. }
  9369. o->mode = Addressing_Constant;
  9370. o->type = t;
  9371. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9372. }
  9373. return kind;
  9374. }
  9375. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9376. u32 prev_state_flags = c->state_flags;
  9377. defer (c->state_flags = prev_state_flags);
  9378. if (node->state_flags != 0) {
  9379. u32 in = node->state_flags;
  9380. u32 out = c->state_flags;
  9381. if (in & StateFlag_no_bounds_check) {
  9382. out |= StateFlag_no_bounds_check;
  9383. out &= ~StateFlag_bounds_check;
  9384. } else if (in & StateFlag_bounds_check) {
  9385. out |= StateFlag_bounds_check;
  9386. out &= ~StateFlag_no_bounds_check;
  9387. }
  9388. if (in & StateFlag_no_type_assert) {
  9389. out |= StateFlag_no_type_assert;
  9390. out &= ~StateFlag_type_assert;
  9391. } else if (in & StateFlag_type_assert) {
  9392. out |= StateFlag_type_assert;
  9393. out &= ~StateFlag_no_type_assert;
  9394. }
  9395. c->state_flags = out;
  9396. }
  9397. ExprKind kind = Expr_Stmt;
  9398. o->mode = Addressing_Invalid;
  9399. o->type = t_invalid;
  9400. o->value = {ExactValue_Invalid};
  9401. switch (node->kind) {
  9402. default:
  9403. return kind;
  9404. case_ast_node(be, BadExpr, node)
  9405. return kind;
  9406. case_end;
  9407. case_ast_node(i, Implicit, node)
  9408. switch (i->kind) {
  9409. case Token_context:
  9410. {
  9411. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9412. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  9413. return kind;
  9414. }
  9415. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9416. c->scope->flags |= ScopeFlag_ContextDefined;
  9417. }
  9418. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9419. error(node, "'context' has not been defined within this scope");
  9420. // Continue with value
  9421. }
  9422. init_core_context(c->checker);
  9423. o->mode = Addressing_Context;
  9424. o->type = t_context;
  9425. }
  9426. break;
  9427. default:
  9428. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9429. return kind;
  9430. }
  9431. case_end;
  9432. case_ast_node(i, Ident, node);
  9433. check_ident(c, o, node, nullptr, type_hint, false);
  9434. case_end;
  9435. case_ast_node(u, Uninit, node);
  9436. o->mode = Addressing_Value;
  9437. o->type = t_untyped_uninit;
  9438. error(node, "Use of --- outside of variable declaration");
  9439. case_end;
  9440. case_ast_node(bl, BasicLit, node);
  9441. Type *t = t_invalid;
  9442. switch (node->tav.value.kind) {
  9443. case ExactValue_String: t = t_untyped_string; break;
  9444. case ExactValue_Float: t = t_untyped_float; break;
  9445. case ExactValue_Complex: t = t_untyped_complex; break;
  9446. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9447. case ExactValue_Integer:
  9448. t = t_untyped_integer;
  9449. if (bl->token.kind == Token_Rune) {
  9450. t = t_untyped_rune;
  9451. }
  9452. break;
  9453. default:
  9454. GB_PANIC("Unhandled value type for basic literal");
  9455. break;
  9456. }
  9457. o->mode = Addressing_Constant;
  9458. o->type = t;
  9459. o->value = node->tav.value;
  9460. case_end;
  9461. case_ast_node(bd, BasicDirective, node);
  9462. kind = check_basic_directive_expr(c, o, node, type_hint);
  9463. case_end;
  9464. case_ast_node(pg, ProcGroup, node);
  9465. error(node, "Illegal use of a procedure group");
  9466. o->mode = Addressing_Invalid;
  9467. case_end;
  9468. case_ast_node(pl, ProcLit, node);
  9469. CheckerContext ctx = *c;
  9470. DeclInfo *decl = nullptr;
  9471. Type *type = alloc_type(Type_Proc);
  9472. check_open_scope(&ctx, pl->type);
  9473. {
  9474. decl = make_decl_info(ctx.scope, ctx.decl);
  9475. decl->proc_lit = node;
  9476. ctx.decl = decl;
  9477. defer (ctx.decl = ctx.decl->parent);
  9478. if (pl->tags != 0) {
  9479. error(node, "A procedure literal cannot have tags");
  9480. pl->tags = 0; // TODO(bill): Should I zero this?!
  9481. }
  9482. check_procedure_type(&ctx, type, pl->type);
  9483. if (!is_type_proc(type)) {
  9484. gbString str = expr_to_string(node);
  9485. error(node, "Invalid procedure literal '%s'", str);
  9486. gb_string_free(str);
  9487. check_close_scope(&ctx);
  9488. return kind;
  9489. }
  9490. if (pl->body == nullptr) {
  9491. error(node, "A procedure literal must have a body");
  9492. return kind;
  9493. }
  9494. pl->decl = decl;
  9495. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9496. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9497. array_add(&ctx.checker->nested_proc_lits, decl);
  9498. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9499. }
  9500. check_close_scope(&ctx);
  9501. o->mode = Addressing_Value;
  9502. o->type = type;
  9503. case_end;
  9504. case_ast_node(te, TernaryIfExpr, node);
  9505. kind = check_ternary_if_expr(c, o, node, type_hint);
  9506. case_end;
  9507. case_ast_node(te, TernaryWhenExpr, node);
  9508. kind = check_ternary_when_expr(c, o, node, type_hint);
  9509. case_end;
  9510. case_ast_node(oe, OrElseExpr, node);
  9511. return check_or_else_expr(c, o, node, type_hint);
  9512. case_end;
  9513. case_ast_node(re, OrReturnExpr, node);
  9514. return check_or_return_expr(c, o, node, type_hint);
  9515. case_end;
  9516. case_ast_node(cl, CompoundLit, node);
  9517. kind = check_compound_literal(c, o, node, type_hint);
  9518. case_end;
  9519. case_ast_node(pe, ParenExpr, node);
  9520. kind = check_expr_base(c, o, pe->expr, type_hint);
  9521. node->viral_state_flags |= pe->expr->viral_state_flags;
  9522. o->expr = node;
  9523. case_end;
  9524. case_ast_node(te, TagExpr, node);
  9525. String name = te->name.string;
  9526. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9527. if (te->expr) {
  9528. kind = check_expr_base(c, o, te->expr, type_hint);
  9529. node->viral_state_flags |= te->expr->viral_state_flags;
  9530. }
  9531. o->expr = node;
  9532. case_end;
  9533. case_ast_node(ta, TypeAssertion, node);
  9534. kind = check_type_assertion(c, o, node, type_hint);
  9535. case_end;
  9536. case_ast_node(tc, TypeCast, node);
  9537. check_expr_or_type(c, o, tc->type);
  9538. if (o->mode != Addressing_Type) {
  9539. gbString str = expr_to_string(tc->type);
  9540. error(tc->type, "Expected a type, got %s", str);
  9541. gb_string_free(str);
  9542. o->mode = Addressing_Invalid;
  9543. }
  9544. if (o->mode == Addressing_Invalid) {
  9545. o->expr = node;
  9546. return kind;
  9547. }
  9548. Type *type = o->type;
  9549. check_expr_base(c, o, tc->expr, type);
  9550. node->viral_state_flags |= tc->expr->viral_state_flags;
  9551. if (o->mode != Addressing_Invalid) {
  9552. switch (tc->token.kind) {
  9553. case Token_transmute:
  9554. check_transmute(c, node, o, type);
  9555. break;
  9556. case Token_cast:
  9557. check_cast(c, o, type);
  9558. break;
  9559. default:
  9560. error(node, "Invalid AST: Invalid casting expression");
  9561. o->mode = Addressing_Invalid;
  9562. break;
  9563. }
  9564. }
  9565. return Expr_Expr;
  9566. case_end;
  9567. case_ast_node(ac, AutoCast, node);
  9568. check_expr_base(c, o, ac->expr, type_hint);
  9569. node->viral_state_flags |= ac->expr->viral_state_flags;
  9570. if (o->mode == Addressing_Invalid) {
  9571. o->expr = node;
  9572. return kind;
  9573. }
  9574. if (type_hint) {
  9575. Type *type = type_of_expr(ac->expr);
  9576. check_cast(c, o, type_hint);
  9577. if (is_type_typed(type) && are_types_identical(type, type_hint)) {
  9578. if (build_context.vet_extra) {
  9579. error(node, "Redundant 'auto_cast' applied to expression");
  9580. }
  9581. }
  9582. }
  9583. o->expr = node;
  9584. return Expr_Expr;
  9585. case_end;
  9586. case_ast_node(ue, UnaryExpr, node);
  9587. Type *th = type_hint;
  9588. if (ue->op.kind == Token_And) {
  9589. th = type_deref(th);
  9590. }
  9591. check_expr_base(c, o, ue->expr, th);
  9592. node->viral_state_flags |= ue->expr->viral_state_flags;
  9593. if (o->mode != Addressing_Invalid) {
  9594. check_unary_expr(c, o, ue->op, node);
  9595. }
  9596. o->expr = node;
  9597. return Expr_Expr;
  9598. case_end;
  9599. case_ast_node(be, BinaryExpr, node);
  9600. check_binary_expr(c, o, node, type_hint, true);
  9601. if (o->mode == Addressing_Invalid) {
  9602. o->expr = node;
  9603. return kind;
  9604. }
  9605. case_end;
  9606. case_ast_node(se, SelectorExpr, node);
  9607. check_selector(c, o, node, type_hint);
  9608. node->viral_state_flags |= se->expr->viral_state_flags;
  9609. case_end;
  9610. case_ast_node(se, SelectorCallExpr, node);
  9611. return check_selector_call_expr(c, o, node, type_hint);
  9612. case_end;
  9613. case_ast_node(ise, ImplicitSelectorExpr, node);
  9614. return check_implicit_selector_expr(c, o, node, type_hint);
  9615. case_end;
  9616. case_ast_node(ie, IndexExpr, node);
  9617. kind = check_index_expr(c, o, node, type_hint);
  9618. case_end;
  9619. case_ast_node(se, SliceExpr, node);
  9620. kind = check_slice_expr(c, o, node, type_hint);
  9621. case_end;
  9622. case_ast_node(mie, MatrixIndexExpr, node);
  9623. check_matrix_index_expr(c, o, node, type_hint);
  9624. o->expr = node;
  9625. return Expr_Expr;
  9626. case_end;
  9627. case_ast_node(ce, CallExpr, node);
  9628. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9629. case_end;
  9630. case_ast_node(de, DerefExpr, node);
  9631. check_expr_or_type(c, o, de->expr);
  9632. node->viral_state_flags |= de->expr->viral_state_flags;
  9633. if (o->mode == Addressing_Invalid) {
  9634. o->mode = Addressing_Invalid;
  9635. o->expr = node;
  9636. return kind;
  9637. } else {
  9638. Type *t = base_type(o->type);
  9639. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9640. o->mode = Addressing_Variable;
  9641. o->type = t->Pointer.elem;
  9642. } else if (t->kind == Type_SoaPointer) {
  9643. o->mode = Addressing_SoaVariable;
  9644. o->type = type_deref(t);
  9645. } else if (t->kind == Type_RelativePointer) {
  9646. if (o->mode != Addressing_Variable) {
  9647. gbString str = expr_to_string(o->expr);
  9648. gbString typ = type_to_string(o->type);
  9649. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9650. gb_string_free(typ);
  9651. gb_string_free(str);
  9652. }
  9653. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9654. add_type_info_type(c, o->type);
  9655. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9656. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9657. o->mode = Addressing_Variable;
  9658. o->type = ptr_type->Pointer.elem;
  9659. } else {
  9660. gbString str = expr_to_string(o->expr);
  9661. gbString typ = type_to_string(o->type);
  9662. begin_error_block();
  9663. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9664. if (o->type && is_type_multi_pointer(o->type)) {
  9665. error_line("\tDid you mean '%s[0]'?\n", str);
  9666. }
  9667. end_error_block();
  9668. gb_string_free(typ);
  9669. gb_string_free(str);
  9670. o->mode = Addressing_Invalid;
  9671. o->expr = node;
  9672. return kind;
  9673. }
  9674. }
  9675. case_end;
  9676. case_ast_node(ia, InlineAsmExpr, node);
  9677. if (c->curr_proc_decl == nullptr) {
  9678. error(node, "Inline asm expressions are only allowed within a procedure body");
  9679. }
  9680. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9681. Type *return_type = nullptr;
  9682. for_array(i, ia->param_types) {
  9683. param_types[i] = check_type(c, ia->param_types[i]);
  9684. }
  9685. if (ia->return_type != nullptr) {
  9686. return_type = check_type(c, ia->return_type);
  9687. }
  9688. Operand x = {};
  9689. check_expr(c, &x, ia->asm_string);
  9690. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9691. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9692. }
  9693. check_expr(c, &x, ia->constraints_string);
  9694. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9695. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9696. }
  9697. Scope *scope = create_scope(c->info, c->scope);
  9698. scope->flags |= ScopeFlag_Proc;
  9699. Type *params = alloc_type_tuple();
  9700. Type *results = alloc_type_tuple();
  9701. if (param_types.count != 0) {
  9702. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9703. for_array(i, param_types) {
  9704. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9705. }
  9706. }
  9707. if (return_type != nullptr) {
  9708. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9709. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9710. }
  9711. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9712. o->type = pt;
  9713. o->mode = Addressing_Value;
  9714. o->expr = node;
  9715. return Expr_Expr;
  9716. case_end;
  9717. case Ast_TypeidType:
  9718. case Ast_PolyType:
  9719. case Ast_ProcType:
  9720. case Ast_PointerType:
  9721. case Ast_MultiPointerType:
  9722. case Ast_ArrayType:
  9723. case Ast_DynamicArrayType:
  9724. case Ast_StructType:
  9725. case Ast_UnionType:
  9726. case Ast_EnumType:
  9727. case Ast_MapType:
  9728. case Ast_BitSetType:
  9729. case Ast_MatrixType:
  9730. case Ast_RelativeType:
  9731. o->mode = Addressing_Type;
  9732. o->type = check_type(c, node);
  9733. break;
  9734. }
  9735. kind = Expr_Expr;
  9736. o->expr = node;
  9737. return kind;
  9738. }
  9739. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9740. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9741. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9742. o->type = t_invalid;
  9743. gbString xs = expr_to_string(o->expr);
  9744. if (o->mode == Addressing_Type) {
  9745. error(o->expr, "Invalid type usage '%s'", xs);
  9746. } else {
  9747. error(o->expr, "Invalid expression '%s'", xs);
  9748. }
  9749. gb_string_free(xs);
  9750. }
  9751. if (o->type != nullptr && is_type_untyped(o->type)) {
  9752. add_untyped(c, node, o->mode, o->type, o->value);
  9753. }
  9754. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9755. add_type_and_value(c, node, o->mode, o->type, o->value);
  9756. return kind;
  9757. }
  9758. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9759. check_expr_base(c, o, e, nullptr);
  9760. switch (o->mode) {
  9761. default:
  9762. return; // NOTE(bill): Valid
  9763. case Addressing_NoValue:
  9764. error_operand_no_value(o);
  9765. break;
  9766. }
  9767. o->mode = Addressing_Invalid;
  9768. }
  9769. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9770. check_expr_base(c, o, e, nullptr);
  9771. switch (o->mode) {
  9772. default:
  9773. return; // NOTE(bill): Valid
  9774. case Addressing_NoValue:
  9775. error_operand_no_value(o);
  9776. break;
  9777. case Addressing_Type:
  9778. error_operand_not_expression(o);
  9779. break;
  9780. }
  9781. o->mode = Addressing_Invalid;
  9782. }
  9783. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9784. check_expr_base(c, o, e, type_hint);
  9785. switch (o->mode) {
  9786. default:
  9787. return; // NOTE(bill): Valid
  9788. case Addressing_NoValue:
  9789. error_operand_no_value(o);
  9790. break;
  9791. case Addressing_Type:
  9792. error_operand_not_expression(o);
  9793. break;
  9794. }
  9795. o->mode = Addressing_Invalid;
  9796. }
  9797. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9798. if (o->mode == Addressing_Value) {
  9799. // NOTE(bill): Tuples are not first class thus never named
  9800. if (o->type->kind == Type_Tuple) {
  9801. isize count = o->type->Tuple.variables.count;
  9802. error(o->expr,
  9803. "%td-valued expression found where single value expected", count);
  9804. o->mode = Addressing_Invalid;
  9805. GB_ASSERT(count != 1);
  9806. }
  9807. }
  9808. }
  9809. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9810. check_multi_expr(c, o, e);
  9811. check_not_tuple(c, o);
  9812. }
  9813. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9814. check_expr_base(c, o, e, type_hint);
  9815. check_not_tuple(c, o);
  9816. error_operand_no_value(o);
  9817. }
  9818. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9819. switch (v.kind) {
  9820. case ExactValue_Invalid:
  9821. return true;
  9822. case ExactValue_Bool:
  9823. return !v.value_bool;
  9824. case ExactValue_String:
  9825. return v.value_string.len == 0;
  9826. case ExactValue_Integer:
  9827. return big_int_is_zero(&v.value_integer);
  9828. case ExactValue_Float:
  9829. return v.value_float == 0.0;
  9830. case ExactValue_Complex:
  9831. if (v.value_complex) {
  9832. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9833. }
  9834. return true;
  9835. case ExactValue_Quaternion:
  9836. if (v.value_quaternion) {
  9837. return v.value_quaternion->real == 0.0 &&
  9838. v.value_quaternion->imag == 0.0 &&
  9839. v.value_quaternion->jmag == 0.0 &&
  9840. v.value_quaternion->kmag == 0.0;
  9841. }
  9842. return true;
  9843. case ExactValue_Pointer:
  9844. return v.value_pointer == 0;
  9845. case ExactValue_Compound:
  9846. if (v.value_compound == nullptr) {
  9847. return true;
  9848. } else {
  9849. ast_node(cl, CompoundLit, v.value_compound);
  9850. if (cl->elems.count == 0) {
  9851. return true;
  9852. } else {
  9853. for (Ast *elem : cl->elems) {
  9854. if (elem->tav.mode != Addressing_Constant) {
  9855. return false;
  9856. }
  9857. if (!is_exact_value_zero(elem->tav.value)) {
  9858. return false;
  9859. }
  9860. }
  9861. return true;
  9862. }
  9863. }
  9864. case ExactValue_Procedure:
  9865. return v.value_procedure == nullptr;
  9866. case ExactValue_Typeid:
  9867. return v.value_typeid == nullptr;
  9868. }
  9869. return true;
  9870. }
  9871. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9872. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9873. for_array(i, params) {
  9874. if (i > 0) {
  9875. str = gb_string_appendc(str, ", ");
  9876. }
  9877. str = write_expr_to_string(str, params[i], false);
  9878. }
  9879. return str;
  9880. }
  9881. gb_internal gbString string_append_string(gbString str, String string) {
  9882. if (string.len > 0) {
  9883. return gb_string_append_length(str, &string[0], string.len);
  9884. }
  9885. return str;
  9886. }
  9887. gb_internal gbString string_append_token(gbString str, Token token) {
  9888. str = string_append_string(str, token.string);
  9889. return str;
  9890. }
  9891. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9892. if (node == nullptr)
  9893. return str;
  9894. if (is_ast_stmt(node)) {
  9895. GB_ASSERT("stmt passed to write_expr_to_string");
  9896. }
  9897. switch (node->kind) {
  9898. default:
  9899. str = gb_string_appendc(str, "(BadExpr)");
  9900. break;
  9901. case_ast_node(i, Ident, node);
  9902. str = string_append_token(str, i->token);
  9903. case_end;
  9904. case_ast_node(i, Implicit, node);
  9905. str = string_append_token(str, *i);
  9906. case_end;
  9907. case_ast_node(bl, BasicLit, node);
  9908. str = string_append_token(str, bl->token);
  9909. case_end;
  9910. case_ast_node(bd, BasicDirective, node);
  9911. str = gb_string_append_rune(str, '#');
  9912. str = string_append_string(str, bd->name.string);
  9913. case_end;
  9914. case_ast_node(ud, Uninit, node);
  9915. str = gb_string_appendc(str, "---");
  9916. case_end;
  9917. case_ast_node(pg, ProcGroup, node);
  9918. str = gb_string_appendc(str, "proc{");
  9919. for_array(i, pg->args) {
  9920. if (i > 0) str = gb_string_appendc(str, ", ");
  9921. str = write_expr_to_string(str, pg->args[i], shorthand);
  9922. }
  9923. str = gb_string_append_rune(str, '}');
  9924. case_end;
  9925. case_ast_node(pl, ProcLit, node);
  9926. str = write_expr_to_string(str, pl->type, shorthand);
  9927. if (pl->body) {
  9928. str = gb_string_appendc(str, " {...}");
  9929. } else {
  9930. str = gb_string_appendc(str, " ---");
  9931. }
  9932. case_end;
  9933. case_ast_node(cl, CompoundLit, node);
  9934. str = write_expr_to_string(str, cl->type, shorthand);
  9935. str = gb_string_append_rune(str, '{');
  9936. if (shorthand) {
  9937. str = gb_string_appendc(str, "...");
  9938. } else {
  9939. for_array(i, cl->elems) {
  9940. if (i > 0) str = gb_string_appendc(str, ", ");
  9941. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9942. }
  9943. }
  9944. str = gb_string_append_rune(str, '}');
  9945. case_end;
  9946. case_ast_node(te, TagExpr, node);
  9947. str = gb_string_append_rune(str, '#');
  9948. str = string_append_token(str, te->name);
  9949. str = write_expr_to_string(str, te->expr, shorthand);
  9950. case_end;
  9951. case_ast_node(ue, UnaryExpr, node);
  9952. str = string_append_token(str, ue->op);
  9953. str = write_expr_to_string(str, ue->expr, shorthand);
  9954. case_end;
  9955. case_ast_node(de, DerefExpr, node);
  9956. str = write_expr_to_string(str, de->expr, shorthand);
  9957. str = gb_string_append_rune(str, '^');
  9958. case_end;
  9959. case_ast_node(be, BinaryExpr, node);
  9960. str = write_expr_to_string(str, be->left, shorthand);
  9961. str = gb_string_append_rune(str, ' ');
  9962. str = string_append_token(str, be->op);
  9963. str = gb_string_append_rune(str, ' ');
  9964. str = write_expr_to_string(str, be->right, shorthand);
  9965. case_end;
  9966. case_ast_node(te, TernaryIfExpr, node);
  9967. TokenPos x = ast_token(te->x).pos;
  9968. TokenPos cond = ast_token(te->cond).pos;
  9969. if (x < cond) {
  9970. str = write_expr_to_string(str, te->x, shorthand);
  9971. str = gb_string_appendc(str, " if ");
  9972. str = write_expr_to_string(str, te->cond, shorthand);
  9973. str = gb_string_appendc(str, " else ");
  9974. str = write_expr_to_string(str, te->y, shorthand);
  9975. } else {
  9976. str = write_expr_to_string(str, te->cond, shorthand);
  9977. str = gb_string_appendc(str, " ? ");
  9978. str = write_expr_to_string(str, te->x, shorthand);
  9979. str = gb_string_appendc(str, " : ");
  9980. str = write_expr_to_string(str, te->y, shorthand);
  9981. }
  9982. case_end;
  9983. case_ast_node(te, TernaryWhenExpr, node);
  9984. str = write_expr_to_string(str, te->x, shorthand);
  9985. str = gb_string_appendc(str, " when ");
  9986. str = write_expr_to_string(str, te->cond, shorthand);
  9987. str = gb_string_appendc(str, " else ");
  9988. str = write_expr_to_string(str, te->y, shorthand);
  9989. case_end;
  9990. case_ast_node(oe, OrElseExpr, node);
  9991. str = write_expr_to_string(str, oe->x, shorthand);
  9992. str = gb_string_appendc(str, " or_else ");
  9993. str = write_expr_to_string(str, oe->y, shorthand);
  9994. case_end;
  9995. case_ast_node(oe, OrReturnExpr, node);
  9996. str = write_expr_to_string(str, oe->expr, shorthand);
  9997. str = gb_string_appendc(str, " or_return");
  9998. case_end;
  9999. case_ast_node(pe, ParenExpr, node);
  10000. str = gb_string_append_rune(str, '(');
  10001. str = write_expr_to_string(str, pe->expr, shorthand);
  10002. str = gb_string_append_rune(str, ')');
  10003. case_end;
  10004. case_ast_node(se, SelectorExpr, node);
  10005. str = write_expr_to_string(str, se->expr, shorthand);
  10006. str = string_append_token(str, se->token);
  10007. str = write_expr_to_string(str, se->selector, shorthand);
  10008. case_end;
  10009. case_ast_node(se, ImplicitSelectorExpr, node);
  10010. str = gb_string_append_rune(str, '.');
  10011. str = write_expr_to_string(str, se->selector, shorthand);
  10012. case_end;
  10013. case_ast_node(se, SelectorCallExpr, node);
  10014. str = write_expr_to_string(str, se->expr, shorthand);
  10015. str = gb_string_appendc(str, "(");
  10016. ast_node(ce, CallExpr, se->call);
  10017. isize start = se->modified_call ? 1 : 0;
  10018. for (isize i = start; i < ce->args.count; i++) {
  10019. Ast *arg = ce->args[i];
  10020. if (i > start) {
  10021. str = gb_string_appendc(str, ", ");
  10022. }
  10023. str = write_expr_to_string(str, arg, shorthand);
  10024. }
  10025. str = gb_string_appendc(str, ")");
  10026. case_end;
  10027. case_ast_node(ta, TypeAssertion, node);
  10028. str = write_expr_to_string(str, ta->expr, shorthand);
  10029. if (ta->type != nullptr &&
  10030. ta->type->kind == Ast_UnaryExpr &&
  10031. ta->type->UnaryExpr.op.kind == Token_Question) {
  10032. str = gb_string_appendc(str, ".?");
  10033. } else {
  10034. str = gb_string_appendc(str, ".(");
  10035. str = write_expr_to_string(str, ta->type, shorthand);
  10036. str = gb_string_append_rune(str, ')');
  10037. }
  10038. case_end;
  10039. case_ast_node(tc, TypeCast, node);
  10040. str = string_append_token(str, tc->token);
  10041. str = gb_string_append_rune(str, '(');
  10042. str = write_expr_to_string(str, tc->type, shorthand);
  10043. str = gb_string_append_rune(str, ')');
  10044. str = write_expr_to_string(str, tc->expr, shorthand);
  10045. case_end;
  10046. case_ast_node(ac, AutoCast, node);
  10047. str = string_append_token(str, ac->token);
  10048. str = gb_string_append_rune(str, ' ');
  10049. str = write_expr_to_string(str, ac->expr, shorthand);
  10050. case_end;
  10051. case_ast_node(ie, IndexExpr, node);
  10052. str = write_expr_to_string(str, ie->expr, shorthand);
  10053. str = gb_string_append_rune(str, '[');
  10054. str = write_expr_to_string(str, ie->index, shorthand);
  10055. str = gb_string_append_rune(str, ']');
  10056. case_end;
  10057. case_ast_node(se, SliceExpr, node);
  10058. str = write_expr_to_string(str, se->expr, shorthand);
  10059. str = gb_string_append_rune(str, '[');
  10060. str = write_expr_to_string(str, se->low, shorthand);
  10061. str = string_append_token(str, se->interval);
  10062. str = write_expr_to_string(str, se->high, shorthand);
  10063. str = gb_string_append_rune(str, ']');
  10064. case_end;
  10065. case_ast_node(mie, MatrixIndexExpr, node);
  10066. str = write_expr_to_string(str, mie->expr, shorthand);
  10067. str = gb_string_append_rune(str, '[');
  10068. str = write_expr_to_string(str, mie->row_index, shorthand);
  10069. str = gb_string_appendc(str, ", ");
  10070. str = write_expr_to_string(str, mie->column_index, shorthand);
  10071. str = gb_string_append_rune(str, ']');
  10072. case_end;
  10073. case_ast_node(e, Ellipsis, node);
  10074. str = gb_string_appendc(str, "..");
  10075. str = write_expr_to_string(str, e->expr, shorthand);
  10076. case_end;
  10077. case_ast_node(fv, FieldValue, node);
  10078. str = write_expr_to_string(str, fv->field, shorthand);
  10079. str = gb_string_appendc(str, " = ");
  10080. str = write_expr_to_string(str, fv->value, shorthand);
  10081. case_end;
  10082. case_ast_node(fv, EnumFieldValue, node);
  10083. str = write_expr_to_string(str, fv->name, shorthand);
  10084. if (fv->value) {
  10085. str = gb_string_appendc(str, " = ");
  10086. str = write_expr_to_string(str, fv->value, shorthand);
  10087. }
  10088. case_end;
  10089. case_ast_node(ht, HelperType, node);
  10090. str = gb_string_appendc(str, "#type ");
  10091. str = write_expr_to_string(str, ht->type, shorthand);
  10092. case_end;
  10093. case_ast_node(ht, DistinctType, node);
  10094. str = gb_string_appendc(str, "distinct ");
  10095. str = write_expr_to_string(str, ht->type, shorthand);
  10096. case_end;
  10097. case_ast_node(pt, PolyType, node);
  10098. str = gb_string_append_rune(str, '$');
  10099. str = write_expr_to_string(str, pt->type, shorthand);
  10100. if (pt->specialization != nullptr) {
  10101. str = gb_string_append_rune(str, '/');
  10102. str = write_expr_to_string(str, pt->specialization, shorthand);
  10103. }
  10104. case_end;
  10105. case_ast_node(pt, PointerType, node);
  10106. str = gb_string_append_rune(str, '^');
  10107. str = write_expr_to_string(str, pt->type, shorthand);
  10108. case_end;
  10109. case_ast_node(pt, MultiPointerType, node);
  10110. str = gb_string_appendc(str, "[^]");
  10111. str = write_expr_to_string(str, pt->type, shorthand);
  10112. case_end;
  10113. case_ast_node(at, ArrayType, node);
  10114. str = gb_string_append_rune(str, '[');
  10115. if (at->count != nullptr &&
  10116. at->count->kind == Ast_UnaryExpr &&
  10117. at->count->UnaryExpr.op.kind == Token_Question) {
  10118. str = gb_string_appendc(str, "?");
  10119. } else {
  10120. str = write_expr_to_string(str, at->count, shorthand);
  10121. }
  10122. str = gb_string_append_rune(str, ']');
  10123. str = write_expr_to_string(str, at->elem, shorthand);
  10124. case_end;
  10125. case_ast_node(at, DynamicArrayType, node);
  10126. str = gb_string_appendc(str, "[dynamic]");
  10127. str = write_expr_to_string(str, at->elem, shorthand);
  10128. case_end;
  10129. case_ast_node(bs, BitSetType, node);
  10130. str = gb_string_appendc(str, "bit_set[");
  10131. str = write_expr_to_string(str, bs->elem, shorthand);
  10132. str = gb_string_appendc(str, "]");
  10133. case_end;
  10134. case_ast_node(mt, MapType, node);
  10135. str = gb_string_appendc(str, "map[");
  10136. str = write_expr_to_string(str, mt->key, shorthand);
  10137. str = gb_string_append_rune(str, ']');
  10138. str = write_expr_to_string(str, mt->value, shorthand);
  10139. case_end;
  10140. case_ast_node(mt, MatrixType, node);
  10141. str = gb_string_appendc(str, "matrix[");
  10142. str = write_expr_to_string(str, mt->row_count, shorthand);
  10143. str = gb_string_appendc(str, ", ");
  10144. str = write_expr_to_string(str, mt->column_count, shorthand);
  10145. str = gb_string_append_rune(str, ']');
  10146. str = write_expr_to_string(str, mt->elem, shorthand);
  10147. case_end;
  10148. case_ast_node(f, Field, node);
  10149. if (f->flags&FieldFlag_using) {
  10150. str = gb_string_appendc(str, "using ");
  10151. }
  10152. if (f->flags&FieldFlag_no_alias) {
  10153. str = gb_string_appendc(str, "#no_alias ");
  10154. }
  10155. if (f->flags&FieldFlag_c_vararg) {
  10156. str = gb_string_appendc(str, "#c_vararg ");
  10157. }
  10158. if (f->flags&FieldFlag_any_int) {
  10159. str = gb_string_appendc(str, "#any_int ");
  10160. }
  10161. if (f->flags&FieldFlag_const) {
  10162. str = gb_string_appendc(str, "#const ");
  10163. }
  10164. if (f->flags&FieldFlag_subtype) {
  10165. str = gb_string_appendc(str, "#subtype ");
  10166. }
  10167. for_array(i, f->names) {
  10168. Ast *name = f->names[i];
  10169. if (i > 0) str = gb_string_appendc(str, ", ");
  10170. str = write_expr_to_string(str, name, shorthand);
  10171. }
  10172. if (f->names.count > 0) {
  10173. if (f->type == nullptr && f->default_value != nullptr) {
  10174. str = gb_string_append_rune(str, ' ');
  10175. }
  10176. str = gb_string_appendc(str, ":");
  10177. }
  10178. if (f->type != nullptr) {
  10179. str = gb_string_append_rune(str, ' ');
  10180. str = write_expr_to_string(str, f->type, shorthand);
  10181. }
  10182. if (f->default_value != nullptr) {
  10183. if (f->type != nullptr) {
  10184. str = gb_string_append_rune(str, ' ');
  10185. }
  10186. str = gb_string_appendc(str, "= ");
  10187. str = write_expr_to_string(str, f->default_value, shorthand);
  10188. }
  10189. case_end;
  10190. case_ast_node(f, FieldList, node);
  10191. bool has_name = false;
  10192. for_array(i, f->list) {
  10193. ast_node(field, Field, f->list[i]);
  10194. if (field->names.count > 1) {
  10195. has_name = true;
  10196. break;
  10197. }
  10198. if (field->names.count == 0) {
  10199. continue;
  10200. }
  10201. if (!is_blank_ident(field->names[0])) {
  10202. has_name = true;
  10203. break;
  10204. }
  10205. }
  10206. for_array(i, f->list) {
  10207. if (i > 0) str = gb_string_appendc(str, ", ");
  10208. if (has_name) {
  10209. str = write_expr_to_string(str, f->list[i], shorthand);
  10210. } else {
  10211. ast_node(field, Field, f->list[i]);
  10212. if (field->flags&FieldFlag_using) {
  10213. str = gb_string_appendc(str, "using ");
  10214. }
  10215. if (field->flags&FieldFlag_no_alias) {
  10216. str = gb_string_appendc(str, "#no_alias ");
  10217. }
  10218. if (field->flags&FieldFlag_c_vararg) {
  10219. str = gb_string_appendc(str, "#c_vararg ");
  10220. }
  10221. str = write_expr_to_string(str, field->type, shorthand);
  10222. }
  10223. }
  10224. case_end;
  10225. case_ast_node(ce, CallExpr, node);
  10226. switch (ce->inlining) {
  10227. case ProcInlining_inline:
  10228. str = gb_string_appendc(str, "#force_inline ");
  10229. break;
  10230. case ProcInlining_no_inline:
  10231. str = gb_string_appendc(str, "#force_no_inline ");
  10232. break;
  10233. }
  10234. str = write_expr_to_string(str, ce->proc, shorthand);
  10235. str = gb_string_appendc(str, "(");
  10236. isize idx0 = cast(isize)ce->was_selector;
  10237. for (isize i = idx0; i < ce->args.count; i++) {
  10238. Ast *arg = ce->args[i];
  10239. if (i > idx0) {
  10240. str = gb_string_appendc(str, ", ");
  10241. }
  10242. str = write_expr_to_string(str, arg, shorthand);
  10243. }
  10244. str = gb_string_appendc(str, ")");
  10245. case_end;
  10246. case_ast_node(tt, TypeidType, node);
  10247. str = gb_string_appendc(str, "typeid");
  10248. if (tt->specialization) {
  10249. str = gb_string_appendc(str, "/");
  10250. str = write_expr_to_string(str, tt->specialization, shorthand);
  10251. }
  10252. case_end;
  10253. case_ast_node(pt, ProcType, node);
  10254. str = gb_string_appendc(str, "proc(");
  10255. str = write_expr_to_string(str, pt->params, shorthand);
  10256. str = gb_string_appendc(str, ")");
  10257. if (pt->results != nullptr) {
  10258. str = gb_string_appendc(str, " -> ");
  10259. bool parens_needed = false;
  10260. if (pt->results && pt->results->kind == Ast_FieldList) {
  10261. for (Ast *field : pt->results->FieldList.list) {
  10262. ast_node(f, Field, field);
  10263. if (f->names.count != 0) {
  10264. parens_needed = true;
  10265. break;
  10266. }
  10267. }
  10268. }
  10269. if (parens_needed) {
  10270. str = gb_string_append_rune(str, '(');
  10271. }
  10272. str = write_expr_to_string(str, pt->results, shorthand);
  10273. if (parens_needed) {
  10274. str = gb_string_append_rune(str, ')');
  10275. }
  10276. }
  10277. case_end;
  10278. case_ast_node(st, StructType, node);
  10279. str = gb_string_appendc(str, "struct ");
  10280. if (st->polymorphic_params) {
  10281. str = gb_string_append_rune(str, '(');
  10282. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10283. str = gb_string_appendc(str, ") ");
  10284. }
  10285. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10286. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10287. if (st->align) {
  10288. str = gb_string_appendc(str, "#align ");
  10289. str = write_expr_to_string(str, st->align, shorthand);
  10290. str = gb_string_append_rune(str, ' ');
  10291. }
  10292. str = gb_string_append_rune(str, '{');
  10293. if (shorthand) {
  10294. str = gb_string_appendc(str, "...");
  10295. } else {
  10296. str = write_struct_fields_to_string(str, st->fields);
  10297. }
  10298. str = gb_string_append_rune(str, '}');
  10299. case_end;
  10300. case_ast_node(st, UnionType, node);
  10301. str = gb_string_appendc(str, "union ");
  10302. if (st->polymorphic_params) {
  10303. str = gb_string_append_rune(str, '(');
  10304. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10305. str = gb_string_appendc(str, ") ");
  10306. }
  10307. switch (st->kind) {
  10308. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10309. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10310. }
  10311. if (st->align) {
  10312. str = gb_string_appendc(str, "#align ");
  10313. str = write_expr_to_string(str, st->align, shorthand);
  10314. str = gb_string_append_rune(str, ' ');
  10315. }
  10316. str = gb_string_append_rune(str, '{');
  10317. if (shorthand) {
  10318. str = gb_string_appendc(str, "...");
  10319. } else {
  10320. str = write_struct_fields_to_string(str, st->variants);
  10321. }
  10322. str = gb_string_append_rune(str, '}');
  10323. case_end;
  10324. case_ast_node(et, EnumType, node);
  10325. str = gb_string_appendc(str, "enum ");
  10326. if (et->base_type != nullptr) {
  10327. str = write_expr_to_string(str, et->base_type, shorthand);
  10328. str = gb_string_append_rune(str, ' ');
  10329. }
  10330. str = gb_string_append_rune(str, '{');
  10331. if (shorthand) {
  10332. str = gb_string_appendc(str, "...");
  10333. } else {
  10334. for_array(i, et->fields) {
  10335. if (i > 0) {
  10336. str = gb_string_appendc(str, ", ");
  10337. }
  10338. str = write_expr_to_string(str, et->fields[i], shorthand);
  10339. }
  10340. }
  10341. str = gb_string_append_rune(str, '}');
  10342. case_end;
  10343. case_ast_node(rt, RelativeType, node);
  10344. str = write_expr_to_string(str, rt->tag, shorthand);
  10345. str = gb_string_appendc(str, "" );
  10346. str = write_expr_to_string(str, rt->type, shorthand);
  10347. case_end;
  10348. case_ast_node(ia, InlineAsmExpr, node);
  10349. str = gb_string_appendc(str, "asm(");
  10350. for_array(i, ia->param_types) {
  10351. if (i > 0) {
  10352. str = gb_string_appendc(str, ", ");
  10353. }
  10354. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10355. }
  10356. str = gb_string_appendc(str, ")");
  10357. if (ia->return_type != nullptr) {
  10358. str = gb_string_appendc(str, " -> ");
  10359. str = write_expr_to_string(str, ia->return_type, shorthand);
  10360. }
  10361. if (ia->has_side_effects) {
  10362. str = gb_string_appendc(str, " #side_effects");
  10363. }
  10364. if (ia->is_align_stack) {
  10365. str = gb_string_appendc(str, " #stack_align");
  10366. }
  10367. if (ia->dialect) {
  10368. str = gb_string_appendc(str, " #");
  10369. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10370. }
  10371. str = gb_string_appendc(str, " {");
  10372. if (shorthand) {
  10373. str = gb_string_appendc(str, "...");
  10374. } else {
  10375. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10376. str = gb_string_appendc(str, ", ");
  10377. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10378. }
  10379. str = gb_string_appendc(str, "}");
  10380. case_end;
  10381. }
  10382. return str;
  10383. }
  10384. gb_internal gbString expr_to_string(Ast *expression) {
  10385. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10386. }
  10387. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10388. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10389. }
  10390. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10391. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10392. }