check_expr.cpp 264 KB

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