check_expr.cpp 283 KB

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