check_expr.cpp 297 KB

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