check_expr.cpp 303 KB

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