check_expr.cpp 272 KB

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