check_expr.cpp 292 KB

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