check_expr.cpp 320 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_MAX,
  18. };
  19. char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  20. "None",
  21. "NoneProcedureType",
  22. "WrongTypes",
  23. "NonVariadicExpand",
  24. "VariadicTuple",
  25. "MultipleVariadicExpand",
  26. "AmbiguousPolymorphicVariadic",
  27. "ArgumentCount",
  28. "TooFewArguments",
  29. "TooManyArguments",
  30. "InvalidFieldValue",
  31. "ParameterNotFound",
  32. "ParameterMissing",
  33. "DuplicateParameter",
  34. "NoneConstantParameter",
  35. };
  36. enum CallArgumentErrorMode {
  37. CallArgumentMode_NoErrors,
  38. CallArgumentMode_ShowErrors,
  39. };
  40. struct CallArgumentData {
  41. Entity *gen_entity;
  42. i64 score;
  43. Type * result_type;
  44. };
  45. struct PolyProcData {
  46. Entity * gen_entity;
  47. ProcInfo proc_info;
  48. };
  49. struct ValidIndexAndScore {
  50. isize index;
  51. i64 score;
  52. };
  53. int valid_index_and_score_cmp(void const *a, void const *b) {
  54. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  55. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  56. return sj < si ? -1 : sj > si;
  57. }
  58. #define CALL_ARGUMENT_CHECKER(name) CallArgumentError name(CheckerContext *c, Ast *call, Type *proc_type, Entity *entity, Array<Operand> operands, CallArgumentErrorMode show_error_mode, CallArgumentData *data)
  59. typedef CALL_ARGUMENT_CHECKER(CallArgumentCheckerType);
  60. void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  64. ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  66. Type * check_type (CheckerContext *c, Ast *expression);
  67. Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  68. Type * make_optional_ok_type (Type *value, bool typed=true);
  69. Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  70. Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  71. Entity * find_polymorphic_record_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> const &ordered_operands, bool *failure);
  72. void check_not_tuple (CheckerContext *c, Operand *operand);
  73. void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gbString expr_to_string (Ast *expression);
  75. void check_proc_body (CheckerContext *c, Token token, DeclInfo *decl, Type *type, Ast *body);
  76. void update_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. bool check_is_terminating (Ast *node, String const &label);
  78. bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> *operands = nullptr);
  84. void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. CallArgumentData check_call_arguments (CheckerContext *c, Operand *operand, Type *proc_type, Ast *call);
  89. Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  90. Type *type_to_abi_compat_param_type(gbAllocator a, Type *original_type, ProcCallingConvention cc);
  91. Type *type_to_abi_compat_result_type(gbAllocator a, Type *original_type, ProcCallingConvention cc);
  92. bool abi_compat_return_by_pointer(gbAllocator a, ProcCallingConvention cc, Type *abi_return_type);
  93. void set_procedure_abi_types(Type *type);
  94. void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type);
  95. void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  96. Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  97. Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  98. Entity *entity_from_expr(Ast *expr) {
  99. expr = unparen_expr(expr);
  100. switch (expr->kind) {
  101. case Ast_Ident:
  102. return expr->Ident.entity;
  103. case Ast_SelectorExpr:
  104. return entity_from_expr(expr->SelectorExpr.selector);
  105. }
  106. return nullptr;
  107. }
  108. void error_operand_not_expression(Operand *o) {
  109. if (o->mode == Addressing_Type) {
  110. gbString err = expr_to_string(o->expr);
  111. error(o->expr, "'%s' is not an expression but a type", err);
  112. gb_string_free(err);
  113. o->mode = Addressing_Invalid;
  114. }
  115. }
  116. void error_operand_no_value(Operand *o) {
  117. if (o->mode == Addressing_NoValue) {
  118. gbString err = expr_to_string(o->expr);
  119. Ast *x = unparen_expr(o->expr);
  120. if (x->kind == Ast_CallExpr) {
  121. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  122. } else {
  123. error(o->expr, "'%s' used as a value", err);
  124. }
  125. gb_string_free(err);
  126. o->mode = Addressing_Invalid;
  127. }
  128. }
  129. void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  130. Scope *s = c->scope;
  131. check_collect_entities(c, nodes);
  132. for_array(i, s->elements.entries) {
  133. Entity *e = s->elements.entries[i].value;
  134. switch (e->kind) {
  135. case Entity_Constant:
  136. case Entity_TypeName:
  137. case Entity_Procedure:
  138. break;
  139. default:
  140. continue;
  141. }
  142. DeclInfo *d = decl_info_of_entity(e);
  143. if (d != nullptr) {
  144. check_entity_decl(c, e, d, nullptr);
  145. }
  146. }
  147. }
  148. isize check_is_assignable_to_using_subtype(Type *src, Type *dst, isize level = 0, bool src_is_ptr = false) {
  149. Type *prev_src = src;
  150. src = type_deref(src);
  151. if (!src_is_ptr) {
  152. src_is_ptr = src != prev_src;
  153. }
  154. src = base_type(src);
  155. if (!is_type_struct(src)) {
  156. return 0;
  157. }
  158. for_array(i, src->Struct.fields) {
  159. Entity *f = src->Struct.fields[i];
  160. if (f->kind != Entity_Variable || (f->flags&EntityFlag_Using) == 0) {
  161. continue;
  162. }
  163. if (are_types_identical(f->type, dst)) {
  164. return level+1;
  165. }
  166. if (src_is_ptr && is_type_pointer(dst)) {
  167. if (are_types_identical(f->type, type_deref(dst))) {
  168. return level+1;
  169. }
  170. }
  171. isize nested_level = check_is_assignable_to_using_subtype(f->type, dst, level+1, src_is_ptr);
  172. if (nested_level > 0) {
  173. return nested_level;
  174. }
  175. }
  176. return 0;
  177. }
  178. bool find_or_generate_polymorphic_procedure(CheckerContext *c, Entity *base_entity, Type *type,
  179. Array<Operand> *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  180. ///////////////////////////////////////////////////////////////////////////////
  181. // //
  182. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  183. // //
  184. ///////////////////////////////////////////////////////////////////////////////
  185. if (base_entity == nullptr) {
  186. return false;
  187. }
  188. if (!is_type_proc(base_entity->type)) {
  189. return false;
  190. }
  191. String name = base_entity->token.string;
  192. Type *src = base_type(base_entity->type);
  193. Type *dst = nullptr;
  194. if (type != nullptr) dst = base_type(type);
  195. if (param_operands == nullptr) {
  196. GB_ASSERT(dst != nullptr);
  197. }
  198. if (param_operands != nullptr) {
  199. GB_ASSERT(dst == nullptr);
  200. }
  201. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  202. return false;
  203. }
  204. if (dst != nullptr) {
  205. if (dst->Proc.is_polymorphic) {
  206. return false;
  207. }
  208. if (dst->Proc.param_count != src->Proc.param_count ||
  209. dst->Proc.result_count != src->Proc.result_count) {
  210. return false;
  211. }
  212. }
  213. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  214. if (old_decl == nullptr) {
  215. return false;
  216. }
  217. gbAllocator a = heap_allocator();
  218. Array<Operand> operands = {};
  219. if (param_operands) {
  220. operands = *param_operands;
  221. } else {
  222. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  223. for (isize i = 0; i < dst->Proc.param_count; i++) {
  224. Entity *param = dst->Proc.params->Tuple.variables[i];
  225. Operand o = {Addressing_Value};
  226. o.type = param->type;
  227. array_add(&operands, o);
  228. }
  229. }
  230. defer (if (param_operands == nullptr) {
  231. array_free(&operands);
  232. });
  233. CheckerContext nctx = *c;
  234. Scope *scope = create_scope(base_entity->scope);
  235. scope->flags |= ScopeFlag_Proc;
  236. nctx.scope = scope;
  237. nctx.allow_polymorphic_types = true;
  238. if (nctx.polymorphic_scope == nullptr) {
  239. nctx.polymorphic_scope = scope;
  240. }
  241. if (param_operands == nullptr) {
  242. // c->no_polymorphic_errors = false;
  243. }
  244. auto *pt = &src->Proc;
  245. // NOTE(bill): This is slightly memory leaking if the type already exists
  246. // Maybe it's better to check with the previous types first?
  247. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  248. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  249. if (!success) {
  250. return false;
  251. }
  252. auto *found_gen_procs = map_get(&nctx.info->gen_procs, hash_pointer(base_entity->identifier));
  253. if (found_gen_procs) {
  254. auto procs = *found_gen_procs;
  255. for_array(i, procs) {
  256. Entity *other = procs[i];
  257. Type *pt = base_type(other->type);
  258. if (are_types_identical(pt, final_proc_type)) {
  259. if (poly_proc_data) {
  260. poly_proc_data->gen_entity = other;
  261. }
  262. return true;
  263. }
  264. }
  265. }
  266. #if 0
  267. bool generate_type_again = nctx.no_polymorphic_errors;
  268. if (generate_type_again) {
  269. #else
  270. {
  271. #endif
  272. // LEAK TODO(bill): This is technically a memory leak as it has to generate the type twice
  273. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  274. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  275. nctx.no_polymorphic_errors = false;
  276. // NOTE(bill): Reset scope from the failed procedure type
  277. scope_reset(scope);
  278. // LEAK TODO(bill): Cloning this AST may be leaky
  279. Ast *cloned_proc_type_node = clone_ast(pt->node);
  280. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  281. if (!success) {
  282. return false;
  283. }
  284. if (found_gen_procs) {
  285. auto procs = *found_gen_procs;
  286. for_array(i, procs) {
  287. Entity *other = procs[i];
  288. Type *pt = base_type(other->type);
  289. if (are_types_identical(pt, final_proc_type)) {
  290. if (poly_proc_data) {
  291. poly_proc_data->gen_entity = other;
  292. }
  293. return true;
  294. }
  295. }
  296. }
  297. }
  298. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  299. ast_node(pl, ProcLit, proc_lit);
  300. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  301. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  302. final_proc_type->Proc.is_poly_specialized = true;
  303. final_proc_type->Proc.is_polymorphic = true;
  304. for (isize i = 0; i < operands.count; i++) {
  305. Operand o = operands[i];
  306. if (final_proc_type == o.type ||
  307. base_entity->type == o.type) {
  308. // NOTE(bill): Cycle
  309. final_proc_type->Proc.is_poly_specialized = false;
  310. break;
  311. }
  312. }
  313. u64 tags = base_entity->Procedure.tags;
  314. Ast *ident = clone_ast(base_entity->identifier);
  315. Token token = ident->Ident.token;
  316. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  317. d->gen_proc_type = final_proc_type;
  318. d->type_expr = pl->type;
  319. d->proc_lit = proc_lit;
  320. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  321. entity->identifier = ident;
  322. add_entity_and_decl_info(&nctx, ident, entity, d);
  323. // NOTE(bill): Set the scope afterwards as this is not real overloading
  324. entity->scope = scope->parent;
  325. entity->file = base_entity->file;
  326. entity->pkg = base_entity->pkg;
  327. AstFile *file = nullptr;
  328. {
  329. Scope *s = entity->scope;
  330. while (s != nullptr && s->file == nullptr) {
  331. file = s->file;
  332. s = s->parent;
  333. }
  334. }
  335. ProcInfo proc_info = {};
  336. proc_info.file = file;
  337. proc_info.token = token;
  338. proc_info.decl = d;
  339. proc_info.type = final_proc_type;
  340. proc_info.body = pl->body;
  341. proc_info.tags = tags;
  342. proc_info.generated_from_polymorphic = true;
  343. proc_info.poly_def_node = poly_def_node;
  344. if (found_gen_procs) {
  345. array_add(found_gen_procs, entity);
  346. } else {
  347. auto array = array_make<Entity *>(heap_allocator());
  348. array_add(&array, entity);
  349. map_set(&nctx.checker->info.gen_procs, hash_pointer(base_entity->identifier), array);
  350. }
  351. GB_ASSERT(entity != nullptr);
  352. if (poly_proc_data) {
  353. poly_proc_data->gen_entity = entity;
  354. poly_proc_data->proc_info = proc_info;
  355. }
  356. // NOTE(bill): Check the newly generated procedure body
  357. check_procedure_later(nctx.checker, proc_info);
  358. return true;
  359. }
  360. bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  361. if (operand->expr == nullptr) return false;
  362. Entity *base_entity = entity_of_node(operand->expr);
  363. if (base_entity == nullptr) return false;
  364. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  365. }
  366. bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  367. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  368. }
  369. bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  370. bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  371. bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  372. #define MAXIMUM_TYPE_DISTANCE 10
  373. i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  374. if (operand->mode == Addressing_Invalid ||
  375. type == t_invalid) {
  376. return -1;
  377. }
  378. if (operand->mode == Addressing_Builtin) {
  379. return -1;
  380. }
  381. if (operand->mode == Addressing_Type) {
  382. if (is_type_typeid(type)) {
  383. add_type_info_type(c, operand->type);
  384. return 4;
  385. }
  386. return -1;
  387. }
  388. Type *s = operand->type;
  389. if (are_types_identical(s, type)) {
  390. return 0;
  391. }
  392. Type *src = base_type(s);
  393. Type *dst = base_type(type);
  394. if (is_type_untyped_undef(src)) {
  395. if (type_has_undef(dst)) {
  396. return 1;
  397. }
  398. return -1;
  399. }
  400. if (is_type_untyped_nil(src)) {
  401. if (type_has_nil(dst)) {
  402. return 1;
  403. }
  404. return -1;
  405. }
  406. if (is_type_untyped(src)) {
  407. if (is_type_any(dst)) {
  408. // NOTE(bill): Anything can cast to 'Any'
  409. add_type_info_type(c, s);
  410. return MAXIMUM_TYPE_DISTANCE;
  411. }
  412. if (dst->kind == Type_Basic) {
  413. if (operand->mode == Addressing_Constant) {
  414. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  415. if (is_type_typed(dst) && src->kind == Type_Basic) {
  416. switch (src->Basic.kind) {
  417. case Basic_UntypedRune:
  418. if (is_type_integer(dst) || is_type_rune(dst)) {
  419. return 1;
  420. }
  421. break;
  422. case Basic_UntypedInteger:
  423. if (is_type_integer(dst) || is_type_rune(dst)) {
  424. return 1;
  425. }
  426. break;
  427. case Basic_UntypedFloat:
  428. if (is_type_float(dst)) {
  429. return 1;
  430. }
  431. break;
  432. case Basic_UntypedComplex:
  433. if (is_type_complex(dst)) {
  434. return 1;
  435. }
  436. if (is_type_quaternion(dst)) {
  437. return 2;
  438. }
  439. break;
  440. case Basic_UntypedQuaternion:
  441. if (is_type_quaternion(dst)) {
  442. return 1;
  443. }
  444. break;
  445. }
  446. }
  447. return 2;
  448. }
  449. return -1;
  450. }
  451. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedRune) {
  452. if (is_type_integer(dst) || is_type_rune(dst)) {
  453. if (is_type_typed(type)) {
  454. return 2;
  455. }
  456. return 1;
  457. }
  458. return -1;
  459. }
  460. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedBool) {
  461. if (is_type_boolean(dst)) {
  462. if (is_type_typed(type)) {
  463. return 2;
  464. }
  465. return 1;
  466. }
  467. return -1;
  468. }
  469. }
  470. }
  471. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  472. if (c->in_enum_type) {
  473. return 3;
  474. }
  475. }
  476. {
  477. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  478. if (subtype_level > 0) {
  479. return 4 + subtype_level;
  480. }
  481. }
  482. // ^T <- rawptr
  483. #if 0
  484. // TODO(bill): Should C-style (not C++) pointer cast be allowed?
  485. if (is_type_pointer(dst) && is_type_rawptr(src)) {
  486. return true;
  487. }
  488. #endif
  489. #if 1
  490. // TODO(bill): Should I allow this implicit conversion at all?!
  491. // rawptr <- ^T
  492. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  493. return 5;
  494. }
  495. #endif
  496. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  497. bool modify_type = !c->no_polymorphic_errors;
  498. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  499. return 2;
  500. }
  501. }
  502. if (is_type_union(dst)) {
  503. for_array(i, dst->Union.variants) {
  504. Type *vt = dst->Union.variants[i];
  505. if (are_types_identical(vt, s)) {
  506. return 1;
  507. }
  508. }
  509. }
  510. if (is_type_relative_pointer(dst)) {
  511. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  512. if (score >= 0) {
  513. return score+2;
  514. }
  515. }
  516. if (is_type_relative_slice(dst)) {
  517. i64 score = check_distance_between_types(c, operand, dst->RelativeSlice.slice_type);
  518. if (score >= 0) {
  519. return score+2;
  520. }
  521. }
  522. if (is_type_proc(dst)) {
  523. if (are_types_identical(src, dst)) {
  524. return 3;
  525. }
  526. PolyProcData poly_proc_data = {};
  527. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  528. add_entity_use(c, operand->expr, poly_proc_data.gen_entity);
  529. return 4;
  530. }
  531. }
  532. if (is_type_array(dst)) {
  533. Type *elem = base_array_type(dst);
  534. i64 distance = check_distance_between_types(c, operand, elem);
  535. if (distance >= 0) {
  536. return distance + 6;
  537. }
  538. }
  539. if (is_type_any(dst)) {
  540. if (!is_type_polymorphic(src)) {
  541. if (operand->mode == Addressing_Context && operand->type == t_context) {
  542. return -1;
  543. } else {
  544. // NOTE(bill): Anything can cast to 'Any'
  545. add_type_info_type(c, s);
  546. return MAXIMUM_TYPE_DISTANCE;
  547. }
  548. }
  549. }
  550. Ast *expr = unparen_expr(operand->expr);
  551. if (expr != nullptr) {
  552. if (expr->kind == Ast_AutoCast) {
  553. Operand x = *operand;
  554. x.expr = expr->AutoCast.expr;
  555. bool ok = check_cast_internal(c, &x, type);
  556. if (ok) {
  557. return MAXIMUM_TYPE_DISTANCE;
  558. }
  559. } /*else if (expr->kind == Ast_CallExpr) {
  560. // NOTE(bill, 2021-04-19): Allow assignment of procedure calls with #optional_ok
  561. ast_node(ce, CallExpr, expr);
  562. Type *pt = base_type(type_of_expr(ce->proc));
  563. if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  564. Operand x = *operand;
  565. x.type = pt->Proc.results->Tuple.variables[0]->type;
  566. i64 res = check_distance_between_types(c, &x, type);
  567. if (res >= 0) {
  568. return res+1;
  569. }
  570. }
  571. }*/
  572. }
  573. return -1;
  574. }
  575. i64 assign_score_function(i64 distance, bool is_variadic=false) {
  576. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  577. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  578. // TODO(bill): A decent score function
  579. i64 d = distance*distance; // x^2
  580. if (is_variadic && d >= 0) {
  581. d += distance + 1; // x^2 + x + 1
  582. }
  583. return gb_max(c - d, 0);
  584. }
  585. bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  586. i64 score = 0;
  587. i64 distance = check_distance_between_types(c, operand, type);
  588. bool ok = distance >= 0;
  589. if (ok) {
  590. score = assign_score_function(distance, is_variadic);
  591. }
  592. if (score_) *score_ = score;
  593. return ok;
  594. }
  595. bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  596. i64 score = 0;
  597. return check_is_assignable_to_with_score(c, operand, type, &score);
  598. }
  599. // NOTE(bill): 'content_name' is for debugging and error messages
  600. void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  601. check_not_tuple(c, operand);
  602. if (operand->mode == Addressing_Invalid) {
  603. return;
  604. }
  605. if (is_type_untyped(operand->type)) {
  606. Type *target_type = type;
  607. if (type == nullptr || is_type_any(type)) {
  608. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  609. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  610. operand->mode = Addressing_Invalid;
  611. return;
  612. }
  613. if (type == nullptr && is_type_untyped_undef(operand->type)) {
  614. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  615. operand->mode = Addressing_Invalid;
  616. return;
  617. }
  618. target_type = default_type(operand->type);
  619. if (type != nullptr && !is_type_any(type)) {
  620. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  621. }
  622. add_type_info_type(c, type);
  623. add_type_info_type(c, target_type);
  624. }
  625. convert_to_typed(c, operand, target_type);
  626. if (operand->mode == Addressing_Invalid) {
  627. return;
  628. }
  629. }
  630. if (type == nullptr) {
  631. return;
  632. }
  633. if (operand->mode == Addressing_ProcGroup) {
  634. Array<Entity *> procs = proc_group_entities(c, *operand);
  635. bool good = false;
  636. // NOTE(bill): These should be done
  637. for_array(i, procs) {
  638. Type *t = base_type(procs[i]->type);
  639. if (t == t_invalid) {
  640. continue;
  641. }
  642. Operand x = {};
  643. x.mode = Addressing_Value;
  644. x.type = t;
  645. if (check_is_assignable_to(c, &x, type)) {
  646. Entity *e = procs[i];
  647. add_entity_use(c, operand->expr, e);
  648. good = true;
  649. break;
  650. }
  651. }
  652. if (!good) {
  653. gbString expr_str = expr_to_string(operand->expr);
  654. gbString op_type_str = type_to_string(operand->type);
  655. gbString type_str = type_to_string(type);
  656. defer (gb_string_free(type_str));
  657. defer (gb_string_free(op_type_str));
  658. defer (gb_string_free(expr_str));
  659. // TODO(bill): is this a good enough error message?
  660. error(operand->expr,
  661. "Cannot assign overloaded procedure '%s' to '%s' in %.*s",
  662. expr_str,
  663. op_type_str,
  664. LIT(context_name));
  665. operand->mode = Addressing_Invalid;
  666. }
  667. return;
  668. }
  669. if (check_is_assignable_to(c, operand, type)) {
  670. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  671. add_type_info_type(c, operand->type);
  672. add_type_and_value(c->info, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  673. }
  674. } else {
  675. gbString expr_str = expr_to_string(operand->expr);
  676. gbString op_type_str = type_to_string(operand->type);
  677. gbString type_str = type_to_string(type);
  678. defer (gb_string_free(type_str));
  679. defer (gb_string_free(op_type_str));
  680. defer (gb_string_free(expr_str));
  681. switch (operand->mode) {
  682. case Addressing_Builtin:
  683. // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use
  684. error(operand->expr,
  685. "Cannot assign built-in procedure '%s' in %.*s",
  686. expr_str,
  687. LIT(context_name));
  688. break;
  689. case Addressing_Type:
  690. error(operand->expr,
  691. "Cannot assign '%s' which is a type in %.*s",
  692. op_type_str,
  693. LIT(context_name));
  694. break;
  695. default:
  696. // TODO(bill): is this a good enough error message?
  697. error(operand->expr,
  698. "Cannot assign value '%s' of type '%s' to '%s' in %.*s",
  699. expr_str,
  700. op_type_str,
  701. type_str,
  702. LIT(context_name));
  703. check_assignment_error_suggestion(c, operand, type);
  704. break;
  705. }
  706. operand->mode = Addressing_Invalid;
  707. return;
  708. }
  709. }
  710. bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  711. Operand o = {Addressing_Value};
  712. o.type = source;
  713. switch (poly->kind) {
  714. case Type_Basic:
  715. if (compound) return are_types_identical(poly, source);
  716. return check_is_assignable_to(c, &o, poly);
  717. case Type_Named: {
  718. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  719. return true;
  720. }
  721. if (compound || !is_type_generic(poly)) {
  722. return are_types_identical(poly, source);
  723. }
  724. return check_is_assignable_to(c, &o, poly);
  725. }
  726. case Type_Generic: {
  727. if (poly->Generic.specialized != nullptr) {
  728. Type *s = poly->Generic.specialized;
  729. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  730. return false;
  731. }
  732. }
  733. if (modify_type) {
  734. Type *ds = default_type(source); // IMPORTANT TODO(bill): IS THIS CORRECT?
  735. gb_memmove(poly, ds, gb_size_of(Type));
  736. }
  737. return true;
  738. }
  739. case Type_Pointer:
  740. if (source->kind == Type_Pointer) {
  741. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem);
  742. if (level > 0) {
  743. return true;
  744. }
  745. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  746. }
  747. return false;
  748. case Type_Array:
  749. if (source->kind == Type_Array) {
  750. // IMPORTANT TODO(bill): Which is correct?
  751. // if (poly->Array.generic_count != nullptr && modify_type) {
  752. if (poly->Array.generic_count != nullptr) {
  753. Type *gt = poly->Array.generic_count;
  754. GB_ASSERT(gt->kind == Type_Generic);
  755. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  756. GB_ASSERT(e != nullptr);
  757. if (e->kind == Entity_TypeName) {
  758. poly->Array.generic_count = nullptr;
  759. poly->Array.count = source->Array.count;
  760. e->kind = Entity_Constant;
  761. e->Constant.value = exact_value_i64(source->Array.count);
  762. e->type = t_untyped_integer;
  763. } else if (e->kind == Entity_Constant) {
  764. poly->Array.generic_count = nullptr;
  765. if (e->Constant.value.kind != ExactValue_Integer) {
  766. return false;
  767. }
  768. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  769. if (count != source->Array.count) {
  770. return false;
  771. }
  772. poly->Array.count = source->Array.count;
  773. } else {
  774. return false;
  775. }
  776. }
  777. if (poly->Array.count == source->Array.count) {
  778. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  779. }
  780. } else if (source->kind == Type_EnumeratedArray) {
  781. // IMPORTANT TODO(bill): Which is correct?
  782. // if (poly->Array.generic_count != nullptr && modify_type) {
  783. if (poly->Array.generic_count != nullptr) {
  784. Type *gt = poly->Array.generic_count;
  785. GB_ASSERT(gt->kind == Type_Generic);
  786. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  787. GB_ASSERT(e != nullptr);
  788. if (e->kind == Entity_TypeName) {
  789. Type *elem = poly->Array.elem;
  790. Type *index = source->EnumeratedArray.index;
  791. Type *it = base_type(index);
  792. if (it->kind != Type_Enum) {
  793. return false;
  794. }
  795. poly->kind = Type_EnumeratedArray;
  796. poly->cached_size = -1;
  797. poly->cached_align = -1;
  798. poly->flags = source->flags;
  799. poly->failure = false;
  800. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  801. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  802. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  803. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  804. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  805. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  806. e->kind = Entity_TypeName;
  807. e->TypeName.is_type_alias = true;
  808. e->type = index;
  809. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  810. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  811. }
  812. }
  813. }
  814. }
  815. return false;
  816. case Type_EnumeratedArray:
  817. if (source->kind == Type_EnumeratedArray) {
  818. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  819. return false;
  820. }
  821. if (poly->EnumeratedArray.op) {
  822. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  823. return false;
  824. }
  825. if (compare_exact_values(Token_NotEq, poly->EnumeratedArray.min_value, source->EnumeratedArray.min_value)) {
  826. return false;
  827. }
  828. if (compare_exact_values(Token_NotEq, poly->EnumeratedArray.max_value, source->EnumeratedArray.max_value)) {
  829. return false;
  830. }
  831. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  832. }
  833. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  834. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  835. return index || elem;
  836. }
  837. return false;
  838. case Type_DynamicArray:
  839. if (source->kind == Type_DynamicArray) {
  840. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  841. }
  842. return false;
  843. case Type_Slice:
  844. if (source->kind == Type_Slice) {
  845. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  846. }
  847. return false;
  848. case Type_Enum:
  849. return false;
  850. case Type_BitSet:
  851. if (source->kind == Type_BitSet) {
  852. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  853. return false;
  854. }
  855. if (poly->BitSet.underlying == nullptr) {
  856. if (modify_type) {
  857. poly->BitSet.underlying = source->BitSet.underlying;
  858. }
  859. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  860. return false;
  861. }
  862. return true;
  863. }
  864. return false;
  865. case Type_Union:
  866. if (source->kind == Type_Union) {
  867. TypeUnion *x = &poly->Union;
  868. TypeUnion *y = &source->Union;
  869. if (x->variants.count != y->variants.count) {
  870. return false;
  871. }
  872. for_array(i, x->variants) {
  873. Type *a = x->variants[i];
  874. Type *b = y->variants[i];
  875. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  876. if (!ok) return false;
  877. }
  878. return true;
  879. }
  880. return false;
  881. case Type_Struct:
  882. if (source->kind == Type_Struct) {
  883. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  884. poly->Struct.soa_kind != StructSoa_None) {
  885. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  886. if (ok) switch (source->Struct.soa_kind) {
  887. case StructSoa_Fixed:
  888. default:
  889. GB_PANIC("Unhandled SOA Kind");
  890. break;
  891. case StructSoa_Slice:
  892. if (modify_type) {
  893. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  894. gb_memmove(poly, type, gb_size_of(*type));
  895. }
  896. break;
  897. case StructSoa_Dynamic:
  898. if (modify_type) {
  899. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  900. gb_memmove(poly, type, gb_size_of(*type));
  901. }
  902. break;
  903. }
  904. return ok;
  905. }
  906. // return check_is_assignable_to(c, &o, poly);
  907. }
  908. return false;
  909. case Type_Tuple:
  910. GB_PANIC("This should never happen");
  911. return false;
  912. case Type_Proc:
  913. if (source->kind == Type_Proc) {
  914. // return check_is_assignable_to(c, &o, poly);
  915. // TODO(bill): Polymorphic type assignment
  916. #if 1
  917. TypeProc *x = &poly->Proc;
  918. TypeProc *y = &source->Proc;
  919. if (x->calling_convention != y->calling_convention) {
  920. return false;
  921. }
  922. if (x->c_vararg != y->c_vararg) {
  923. return false;
  924. }
  925. if (x->variadic != y->variadic) {
  926. return false;
  927. }
  928. if (x->param_count != y->param_count) {
  929. return false;
  930. }
  931. if (x->result_count != y->result_count) {
  932. return false;
  933. }
  934. for (isize i = 0; i < x->param_count; i++) {
  935. Entity *a = x->params->Tuple.variables[i];
  936. Entity *b = y->params->Tuple.variables[i];
  937. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  938. if (!ok) return false;
  939. }
  940. for (isize i = 0; i < x->result_count; i++) {
  941. Entity *a = x->results->Tuple.variables[i];
  942. Entity *b = y->results->Tuple.variables[i];
  943. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  944. if (!ok) return false;
  945. }
  946. if (modify_type) {
  947. set_procedure_abi_types(source);
  948. }
  949. return true;
  950. #endif
  951. }
  952. return false;
  953. case Type_Map:
  954. if (source->kind == Type_Map) {
  955. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  956. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  957. return key || value;
  958. }
  959. return false;
  960. }
  961. return false;
  962. }
  963. bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  964. if (curr->state != EntityState_InProgress) {
  965. return false;
  966. }
  967. for_array(i, *c->type_path) {
  968. Entity *prev = (*c->type_path)[i];
  969. if (prev == curr) {
  970. if (report) {
  971. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  972. for (isize j = i; j < c->type_path->count; j++) {
  973. Entity *curr = (*c->type_path)[j];
  974. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  975. }
  976. error(curr->token, "\t%.*s", LIT(curr->token.string));
  977. }
  978. return true;
  979. }
  980. }
  981. return false;
  982. }
  983. Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  984. GB_ASSERT(n->kind == Ast_Ident);
  985. o->mode = Addressing_Invalid;
  986. o->expr = n;
  987. String name = n->Ident.token.string;
  988. Entity *e = scope_lookup(c->scope, name);
  989. if (e == nullptr) {
  990. if (is_blank_ident(name)) {
  991. error(n, "'_' cannot be used as a value type");
  992. } else {
  993. error(n, "Undeclared name: %.*s", LIT(name));
  994. }
  995. o->type = t_invalid;
  996. o->mode = Addressing_Invalid;
  997. if (named_type != nullptr) {
  998. set_base_type(named_type, t_invalid);
  999. }
  1000. return nullptr;
  1001. }
  1002. if (e->parent_proc_decl != nullptr &&
  1003. e->parent_proc_decl != c->curr_proc_decl) {
  1004. if (e->kind == Entity_Variable) {
  1005. if ((e->flags & EntityFlag_Static) == 0) {
  1006. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1007. return nullptr;
  1008. }
  1009. } else if (e->kind == Entity_Label) {
  1010. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1011. return nullptr;
  1012. }
  1013. }
  1014. if (e->kind == Entity_ProcGroup) {
  1015. auto *pge = &e->ProcGroup;
  1016. DeclInfo *d = decl_info_of_entity(e);
  1017. check_entity_decl(c, e, d, nullptr);
  1018. Array<Entity *> procs = pge->entities;
  1019. bool skip = false;
  1020. if (type_hint != nullptr) {
  1021. // NOTE(bill): These should be done
  1022. for_array(i, procs) {
  1023. Type *t = base_type(procs[i]->type);
  1024. if (t == t_invalid) {
  1025. continue;
  1026. }
  1027. Operand x = {};
  1028. x.mode = Addressing_Value;
  1029. x.type = t;
  1030. if (check_is_assignable_to(c, &x, type_hint)) {
  1031. e = procs[i];
  1032. add_entity_use(c, n, e);
  1033. skip = true;
  1034. break;
  1035. }
  1036. }
  1037. }
  1038. if (!skip) {
  1039. o->mode = Addressing_ProcGroup;
  1040. o->type = t_invalid;
  1041. o->proc_group = e;
  1042. return nullptr;
  1043. }
  1044. }
  1045. add_entity_use(c, n, e);
  1046. if (e->state == EntityState_Unresolved) {
  1047. check_entity_decl(c, e, nullptr, named_type);
  1048. }
  1049. if (e->type == nullptr) {
  1050. // TODO(bill): Which is correct? return or compiler_error?
  1051. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1052. return nullptr;
  1053. }
  1054. e->flags |= EntityFlag_Used;
  1055. Type *type = e->type;
  1056. o->type = type;
  1057. switch (e->kind) {
  1058. case Entity_Constant:
  1059. if (type == t_invalid) {
  1060. o->type = t_invalid;
  1061. return e;
  1062. }
  1063. o->value = e->Constant.value;
  1064. if (o->value.kind == ExactValue_Invalid) {
  1065. return e;
  1066. }
  1067. if (o->value.kind == ExactValue_Procedure) {
  1068. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1069. if (proc != nullptr) {
  1070. o->mode = Addressing_Value;
  1071. o->type = proc->type;
  1072. return proc;
  1073. }
  1074. }
  1075. o->mode = Addressing_Constant;
  1076. break;
  1077. case Entity_Variable:
  1078. e->flags |= EntityFlag_Used;
  1079. if (type == t_invalid) {
  1080. o->type = t_invalid;
  1081. return e;
  1082. }
  1083. o->mode = Addressing_Variable;
  1084. if (e->flags & EntityFlag_Value) {
  1085. o->mode = Addressing_Value;
  1086. }
  1087. break;
  1088. case Entity_Procedure:
  1089. o->mode = Addressing_Value;
  1090. o->value = exact_value_procedure(n);
  1091. break;
  1092. case Entity_Builtin:
  1093. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1094. o->mode = Addressing_Builtin;
  1095. break;
  1096. case Entity_TypeName:
  1097. o->mode = Addressing_Type;
  1098. if (check_cycle(c, e, true)) {
  1099. type = t_invalid;
  1100. }
  1101. break;
  1102. case Entity_ImportName:
  1103. if (!allow_import_name) {
  1104. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1105. }
  1106. return e;
  1107. case Entity_LibraryName:
  1108. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1109. return e;
  1110. case Entity_Label:
  1111. o->mode = Addressing_NoValue;
  1112. break;
  1113. case Entity_Nil:
  1114. o->mode = Addressing_Value;
  1115. break;
  1116. default:
  1117. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1118. break;
  1119. }
  1120. return e;
  1121. }
  1122. bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1123. if (o->type == nullptr) {
  1124. gbString str = expr_to_string(o->expr);
  1125. error(o->expr, "Expression has no value '%s'", str);
  1126. gb_string_free(str);
  1127. return false;
  1128. }
  1129. // TODO(bill): Handle errors correctly
  1130. Type *type = base_type(core_array_type(o->type));
  1131. gbString str = nullptr;
  1132. switch (op.kind) {
  1133. case Token_Add:
  1134. case Token_Sub:
  1135. if (!is_type_numeric(type)) {
  1136. str = expr_to_string(o->expr);
  1137. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1138. gb_string_free(str);
  1139. }
  1140. break;
  1141. case Token_Xor:
  1142. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1143. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1144. }
  1145. break;
  1146. case Token_Not:
  1147. if (!is_type_boolean(type)) {
  1148. str = expr_to_string(o->expr);
  1149. error(op, "Operator '%.*s' is only allowed on boolean expression", LIT(op.string));
  1150. gb_string_free(str);
  1151. }
  1152. break;
  1153. default:
  1154. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1155. return false;
  1156. }
  1157. return true;
  1158. }
  1159. bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1160. // TODO(bill): Handle errors correctly
  1161. Type *type = base_type(core_array_type(o->type));
  1162. Type *ct = core_type(type);
  1163. switch (op.kind) {
  1164. case Token_Sub:
  1165. case Token_SubEq:
  1166. if (is_type_bit_set(type)) {
  1167. return true;
  1168. } else if (!is_type_numeric(type)) {
  1169. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1170. return false;
  1171. }
  1172. break;
  1173. case Token_Mul:
  1174. case Token_Quo:
  1175. case Token_MulEq:
  1176. case Token_QuoEq:
  1177. case Token_AddEq:
  1178. if (is_type_bit_set(type)) {
  1179. return true;
  1180. } else if (!is_type_numeric(type)) {
  1181. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1182. return false;
  1183. }
  1184. break;
  1185. case Token_Add:
  1186. if (is_type_string(type)) {
  1187. if (o->mode == Addressing_Constant) {
  1188. return true;
  1189. }
  1190. error(op, "String concatenation is only allowed with constant strings");
  1191. return false;
  1192. } else if (is_type_bit_set(type)) {
  1193. return true;
  1194. } else if (!is_type_numeric(type)) {
  1195. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1196. return false;
  1197. }
  1198. break;
  1199. case Token_And:
  1200. case Token_Or:
  1201. case Token_AndEq:
  1202. case Token_OrEq:
  1203. case Token_Xor:
  1204. case Token_XorEq:
  1205. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1206. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1207. return false;
  1208. }
  1209. break;
  1210. case Token_Mod:
  1211. case Token_ModMod:
  1212. case Token_ModEq:
  1213. case Token_ModModEq:
  1214. if (!is_type_integer(type)) {
  1215. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1216. return false;
  1217. }
  1218. if (is_type_simd_vector(o->type)) {
  1219. switch (op.kind) {
  1220. case Token_ModMod:
  1221. case Token_ModModEq:
  1222. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1223. return false;
  1224. }
  1225. }
  1226. break;
  1227. case Token_AndNot:
  1228. case Token_AndNotEq:
  1229. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1230. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1231. return false;
  1232. }
  1233. if (is_type_simd_vector(o->type)) {
  1234. switch (op.kind) {
  1235. case Token_AndNot:
  1236. case Token_AndNotEq:
  1237. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1238. return false;
  1239. }
  1240. }
  1241. break;
  1242. case Token_CmpAnd:
  1243. case Token_CmpOr:
  1244. case Token_CmpAndEq:
  1245. case Token_CmpOrEq:
  1246. if (!is_type_boolean(type)) {
  1247. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1248. return false;
  1249. }
  1250. break;
  1251. default:
  1252. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1253. return false;
  1254. }
  1255. return true;
  1256. }
  1257. bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1258. if (in_value.kind == ExactValue_Invalid) {
  1259. // NOTE(bill): There's already been an error
  1260. return true;
  1261. }
  1262. type = core_type(type);
  1263. if (type == t_invalid) {
  1264. return false;
  1265. } else if (is_type_boolean(type)) {
  1266. return in_value.kind == ExactValue_Bool;
  1267. } else if (is_type_string(type)) {
  1268. return in_value.kind == ExactValue_String;
  1269. } else if (is_type_integer(type) || is_type_rune(type)) {
  1270. if (in_value.kind == ExactValue_Bool) {
  1271. return false;
  1272. }
  1273. ExactValue v = exact_value_to_integer(in_value);
  1274. if (v.kind != ExactValue_Integer) {
  1275. return false;
  1276. }
  1277. if (out_value) *out_value = v;
  1278. if (is_type_untyped(type)) {
  1279. return true;
  1280. }
  1281. BigInt i = v.value_integer;
  1282. i64 bit_size = type_size_of(type);
  1283. BigInt umax = {};
  1284. BigInt imin = {};
  1285. BigInt imax = {};
  1286. if (bit_size < 16) {
  1287. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1288. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1289. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1290. } else {
  1291. big_int_from_u64(&umax, 1);
  1292. big_int_from_i64(&imin, 1);
  1293. big_int_from_i64(&imax, 1);
  1294. BigInt bi128 = {};
  1295. BigInt bi127 = {};
  1296. big_int_from_i64(&bi128, 128);
  1297. big_int_from_i64(&bi127, 127);
  1298. big_int_shl_eq(&umax, &bi128);
  1299. big_int_sub_eq(&umax, &BIG_INT_ONE);
  1300. big_int_shl_eq(&imin, &bi127);
  1301. big_int_neg(&imin, &imin);
  1302. big_int_shl_eq(&imax, &bi127);
  1303. big_int_sub_eq(&imax, &BIG_INT_ONE);
  1304. }
  1305. switch (type->Basic.kind) {
  1306. case Basic_rune:
  1307. case Basic_i8:
  1308. case Basic_i16:
  1309. case Basic_i32:
  1310. case Basic_i64:
  1311. case Basic_i128:
  1312. case Basic_int:
  1313. case Basic_i16le:
  1314. case Basic_i32le:
  1315. case Basic_i64le:
  1316. case Basic_i128le:
  1317. case Basic_i16be:
  1318. case Basic_i32be:
  1319. case Basic_i64be:
  1320. case Basic_i128be:
  1321. {
  1322. // return imin <= i && i <= imax;
  1323. int a = big_int_cmp(&imin, &i);
  1324. int b = big_int_cmp(&i, &imax);
  1325. return (a <= 0) && (b <= 0);
  1326. }
  1327. case Basic_u8:
  1328. case Basic_u16:
  1329. case Basic_u32:
  1330. case Basic_u64:
  1331. case Basic_u128:
  1332. case Basic_uint:
  1333. case Basic_uintptr:
  1334. case Basic_u16le:
  1335. case Basic_u32le:
  1336. case Basic_u64le:
  1337. case Basic_u128le:
  1338. case Basic_u16be:
  1339. case Basic_u32be:
  1340. case Basic_u64be:
  1341. case Basic_u128be:
  1342. {
  1343. // return 0ull <= i && i <= umax;
  1344. int b = big_int_cmp(&i, &umax);
  1345. return !i.neg && (b <= 0);
  1346. }
  1347. case Basic_UntypedInteger:
  1348. return true;
  1349. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1350. }
  1351. } else if (is_type_float(type)) {
  1352. ExactValue v = exact_value_to_float(in_value);
  1353. if (v.kind != ExactValue_Float) {
  1354. return false;
  1355. }
  1356. if (out_value) *out_value = v;
  1357. switch (type->Basic.kind) {
  1358. case Basic_f16:
  1359. case Basic_f32:
  1360. case Basic_f64:
  1361. return true;
  1362. case Basic_f16le:
  1363. case Basic_f16be:
  1364. case Basic_f32le:
  1365. case Basic_f32be:
  1366. case Basic_f64le:
  1367. case Basic_f64be:
  1368. return true;
  1369. case Basic_UntypedFloat:
  1370. return true;
  1371. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1372. }
  1373. } else if (is_type_complex(type)) {
  1374. ExactValue v = exact_value_to_complex(in_value);
  1375. if (v.kind != ExactValue_Complex) {
  1376. return false;
  1377. }
  1378. switch (type->Basic.kind) {
  1379. case Basic_complex32:
  1380. case Basic_complex64:
  1381. case Basic_complex128: {
  1382. ExactValue real = exact_value_real(v);
  1383. ExactValue imag = exact_value_imag(v);
  1384. if (real.kind != ExactValue_Invalid &&
  1385. imag.kind != ExactValue_Invalid) {
  1386. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1387. return true;
  1388. }
  1389. break;
  1390. }
  1391. case Basic_UntypedComplex:
  1392. return true;
  1393. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1394. }
  1395. return false;
  1396. } else if (is_type_quaternion(type)) {
  1397. ExactValue v = exact_value_to_quaternion(in_value);
  1398. if (v.kind != ExactValue_Quaternion) {
  1399. return false;
  1400. }
  1401. switch (type->Basic.kind) {
  1402. case Basic_quaternion64:
  1403. case Basic_quaternion128:
  1404. case Basic_quaternion256: {
  1405. ExactValue real = exact_value_real(v);
  1406. ExactValue imag = exact_value_imag(v);
  1407. ExactValue jmag = exact_value_jmag(v);
  1408. ExactValue kmag = exact_value_kmag(v);
  1409. if (real.kind != ExactValue_Invalid &&
  1410. imag.kind != ExactValue_Invalid) {
  1411. 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));
  1412. return true;
  1413. }
  1414. break;
  1415. }
  1416. case Basic_UntypedComplex:
  1417. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1418. return true;
  1419. case Basic_UntypedQuaternion:
  1420. return true;
  1421. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1422. }
  1423. return false;
  1424. } else if (is_type_pointer(type)) {
  1425. if (in_value.kind == ExactValue_Pointer) {
  1426. return true;
  1427. }
  1428. if (in_value.kind == ExactValue_Integer) {
  1429. return false;
  1430. // return true;
  1431. }
  1432. if (in_value.kind == ExactValue_String) {
  1433. return false;
  1434. }
  1435. if (out_value) *out_value = in_value;
  1436. } else if (is_type_bit_set(type)) {
  1437. if (in_value.kind == ExactValue_Integer) {
  1438. return true;
  1439. }
  1440. }
  1441. return false;
  1442. }
  1443. void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1444. gbString a = expr_to_string(o->expr);
  1445. gbString b = type_to_string(type);
  1446. defer(
  1447. gb_string_free(b);
  1448. gb_string_free(a);
  1449. );
  1450. Type *src = base_type(o->type);
  1451. Type *dst = base_type(type);
  1452. if (is_type_array(src) && is_type_slice(dst)) {
  1453. Type *s = src->Array.elem;
  1454. Type *d = dst->Slice.elem;
  1455. if (are_types_identical(s, d)) {
  1456. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1457. }
  1458. } else if (are_types_identical(src, dst)) {
  1459. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1460. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1461. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1462. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string)) {
  1463. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1464. }
  1465. }
  1466. void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1467. gbString a = expr_to_string(o->expr);
  1468. gbString b = type_to_string(type);
  1469. defer(
  1470. gb_string_free(b);
  1471. gb_string_free(a);
  1472. );
  1473. Type *src = base_type(o->type);
  1474. Type *dst = base_type(type);
  1475. if (is_type_array(src) && is_type_slice(dst)) {
  1476. Type *s = src->Array.elem;
  1477. Type *d = dst->Slice.elem;
  1478. if (are_types_identical(s, d)) {
  1479. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1480. }
  1481. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1482. if (is_type_uintptr(type)) {
  1483. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1484. } else {
  1485. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1486. i64 x = type_size_of(o->type);
  1487. i64 y = type_size_of(type);
  1488. if (x != y) {
  1489. 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);
  1490. }
  1491. }
  1492. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  1493. if (is_type_uintptr(o->type)) {
  1494. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  1495. } else {
  1496. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  1497. }
  1498. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1499. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1500. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string)) {
  1501. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1502. }
  1503. }
  1504. void check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  1505. GB_ASSERT(o->mode == Addressing_Constant);
  1506. if (!is_type_constant_type(type) || !check_representable_as_constant(ctx, o->value, type, &o->value)) {
  1507. gbString a = expr_to_string(o->expr);
  1508. gbString b = type_to_string(type);
  1509. gbString c = type_to_string(o->type);
  1510. defer(
  1511. gb_string_free(c);
  1512. gb_string_free(b);
  1513. gb_string_free(a);
  1514. o->mode = Addressing_Invalid;
  1515. );
  1516. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1517. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1518. error(o->expr, "'%s' truncated to '%s'", a, b);
  1519. } else {
  1520. error(o->expr, "Cannot convert '%s' to '%s' form '%s", a, b, c);
  1521. check_assignment_error_suggestion(ctx, o, type);
  1522. }
  1523. } else {
  1524. error(o->expr, "Cannot convert '%s' to '%s' from '%s", a, b, c);
  1525. check_assignment_error_suggestion(ctx, o, type);
  1526. }
  1527. }
  1528. }
  1529. bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1530. if (o->mode == Addressing_OptionalOk) {
  1531. Ast *expr = unselector_expr(o->expr);
  1532. if (expr->kind != Ast_TypeAssertion) {
  1533. return true;
  1534. }
  1535. ast_node(ta, TypeAssertion, expr);
  1536. TypeAndValue tv = ta->expr->tav;
  1537. if (is_type_pointer(tv.type)) {
  1538. return false;
  1539. }
  1540. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1541. return false;
  1542. }
  1543. if (is_type_any(tv.type)) {
  1544. return false;
  1545. }
  1546. return true;
  1547. }
  1548. if (o->mode == Addressing_MapIndex) {
  1549. return false;
  1550. }
  1551. Ast *expr = unparen_expr(o->expr);
  1552. if (expr->kind == Ast_CompoundLit) {
  1553. return false;
  1554. }
  1555. if (o->mode != Addressing_Variable) {
  1556. return true;
  1557. }
  1558. return false;
  1559. }
  1560. void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  1561. switch (op.kind) {
  1562. case Token_And: { // Pointer address
  1563. if (check_is_not_addressable(c, o)) {
  1564. if (ast_node_expect(node, Ast_UnaryExpr)) {
  1565. ast_node(ue, UnaryExpr, node);
  1566. gbString str = expr_to_string(ue->expr);
  1567. defer (gb_string_free(str));
  1568. Entity *e = entity_of_node(o->expr);
  1569. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  1570. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  1571. } else {
  1572. switch (o->mode) {
  1573. case Addressing_SoaVariable:
  1574. error(op, "Cannot take the pointer address of '%s' as it is an indirect index of an SOA struct", str);
  1575. break;
  1576. case Addressing_Constant:
  1577. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  1578. break;
  1579. default:
  1580. error(op, "Cannot take the pointer address of '%s'", str);
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. o->mode = Addressing_Invalid;
  1586. return;
  1587. }
  1588. o->mode = Addressing_Value;
  1589. o->type = alloc_type_pointer(o->type);
  1590. return;
  1591. }
  1592. }
  1593. if (!check_unary_op(c, o, op)) {
  1594. o->mode = Addressing_Invalid;
  1595. return;
  1596. }
  1597. if (o->mode == Addressing_Constant) {
  1598. Type *type = base_type(o->type);
  1599. if (!is_type_constant_type(o->type)) {
  1600. gbString xt = type_to_string(o->type);
  1601. gbString err_str = expr_to_string(node);
  1602. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  1603. gb_string_free(err_str);
  1604. gb_string_free(xt);
  1605. o->mode = Addressing_Invalid;
  1606. return;
  1607. }
  1608. if (op.kind == Token_Xor && is_type_untyped(type)) {
  1609. gbString err_str = expr_to_string(node);
  1610. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  1611. gb_string_free(err_str);
  1612. o->mode = Addressing_Invalid;
  1613. return;
  1614. }
  1615. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  1616. gbString err_str = expr_to_string(node);
  1617. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  1618. gb_string_free(err_str);
  1619. o->mode = Addressing_Invalid;
  1620. return;
  1621. }
  1622. i32 precision = 0;
  1623. if (is_type_typed(type)) {
  1624. precision = cast(i32)(8 * type_size_of(type));
  1625. }
  1626. bool is_unsigned = is_type_unsigned(type);
  1627. if (is_type_rune(type)) {
  1628. GB_ASSERT(!is_unsigned);
  1629. }
  1630. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  1631. if (is_type_typed(type)) {
  1632. if (node != nullptr) {
  1633. o->expr = node;
  1634. }
  1635. check_is_expressible(c, o, type);
  1636. }
  1637. return;
  1638. }
  1639. o->mode = Addressing_Value;
  1640. }
  1641. void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  1642. if (t == nullptr) {
  1643. return;
  1644. }
  1645. t = base_type(t);
  1646. if (!is_type_comparable(t)) {
  1647. return;
  1648. }
  1649. switch (t->kind) {
  1650. case Type_Basic:
  1651. switch (t->Basic.kind) {
  1652. case Basic_complex64:
  1653. add_package_dependency(c, "runtime", "complex64_eq");
  1654. add_package_dependency(c, "runtime", "complex64_ne");
  1655. break;
  1656. case Basic_complex128:
  1657. add_package_dependency(c, "runtime", "complex128_eq");
  1658. add_package_dependency(c, "runtime", "complex128_ne");
  1659. break;
  1660. case Basic_quaternion128:
  1661. add_package_dependency(c, "runtime", "quaternion128_eq");
  1662. add_package_dependency(c, "runtime", "quaternion128_ne");
  1663. break;
  1664. case Basic_quaternion256:
  1665. add_package_dependency(c, "runtime", "quaternion256_eq");
  1666. add_package_dependency(c, "runtime", "quaternion256_ne");
  1667. break;
  1668. case Basic_cstring:
  1669. add_package_dependency(c, "runtime", "cstring_to_string");
  1670. /*fallthrough*/
  1671. case Basic_string:
  1672. add_package_dependency(c, "runtime", "string_eq");
  1673. add_package_dependency(c, "runtime", "string_ne");
  1674. break;
  1675. }
  1676. break;
  1677. case Type_Struct:
  1678. for_array(i, t->Struct.fields) {
  1679. add_comparison_procedures_for_fields(c, t->Struct.fields[i]->type);
  1680. }
  1681. break;
  1682. }
  1683. }
  1684. void check_comparison(CheckerContext *c, Operand *x, Operand *y, TokenKind op) {
  1685. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  1686. bool comp = are_types_identical(x->type, y->type);
  1687. switch (op) {
  1688. case Token_CmpEq: /* comp = comp; */ break;
  1689. case Token_NotEq: comp = !comp; break;
  1690. }
  1691. x->mode = Addressing_Constant;
  1692. x->type = t_untyped_bool;
  1693. x->value = exact_value_bool(comp);
  1694. return;
  1695. }
  1696. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  1697. add_type_info_type(c, x->type);
  1698. add_type_info_type(c, y->type);
  1699. add_type_and_value(c->info, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  1700. x->mode = Addressing_Value;
  1701. x->type = t_untyped_bool;
  1702. return;
  1703. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  1704. add_type_info_type(c, x->type);
  1705. add_type_info_type(c, y->type);
  1706. add_type_and_value(c->info, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  1707. x->mode = Addressing_Value;
  1708. x->type = t_untyped_bool;
  1709. return;
  1710. }
  1711. gbString err_str = nullptr;
  1712. if (check_is_assignable_to(c, x, y->type) ||
  1713. check_is_assignable_to(c, y, x->type)) {
  1714. Type *err_type = x->type;
  1715. bool defined = false;
  1716. switch (op) {
  1717. case Token_CmpEq:
  1718. case Token_NotEq:
  1719. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  1720. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  1721. (is_operand_nil(*y) && type_has_nil(x->type));
  1722. break;
  1723. case Token_Lt:
  1724. case Token_Gt:
  1725. case Token_LtEq:
  1726. case Token_GtEq:
  1727. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  1728. defined = true;
  1729. } else {
  1730. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  1731. }
  1732. break;
  1733. }
  1734. if (!defined) {
  1735. if (x->type == err_type && is_operand_nil(*x)) {
  1736. err_type = y->type;
  1737. }
  1738. gbString type_string = type_to_string(err_type);
  1739. defer (gb_string_free(type_string));
  1740. err_str = gb_string_make(temporary_allocator(),
  1741. gb_bprintf("operator '%.*s' not defined for type '%s'", LIT(token_strings[op]), type_string));
  1742. } else {
  1743. Type *comparison_type = x->type;
  1744. if (x->type == err_type && is_operand_nil(*x)) {
  1745. comparison_type = y->type;
  1746. }
  1747. add_comparison_procedures_for_fields(c, comparison_type);
  1748. }
  1749. } else {
  1750. gbString xt, yt;
  1751. if (x->mode == Addressing_ProcGroup) {
  1752. xt = gb_string_make(heap_allocator(), "procedure group");
  1753. } else {
  1754. xt = type_to_string(x->type);
  1755. }
  1756. if (y->mode == Addressing_ProcGroup) {
  1757. yt = gb_string_make(heap_allocator(), "procedure group");
  1758. } else {
  1759. yt = type_to_string(y->type);
  1760. }
  1761. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  1762. gb_string_free(yt);
  1763. gb_string_free(xt);
  1764. }
  1765. if (err_str != nullptr) {
  1766. error(x->expr, "Cannot compare expression, %s", err_str);
  1767. x->type = t_untyped_bool;
  1768. } else {
  1769. if (x->mode == Addressing_Constant &&
  1770. y->mode == Addressing_Constant) {
  1771. if (is_type_constant_type(x->type)) {
  1772. if (is_type_bit_set(x->type)) {
  1773. switch (op) {
  1774. case Token_CmpEq:
  1775. case Token_NotEq:
  1776. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  1777. break;
  1778. case Token_Lt:
  1779. case Token_LtEq:
  1780. {
  1781. ExactValue lhs = x->value;
  1782. ExactValue rhs = y->value;
  1783. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  1784. res = exact_value_bool(compare_exact_values(op, res, lhs));
  1785. if (op == Token_Lt) {
  1786. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  1787. }
  1788. x->value = res;
  1789. break;
  1790. }
  1791. case Token_Gt:
  1792. case Token_GtEq:
  1793. {
  1794. ExactValue lhs = x->value;
  1795. ExactValue rhs = y->value;
  1796. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  1797. res = exact_value_bool(compare_exact_values(op, res, rhs));
  1798. if (op == Token_Gt) {
  1799. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  1800. }
  1801. x->value = res;
  1802. break;
  1803. }
  1804. }
  1805. } else {
  1806. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  1807. }
  1808. } else {
  1809. x->mode = Addressing_Value;
  1810. }
  1811. } else {
  1812. x->mode = Addressing_Value;
  1813. update_expr_type(c, x->expr, default_type(x->type), true);
  1814. update_expr_type(c, y->expr, default_type(y->type), true);
  1815. i64 size = 0;
  1816. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  1817. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  1818. if (is_type_string(x->type) || is_type_string(y->type)) {
  1819. switch (op) {
  1820. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  1821. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  1822. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  1823. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  1824. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  1825. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  1826. }
  1827. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  1828. switch (op) {
  1829. case Token_CmpEq:
  1830. switch (8*size) {
  1831. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  1832. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  1833. }
  1834. break;
  1835. case Token_NotEq:
  1836. switch (8*size) {
  1837. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  1838. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  1839. }
  1840. break;
  1841. }
  1842. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  1843. switch (op) {
  1844. case Token_CmpEq:
  1845. switch (8*size) {
  1846. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  1847. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  1848. }
  1849. break;
  1850. case Token_NotEq:
  1851. switch (8*size) {
  1852. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  1853. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  1854. }
  1855. break;
  1856. }
  1857. }
  1858. }
  1859. x->type = t_untyped_bool;
  1860. }
  1861. }
  1862. void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  1863. GB_ASSERT(node->kind == Ast_BinaryExpr);
  1864. ast_node(be, BinaryExpr, node);
  1865. ExactValue x_val = {};
  1866. if (x->mode == Addressing_Constant) {
  1867. x_val = exact_value_to_integer(x->value);
  1868. }
  1869. bool x_is_untyped = is_type_untyped(x->type);
  1870. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  1871. gbString err_str = expr_to_string(x->expr);
  1872. error(node, "Shifted operand '%s' must be an integer", err_str);
  1873. gb_string_free(err_str);
  1874. x->mode = Addressing_Invalid;
  1875. return;
  1876. }
  1877. if (is_type_unsigned(y->type)) {
  1878. } else if (is_type_untyped(y->type)) {
  1879. convert_to_typed(c, y, t_untyped_integer);
  1880. if (y->mode == Addressing_Invalid) {
  1881. x->mode = Addressing_Invalid;
  1882. return;
  1883. }
  1884. } else {
  1885. gbString err_str = expr_to_string(y->expr);
  1886. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  1887. gb_string_free(err_str);
  1888. x->mode = Addressing_Invalid;
  1889. return;
  1890. }
  1891. if (x->mode == Addressing_Constant) {
  1892. if (y->mode == Addressing_Constant) {
  1893. ExactValue y_val = exact_value_to_integer(y->value);
  1894. if (y_val.kind != ExactValue_Integer) {
  1895. gbString err_str = expr_to_string(y->expr);
  1896. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  1897. gb_string_free(err_str);
  1898. x->mode = Addressing_Invalid;
  1899. return;
  1900. }
  1901. BigInt max_shift = {};
  1902. big_int_from_u64(&max_shift, 128);
  1903. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  1904. gbString err_str = expr_to_string(y->expr);
  1905. error(node, "Shift amount too large: '%s'", err_str);
  1906. gb_string_free(err_str);
  1907. x->mode = Addressing_Invalid;
  1908. return;
  1909. }
  1910. if (!is_type_integer(x->type)) {
  1911. // NOTE(bill): It could be an untyped float but still representable
  1912. // as an integer
  1913. x->type = t_untyped_integer;
  1914. }
  1915. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  1916. if (is_type_typed(x->type)) {
  1917. check_is_expressible(c, x, base_type(x->type));
  1918. }
  1919. return;
  1920. }
  1921. TokenPos pos = ast_token(x->expr).pos;
  1922. if (x_is_untyped) {
  1923. ExprInfo *info = check_get_expr_info(&c->checker->info, x->expr);
  1924. if (info != nullptr) {
  1925. info->is_lhs = true;
  1926. }
  1927. x->mode = Addressing_Value;
  1928. if (type_hint && is_type_integer(type_hint)) {
  1929. x->type = type_hint;
  1930. }
  1931. // x->value = x_val;
  1932. return;
  1933. }
  1934. }
  1935. if (y->mode == Addressing_Constant && y->value.value_integer.neg) {
  1936. gbString err_str = expr_to_string(y->expr);
  1937. error(node, "Shift amount cannot be negative: '%s'", err_str);
  1938. gb_string_free(err_str);
  1939. }
  1940. if (!is_type_integer(x->type)) {
  1941. gbString err_str = expr_to_string(y->expr);
  1942. error(node, "Shift operand '%s' must be an integer", err_str);
  1943. gb_string_free(err_str);
  1944. x->mode = Addressing_Invalid;
  1945. return;
  1946. }
  1947. x->mode = Addressing_Value;
  1948. }
  1949. bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  1950. if (check_is_assignable_to(c, operand, y)) {
  1951. return true;
  1952. }
  1953. bool is_constant = operand->mode == Addressing_Constant;
  1954. Type *x = operand->type;
  1955. Type *src = core_type(x);
  1956. Type *dst = core_type(y);
  1957. if (are_types_identical(src, dst)) {
  1958. return true;
  1959. }
  1960. // if (is_type_tuple(src)) {
  1961. // Ast *expr = unparen_expr(operand->expr);
  1962. // if (expr && expr->kind == Ast_CallExpr) {
  1963. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  1964. // ast_node(ce, CallExpr, expr);
  1965. // Type *pt = base_type(type_of_expr(ce->proc));
  1966. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  1967. // if (pt->Proc.result_count > 0) {
  1968. // Operand op = *operand;
  1969. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  1970. // bool ok = check_is_castable_to(c, &op, y);
  1971. // if (ok) {
  1972. // ce->optional_ok_one = true;
  1973. // }
  1974. // return ok;
  1975. // }
  1976. // }
  1977. // }
  1978. // }
  1979. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  1980. if (is_type_u8_array(dst)) {
  1981. String s = operand->value.value_string;
  1982. return s.len == dst->Array.count;
  1983. }
  1984. if (is_type_rune_array(dst)) {
  1985. String s = operand->value.value_string;
  1986. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  1987. }
  1988. }
  1989. if (dst->kind == Type_Array && src->kind == Type_Array) {
  1990. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  1991. return dst->Array.count == src->Array.count;
  1992. }
  1993. }
  1994. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  1995. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  1996. }
  1997. // Cast between booleans and integers
  1998. if (is_type_boolean(src) || is_type_integer(src)) {
  1999. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2000. return true;
  2001. }
  2002. }
  2003. // Cast between numbers
  2004. if (is_type_integer(src) || is_type_float(src)) {
  2005. if (is_type_integer(dst) || is_type_float(dst)) {
  2006. return true;
  2007. }
  2008. }
  2009. if (is_type_integer(src) && is_type_rune(dst)) {
  2010. return true;
  2011. }
  2012. if (is_type_rune(src) && is_type_integer(dst)) {
  2013. return true;
  2014. }
  2015. if (is_type_complex(src) && is_type_complex(dst)) {
  2016. return true;
  2017. }
  2018. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2019. return true;
  2020. }
  2021. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2022. return true;
  2023. }
  2024. // Cast between pointers
  2025. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2026. return true;
  2027. }
  2028. // uintptr <-> pointer
  2029. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2030. return true;
  2031. }
  2032. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2033. return true;
  2034. }
  2035. // []byte/[]u8 <-> string (not cstring)
  2036. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2037. return true;
  2038. }
  2039. if ((is_type_string(src) && !is_type_cstring(src)) && is_type_u8_slice(dst)) {
  2040. // if (is_type_typed(src)) {
  2041. // return true;
  2042. // }
  2043. }
  2044. // cstring -> string
  2045. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2046. if (operand->mode != Addressing_Constant) {
  2047. add_package_dependency(c, "runtime", "cstring_to_string");
  2048. }
  2049. return true;
  2050. }
  2051. // cstring -> ^u8
  2052. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2053. return !is_constant;
  2054. }
  2055. // cstring -> rawptr
  2056. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2057. return !is_constant;
  2058. }
  2059. // ^u8 -> cstring
  2060. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2061. return !is_constant;
  2062. }
  2063. // rawptr -> cstring
  2064. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2065. return !is_constant;
  2066. }
  2067. // proc <-> proc
  2068. if (is_type_proc(src) && is_type_proc(dst)) {
  2069. return true;
  2070. }
  2071. // proc -> rawptr
  2072. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2073. return true;
  2074. }
  2075. // rawptr -> proc
  2076. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2077. return true;
  2078. }
  2079. return false;
  2080. }
  2081. bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2082. bool is_const_expr = x->mode == Addressing_Constant;
  2083. bool can_convert = false;
  2084. Type *bt = base_type(type);
  2085. if (is_const_expr && is_type_constant_type(bt)) {
  2086. if (core_type(bt)->kind == Type_Basic) {
  2087. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2088. return true;
  2089. } else if (is_type_pointer(type) && check_is_castable_to(c, x, type)) {
  2090. return true;
  2091. }
  2092. }
  2093. } else if (check_is_castable_to(c, x, type)) {
  2094. if (x->mode != Addressing_Constant) {
  2095. x->mode = Addressing_Value;
  2096. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2097. x->mode = Addressing_Value;
  2098. } else if (is_type_union(type)) {
  2099. x->mode = Addressing_Value;
  2100. }
  2101. return true;
  2102. }
  2103. return false;
  2104. }
  2105. void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2106. if (!is_operand_value(*x)) {
  2107. error(x->expr, "Only values can be casted");
  2108. x->mode = Addressing_Invalid;
  2109. return;
  2110. }
  2111. bool is_const_expr = x->mode == Addressing_Constant;
  2112. bool can_convert = check_cast_internal(c, x, type);
  2113. if (!can_convert) {
  2114. gbString expr_str = expr_to_string(x->expr);
  2115. gbString to_type = type_to_string(type);
  2116. gbString from_type = type_to_string(x->type);
  2117. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2118. gb_string_free(from_type);
  2119. gb_string_free(to_type);
  2120. gb_string_free(expr_str);
  2121. check_cast_error_suggestion(c, x, type);
  2122. x->mode = Addressing_Invalid;
  2123. return;
  2124. }
  2125. if (is_type_untyped(x->type)) {
  2126. Type *final_type = type;
  2127. if (is_const_expr && !is_type_constant_type(type)) {
  2128. final_type = default_type(x->type);
  2129. }
  2130. update_expr_type(c, x->expr, final_type, true);
  2131. }
  2132. if (build_context.vet_extra) {
  2133. if (are_types_identical(x->type, type)) {
  2134. gbString str = type_to_string(type);
  2135. warning(x->expr, "Unneeded cast to the same type '%s'", str);
  2136. gb_string_free(str);
  2137. }
  2138. }
  2139. x->type = type;
  2140. }
  2141. bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2142. if (!is_operand_value(*o)) {
  2143. error(o->expr, "'transmute' can only be applied to values");
  2144. o->mode = Addressing_Invalid;
  2145. return false;
  2146. }
  2147. if (o->mode == Addressing_Constant) {
  2148. gbString expr_str = expr_to_string(o->expr);
  2149. error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2150. gb_string_free(expr_str);
  2151. o->mode = Addressing_Invalid;
  2152. o->expr = node;
  2153. return false;
  2154. }
  2155. if (is_type_untyped(o->type)) {
  2156. gbString expr_str = expr_to_string(o->expr);
  2157. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2158. gb_string_free(expr_str);
  2159. o->mode = Addressing_Invalid;
  2160. o->expr = node;
  2161. return false;
  2162. }
  2163. i64 srcz = type_size_of(o->type);
  2164. i64 dstz = type_size_of(t);
  2165. if (srcz != dstz) {
  2166. gbString expr_str = expr_to_string(o->expr);
  2167. gbString type_str = type_to_string(t);
  2168. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2169. gb_string_free(type_str);
  2170. gb_string_free(expr_str);
  2171. o->mode = Addressing_Invalid;
  2172. o->expr = node;
  2173. return false;
  2174. }
  2175. if (build_context.vet_extra) {
  2176. if (are_types_identical(o->type, t)) {
  2177. gbString str = type_to_string(t);
  2178. warning(o->expr, "Unneeded transmute to the same type '%s'", str);
  2179. gb_string_free(str);
  2180. }
  2181. }
  2182. o->mode = Addressing_Value;
  2183. o->type = t;
  2184. return true;
  2185. }
  2186. bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2187. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2188. if (check_is_assignable_to(c, y, x->type)) {
  2189. if (check_binary_op(c, x, op)) {
  2190. return true;
  2191. }
  2192. }
  2193. }
  2194. return false;
  2195. }
  2196. void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2197. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2198. Operand y_ = {}, *y = &y_;
  2199. ast_node(be, BinaryExpr, node);
  2200. defer({
  2201. node->viral_state_flags |= be->left->viral_state_flags;
  2202. node->viral_state_flags |= be->right->viral_state_flags;
  2203. });
  2204. Token op = be->op;
  2205. switch (op.kind) {
  2206. case Token_CmpEq:
  2207. case Token_NotEq: {
  2208. // NOTE(bill): Allow comparisons between types
  2209. check_expr_or_type(c, x, be->left, type_hint);
  2210. check_expr_or_type(c, y, be->right, x->type);
  2211. bool xt = x->mode == Addressing_Type;
  2212. bool yt = y->mode == Addressing_Type;
  2213. // If only one is a type, this is an error
  2214. if (xt ^ yt) {
  2215. GB_ASSERT(xt != yt);
  2216. if (xt) {
  2217. if (!is_type_typeid(y->type)) {
  2218. error_operand_not_expression(x);
  2219. }
  2220. }
  2221. if (yt) {
  2222. if (!is_type_typeid(x->type)) {
  2223. error_operand_not_expression(y);
  2224. }
  2225. }
  2226. }
  2227. break;
  2228. }
  2229. case Token_in:
  2230. case Token_not_in:
  2231. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  2232. check_expr(c, y, be->right);
  2233. if (is_type_bit_set(y->type)) {
  2234. Type *elem = base_type(y->type)->BitSet.elem;
  2235. check_expr_with_type_hint(c, x, be->left, elem);
  2236. } else if (is_type_map(y->type)) {
  2237. Type *key = base_type(y->type)->Map.key;
  2238. check_expr_with_type_hint(c, x, be->left, key);
  2239. } else {
  2240. check_expr(c, x, be->left);
  2241. }
  2242. if (x->mode == Addressing_Invalid) {
  2243. return;
  2244. }
  2245. if (y->mode == Addressing_Invalid) {
  2246. x->mode = Addressing_Invalid;
  2247. x->expr = y->expr;
  2248. return;
  2249. }
  2250. if (is_type_map(y->type)) {
  2251. Type *yt = base_type(y->type);
  2252. if (op.kind == Token_in) {
  2253. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  2254. } else {
  2255. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  2256. }
  2257. add_package_dependency(c, "runtime", "__dynamic_map_get");
  2258. } else if (is_type_bit_set(y->type)) {
  2259. Type *yt = base_type(y->type);
  2260. if (op.kind == Token_in) {
  2261. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  2262. } else {
  2263. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  2264. }
  2265. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  2266. ExactValue k = exact_value_to_integer(x->value);
  2267. ExactValue v = exact_value_to_integer(y->value);
  2268. GB_ASSERT(k.kind == ExactValue_Integer);
  2269. GB_ASSERT(v.kind == ExactValue_Integer);
  2270. i64 key = big_int_to_i64(&k.value_integer);
  2271. i64 lower = yt->BitSet.lower;
  2272. i64 upper = yt->BitSet.upper;
  2273. if (lower <= key && key <= upper) {
  2274. i64 bit = 1ll<<key;
  2275. i64 bits = big_int_to_i64(&v.value_integer);
  2276. x->mode = Addressing_Constant;
  2277. x->type = t_untyped_bool;
  2278. if (op.kind == Token_in) {
  2279. x->value = exact_value_bool((bit & bits) != 0);
  2280. } else {
  2281. x->value = exact_value_bool((bit & bits) == 0);
  2282. }
  2283. x->expr = node;
  2284. return;
  2285. } else {
  2286. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  2287. x->mode = Addressing_Invalid;
  2288. }
  2289. }
  2290. } else {
  2291. gbString t = type_to_string(y->type);
  2292. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  2293. gb_string_free(t);
  2294. x->expr = node;
  2295. x->mode = Addressing_Invalid;
  2296. return;
  2297. }
  2298. if (x->mode != Addressing_Invalid) {
  2299. x->mode = Addressing_Value;
  2300. x->type = t_untyped_bool;
  2301. }
  2302. x->expr = node;
  2303. return;
  2304. default:
  2305. check_expr_with_type_hint(c, x, be->left, type_hint);
  2306. if (use_lhs_as_type_hint) {
  2307. check_expr_with_type_hint(c, y, be->right, x->type);
  2308. } else {
  2309. check_expr_with_type_hint(c, y, be->right, type_hint);
  2310. }
  2311. break;
  2312. }
  2313. if (x->mode == Addressing_Invalid) {
  2314. return;
  2315. }
  2316. if (y->mode == Addressing_Invalid) {
  2317. x->mode = Addressing_Invalid;
  2318. x->expr = y->expr;
  2319. return;
  2320. }
  2321. if (x->mode == Addressing_Builtin) {
  2322. x->mode = Addressing_Invalid;
  2323. error(x->expr, "built-in expression in binary expression");
  2324. return;
  2325. }
  2326. if (y->mode == Addressing_Builtin) {
  2327. x->mode = Addressing_Invalid;
  2328. error(y->expr, "built-in expression in binary expression");
  2329. return;
  2330. }
  2331. if (token_is_shift(op.kind)) {
  2332. check_shift(c, x, y, node, type_hint);
  2333. return;
  2334. }
  2335. convert_to_typed(c, x, y->type);
  2336. if (x->mode == Addressing_Invalid) {
  2337. return;
  2338. }
  2339. convert_to_typed(c, y, x->type);
  2340. if (y->mode == Addressing_Invalid) {
  2341. x->mode = Addressing_Invalid;
  2342. return;
  2343. }
  2344. if (token_is_comparison(op.kind)) {
  2345. check_comparison(c, x, y, op.kind);
  2346. return;
  2347. }
  2348. if (check_binary_array_expr(c, op, x, y)) {
  2349. x->mode = Addressing_Value;
  2350. x->type = x->type;
  2351. return;
  2352. }
  2353. if (check_binary_array_expr(c, op, y, x)) {
  2354. x->mode = Addressing_Value;
  2355. x->type = y->type;
  2356. return;
  2357. }
  2358. if (!are_types_identical(x->type, y->type)) {
  2359. if (x->type != t_invalid &&
  2360. y->type != t_invalid) {
  2361. gbString xt = type_to_string(x->type);
  2362. gbString yt = type_to_string(y->type);
  2363. gbString expr_str = expr_to_string(x->expr);
  2364. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  2365. gb_string_free(expr_str);
  2366. gb_string_free(yt);
  2367. gb_string_free(xt);
  2368. }
  2369. x->mode = Addressing_Invalid;
  2370. return;
  2371. }
  2372. if (!check_binary_op(c, x, op)) {
  2373. x->mode = Addressing_Invalid;
  2374. return;
  2375. }
  2376. switch (op.kind) {
  2377. case Token_Quo:
  2378. case Token_Mod:
  2379. case Token_ModMod:
  2380. case Token_QuoEq:
  2381. case Token_ModEq:
  2382. case Token_ModModEq:
  2383. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  2384. y->mode == Addressing_Constant) {
  2385. bool fail = false;
  2386. switch (y->value.kind) {
  2387. case ExactValue_Integer:
  2388. if (big_int_is_zero(&y->value.value_integer)) {
  2389. fail = true;
  2390. }
  2391. break;
  2392. case ExactValue_Float:
  2393. if (y->value.value_float == 0.0) {
  2394. fail = true;
  2395. }
  2396. break;
  2397. }
  2398. if (fail) {
  2399. error(y->expr, "Division by zero not allowed");
  2400. x->mode = Addressing_Invalid;
  2401. return;
  2402. }
  2403. }
  2404. break;
  2405. case Token_CmpAnd:
  2406. case Token_CmpOr:
  2407. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  2408. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  2409. }
  2410. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  2411. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  2412. }
  2413. break;
  2414. }
  2415. if (x->mode == Addressing_Constant &&
  2416. y->mode == Addressing_Constant) {
  2417. ExactValue a = x->value;
  2418. ExactValue b = y->value;
  2419. // Type *type = base_type(x->type);
  2420. Type *type = x->type;
  2421. if (is_type_pointer(type)) {
  2422. GB_ASSERT(op.kind == Token_Sub);
  2423. i64 bytes = a.value_pointer - b.value_pointer;
  2424. i64 diff = bytes/type_size_of(type);
  2425. x->value = exact_value_pointer(diff);
  2426. return;
  2427. }
  2428. if (!is_type_constant_type(type)) {
  2429. gbString xt = type_to_string(x->type);
  2430. gbString err_str = expr_to_string(node);
  2431. error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
  2432. gb_string_free(err_str);
  2433. gb_string_free(xt);
  2434. x->mode = Addressing_Invalid;
  2435. return;
  2436. }
  2437. if (op.kind == Token_Quo && is_type_integer(type)) {
  2438. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  2439. }
  2440. if (is_type_bit_set(type)) {
  2441. switch (op.kind) {
  2442. case Token_Add: op.kind = Token_Or; break;
  2443. case Token_Sub: op.kind = Token_AndNot; break;
  2444. }
  2445. }
  2446. x->value = exact_binary_operator_value(op.kind, a, b);
  2447. if (is_type_typed(type)) {
  2448. if (node != nullptr) {
  2449. x->expr = node;
  2450. }
  2451. check_is_expressible(c, x, type);
  2452. }
  2453. return;
  2454. } else if (is_type_string(x->type)) {
  2455. error(node, "String concatenation is only allowed with constant strings");
  2456. x->mode = Addressing_Invalid;
  2457. return;
  2458. }
  2459. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  2460. Type *bt = base_type(x->type);
  2461. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  2462. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  2463. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  2464. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  2465. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  2466. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  2467. }
  2468. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  2469. Type *bt = base_type(x->type);
  2470. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  2471. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  2472. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  2473. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  2474. }
  2475. }
  2476. x->mode = Addressing_Value;
  2477. }
  2478. void update_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  2479. GB_ASSERT(e != nullptr);
  2480. ExprInfo *found = check_get_expr_info(&c->checker->info, e);
  2481. if (found == nullptr) {
  2482. if (type != nullptr && type != t_invalid) {
  2483. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  2484. add_type_and_value(&c->checker->info, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  2485. }
  2486. }
  2487. return;
  2488. }
  2489. ExprInfo old = *found;
  2490. switch (e->kind) {
  2491. case_ast_node(ue, UnaryExpr, e);
  2492. if (old.value.kind != ExactValue_Invalid) {
  2493. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  2494. // They don't need to be updated as they will be updated later and
  2495. // checked at the end of general checking stage.
  2496. break;
  2497. }
  2498. update_expr_type(c, ue->expr, type, final);
  2499. case_end;
  2500. case_ast_node(be, BinaryExpr, e);
  2501. if (old.value.kind != ExactValue_Invalid) {
  2502. // See above note in UnaryExpr case
  2503. break;
  2504. }
  2505. if (token_is_comparison(be->op.kind)) {
  2506. // NOTE(bill): Do nothing as the types are fine
  2507. } else if (token_is_shift(be->op.kind)) {
  2508. update_expr_type(c, be->left, type, final);
  2509. } else {
  2510. update_expr_type(c, be->left, type, final);
  2511. update_expr_type(c, be->right, type, final);
  2512. }
  2513. case_end;
  2514. case_ast_node(pe, ParenExpr, e);
  2515. update_expr_type(c, pe->expr, type, final);
  2516. case_end;
  2517. }
  2518. if (!final && is_type_untyped(type)) {
  2519. old.type = base_type(type);
  2520. check_set_expr_info(&c->checker->info, e, old);
  2521. return;
  2522. }
  2523. // We need to remove it and then give it a new one
  2524. check_remove_expr_info(&c->checker->info, e);
  2525. if (old.is_lhs && !is_type_integer(type)) {
  2526. gbString expr_str = expr_to_string(e);
  2527. gbString type_str = type_to_string(type);
  2528. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  2529. gb_string_free(type_str);
  2530. gb_string_free(expr_str);
  2531. return;
  2532. }
  2533. add_type_and_value(&c->checker->info, e, old.mode, type, old.value);
  2534. }
  2535. void update_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  2536. ExprInfo *found = check_get_expr_info(&c->checker->info, e);
  2537. if (found) {
  2538. found->value = value;
  2539. }
  2540. }
  2541. void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  2542. gbString expr_str = expr_to_string(operand->expr);
  2543. gbString type_str = type_to_string(target_type);
  2544. gbString from_type_str = type_to_string(operand->type);
  2545. char const *extra_text = "";
  2546. if (operand->mode == Addressing_Constant) {
  2547. if (big_int_is_zero(&operand->value.value_integer)) {
  2548. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  2549. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  2550. extra_text = " - Did you want 'nil'?";
  2551. }
  2552. }
  2553. }
  2554. error(operand->expr, "Cannot convert '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  2555. gb_string_free(from_type_str);
  2556. gb_string_free(type_str);
  2557. gb_string_free(expr_str);
  2558. operand->mode = Addressing_Invalid;
  2559. }
  2560. ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  2561. Type *t = core_type(type);
  2562. if (is_type_boolean(t)) {
  2563. // v = exact_value_to_boolean(v);
  2564. } else if (is_type_float(t)) {
  2565. v = exact_value_to_float(v);
  2566. } else if (is_type_integer(t)) {
  2567. v = exact_value_to_integer(v);
  2568. } else if (is_type_pointer(t)) {
  2569. v = exact_value_to_integer(v);
  2570. } else if (is_type_complex(t)) {
  2571. v = exact_value_to_complex(v);
  2572. } else if (is_type_quaternion(t)) {
  2573. v = exact_value_to_quaternion(v);
  2574. }
  2575. return v;
  2576. }
  2577. void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  2578. GB_ASSERT_NOT_NULL(target_type);
  2579. if (operand->mode == Addressing_Invalid ||
  2580. operand->mode == Addressing_Type ||
  2581. is_type_typed(operand->type) ||
  2582. target_type == t_invalid) {
  2583. return;
  2584. }
  2585. if (is_type_untyped(target_type)) {
  2586. GB_ASSERT(operand->type->kind == Type_Basic);
  2587. GB_ASSERT(target_type->kind == Type_Basic);
  2588. BasicKind x_kind = operand->type->Basic.kind;
  2589. BasicKind y_kind = target_type->Basic.kind;
  2590. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  2591. if (x_kind < y_kind) {
  2592. operand->type = target_type;
  2593. update_expr_type(c, operand->expr, target_type, false);
  2594. }
  2595. } else if (x_kind != y_kind) {
  2596. operand->mode = Addressing_Invalid;
  2597. convert_untyped_error(c, operand, target_type);
  2598. return;
  2599. }
  2600. return;
  2601. }
  2602. Type *t = base_type(target_type);
  2603. if (c->in_enum_type) {
  2604. t = core_type(target_type);
  2605. }
  2606. switch (t->kind) {
  2607. case Type_Basic:
  2608. if (operand->mode == Addressing_Constant) {
  2609. check_is_expressible(c, operand, t);
  2610. if (operand->mode == Addressing_Invalid) {
  2611. return;
  2612. }
  2613. update_expr_value(c, operand->expr, operand->value);
  2614. } else {
  2615. switch (operand->type->Basic.kind) {
  2616. case Basic_UntypedBool:
  2617. if (!is_type_boolean(target_type)) {
  2618. operand->mode = Addressing_Invalid;
  2619. convert_untyped_error(c, operand, target_type);
  2620. return;
  2621. }
  2622. break;
  2623. case Basic_UntypedInteger:
  2624. case Basic_UntypedFloat:
  2625. case Basic_UntypedComplex:
  2626. case Basic_UntypedQuaternion:
  2627. case Basic_UntypedRune:
  2628. if (!is_type_numeric(target_type)) {
  2629. operand->mode = Addressing_Invalid;
  2630. convert_untyped_error(c, operand, target_type);
  2631. return;
  2632. }
  2633. break;
  2634. case Basic_UntypedNil:
  2635. if (is_type_any(target_type)) {
  2636. target_type = t_untyped_nil;
  2637. } else if (is_type_cstring(target_type)) {
  2638. target_type = t_untyped_nil;
  2639. } else if (!type_has_nil(target_type)) {
  2640. operand->mode = Addressing_Invalid;
  2641. convert_untyped_error(c, operand, target_type);
  2642. return;
  2643. }
  2644. break;
  2645. }
  2646. }
  2647. break;
  2648. case Type_Array: {
  2649. Type *elem = base_array_type(t);
  2650. if (check_is_assignable_to(c, operand, elem)) {
  2651. operand->mode = Addressing_Value;
  2652. } else {
  2653. if (operand->value.kind == ExactValue_String) {
  2654. String s = operand->value.value_string;
  2655. if (is_type_u8_array(t)) {
  2656. if (s.len == t->Array.count) {
  2657. break;
  2658. }
  2659. } else if (is_type_rune_array(t)) {
  2660. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  2661. if (rune_count == t->Array.count) {
  2662. break;
  2663. }
  2664. }
  2665. }
  2666. operand->mode = Addressing_Invalid;
  2667. convert_untyped_error(c, operand, target_type);
  2668. return;
  2669. }
  2670. break;
  2671. }
  2672. case Type_Union:
  2673. if (!is_operand_nil(*operand) && !is_operand_undef(*operand)) {
  2674. isize count = t->Union.variants.count;
  2675. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  2676. isize valid_count = 0;
  2677. isize first_success_index = -1;
  2678. for_array(i, t->Union.variants) {
  2679. Type *vt = t->Union.variants[i];
  2680. i64 score = 0;
  2681. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  2682. valids[valid_count].index = i;
  2683. valids[valid_count].score = score;
  2684. valid_count += 1;
  2685. if (first_success_index < 0) {
  2686. first_success_index = i;
  2687. }
  2688. }
  2689. }
  2690. if (valid_count > 1) {
  2691. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  2692. i64 best_score = valids[0].score;
  2693. Type *best_type = t->Union.variants[valids[0].index];
  2694. for (isize i = 1; i < valid_count; i++) {
  2695. auto v = valids[i];
  2696. Type *vt = t->Union.variants[v.index];
  2697. if (best_score > v.score) {
  2698. valid_count = i;
  2699. break;
  2700. }
  2701. best_score = v.score;
  2702. }
  2703. first_success_index = valids[0].index;
  2704. }
  2705. gbString type_str = type_to_string(target_type);
  2706. defer (gb_string_free(type_str));
  2707. if (valid_count == 1) {
  2708. operand->mode = Addressing_Value;
  2709. operand->type = t->Union.variants[first_success_index];
  2710. target_type = t->Union.variants[first_success_index];
  2711. break;
  2712. } else if (valid_count > 1) {
  2713. begin_error_block();
  2714. defer (end_error_block());
  2715. GB_ASSERT(first_success_index >= 0);
  2716. operand->mode = Addressing_Invalid;
  2717. convert_untyped_error(c, operand, target_type);
  2718. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  2719. i32 j = 0;
  2720. for (i32 i = 0; i < valid_count; i++) {
  2721. ValidIndexAndScore valid = valids[i];
  2722. if (j > 0 && valid_count > 2) error_line(", ");
  2723. if (j == valid_count-1) {
  2724. if (valid_count == 2) error_line(" ");
  2725. error_line("or ");
  2726. }
  2727. gbString str = type_to_string(t->Union.variants[valid.index]);
  2728. error_line("'%s'", str);
  2729. gb_string_free(str);
  2730. j++;
  2731. }
  2732. error_line("\n\n");
  2733. return;
  2734. } else if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  2735. target_type = t_untyped_undef;
  2736. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  2737. begin_error_block();
  2738. defer (end_error_block());
  2739. operand->mode = Addressing_Invalid;
  2740. convert_untyped_error(c, operand, target_type);
  2741. if (count > 0) {
  2742. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  2743. error_line("\t");
  2744. for (i32 i = 0; i < count; i++) {
  2745. Type *v = t->Union.variants[i];
  2746. if (i > 0 && count > 2) error_line(", ");
  2747. if (i == count-1) {
  2748. if (count == 2) error_line(" ");
  2749. error_line("or ");
  2750. }
  2751. gbString str = type_to_string(v);
  2752. error_line("'%s'", str);
  2753. gb_string_free(str);
  2754. }
  2755. error_line("\n\n");
  2756. }
  2757. return;
  2758. }
  2759. }
  2760. /* fallthrough */
  2761. default:
  2762. if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  2763. target_type = t_untyped_undef;
  2764. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  2765. target_type = t_untyped_nil;
  2766. } else {
  2767. operand->mode = Addressing_Invalid;
  2768. convert_untyped_error(c, operand, target_type);
  2769. return;
  2770. }
  2771. break;
  2772. }
  2773. operand->type = target_type;
  2774. update_expr_type(c, operand->expr, target_type, true);
  2775. }
  2776. bool check_index_value(CheckerContext *c, bool open_range, Ast *index_value, i64 max_count, i64 *value, Type *type_hint=nullptr) {
  2777. Operand operand = {Addressing_Invalid};
  2778. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  2779. if (operand.mode == Addressing_Invalid) {
  2780. if (value) *value = 0;
  2781. return false;
  2782. }
  2783. Type *index_type = t_int;
  2784. if (type_hint != nullptr) {
  2785. index_type = type_hint;
  2786. }
  2787. convert_to_typed(c, &operand, index_type);
  2788. if (operand.mode == Addressing_Invalid) {
  2789. if (value) *value = 0;
  2790. return false;
  2791. }
  2792. if (type_hint != nullptr) {
  2793. if (!check_is_assignable_to(c, &operand, type_hint)) {
  2794. gbString expr_str = expr_to_string(operand.expr);
  2795. gbString index_type_str = type_to_string(type_hint);
  2796. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  2797. gb_string_free(index_type_str);
  2798. gb_string_free(expr_str);
  2799. if (value) *value = 0;
  2800. return false;
  2801. }
  2802. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  2803. gbString expr_str = expr_to_string(operand.expr);
  2804. error(operand.expr, "Index '%s' must be an integer", expr_str);
  2805. gb_string_free(expr_str);
  2806. if (value) *value = 0;
  2807. return false;
  2808. }
  2809. if (operand.mode == Addressing_Constant &&
  2810. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  2811. BigInt i = exact_value_to_integer(operand.value).value_integer;
  2812. if (i.neg && !is_type_enum(index_type)) {
  2813. gbString expr_str = expr_to_string(operand.expr);
  2814. error(operand.expr, "Index '%s' cannot be a negative value", expr_str);
  2815. gb_string_free(expr_str);
  2816. if (value) *value = 0;
  2817. return false;
  2818. }
  2819. if (max_count >= 0) {
  2820. if (is_type_enum(index_type)) {
  2821. Type *bt = base_type(index_type);
  2822. GB_ASSERT(bt->kind == Type_Enum);
  2823. ExactValue lo = bt->Enum.min_value;
  2824. ExactValue hi = bt->Enum.max_value;
  2825. String lo_str = {};
  2826. String hi_str = {};
  2827. if (bt->Enum.fields.count > 0) {
  2828. lo_str = bt->Enum.fields[bt->Enum.min_value_index]->token.string;
  2829. hi_str = bt->Enum.fields[bt->Enum.max_value_index]->token.string;
  2830. }
  2831. bool out_of_bounds = false;
  2832. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  2833. out_of_bounds = true;
  2834. }
  2835. if (out_of_bounds) {
  2836. gbString expr_str = expr_to_string(operand.expr);
  2837. if (lo_str.len > 0) {
  2838. error(operand.expr, "Index '%s' is out of bounds range %.*s .. %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  2839. } else {
  2840. gbString index_type_str = type_to_string(index_type);
  2841. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  2842. gb_string_free(index_type_str);
  2843. }
  2844. gb_string_free(expr_str);
  2845. return false;
  2846. }
  2847. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  2848. return true;
  2849. } else { // NOTE(bill): Do array bound checking
  2850. i64 v = -1;
  2851. if (i.len <= 1) {
  2852. v = big_int_to_i64(&i);
  2853. }
  2854. if (value) *value = v;
  2855. bool out_of_bounds = false;
  2856. if (v < 0) {
  2857. out_of_bounds = true;
  2858. } else if (open_range) {
  2859. out_of_bounds = v > max_count;
  2860. } else {
  2861. out_of_bounds = v >= max_count;
  2862. }
  2863. if (out_of_bounds) {
  2864. gbString expr_str = expr_to_string(operand.expr);
  2865. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld", expr_str, max_count);
  2866. gb_string_free(expr_str);
  2867. return false;
  2868. }
  2869. return true;
  2870. }
  2871. } else {
  2872. if (value) *value = exact_value_to_i64(operand.value);
  2873. return true;
  2874. }
  2875. }
  2876. // NOTE(bill): It's alright :D
  2877. if (value) *value = -1;
  2878. return true;
  2879. }
  2880. ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  2881. if (value.kind == ExactValue_String) {
  2882. GB_ASSERT(0 <= index && index < value.value_string.len);
  2883. u8 val = value.value_string[index];
  2884. if (success_) *success_ = true;
  2885. if (finish_) *finish_ = true;
  2886. return exact_value_u64(val);
  2887. }
  2888. if (value.kind != ExactValue_Compound) {
  2889. if (success_) *success_ = true;
  2890. if (finish_) *finish_ = true;
  2891. return value;
  2892. }
  2893. Ast *node = value.value_compound;
  2894. switch (node->kind) {
  2895. case_ast_node(cl, CompoundLit, node);
  2896. if (cl->elems.count == 0) {
  2897. if (success_) *success_ = true;
  2898. if (finish_) *finish_ = true;
  2899. return empty_exact_value;
  2900. }
  2901. if (cl->elems[0]->kind == Ast_FieldValue) {
  2902. if (is_type_struct(node->tav.type)) {
  2903. for_array(i, cl->elems) {
  2904. Ast *elem = cl->elems[i];
  2905. if (elem->kind != Ast_FieldValue) {
  2906. continue;
  2907. }
  2908. ast_node(fv, FieldValue, elem);
  2909. String name = fv->field->Ident.token.string;
  2910. Selection sub_sel = lookup_field(node->tav.type, name, false);
  2911. defer (array_free(&sub_sel.index));
  2912. if (sub_sel.index[0] == index) {
  2913. value = fv->value->tav.value;
  2914. break;
  2915. }
  2916. }
  2917. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  2918. for_array(i, cl->elems) {
  2919. Ast *elem = cl->elems[i];
  2920. if (elem->kind != Ast_FieldValue) {
  2921. continue;
  2922. }
  2923. ast_node(fv, FieldValue, elem);
  2924. if (is_ast_range(fv->field)) {
  2925. ast_node(ie, BinaryExpr, fv->field);
  2926. TypeAndValue lo_tav = ie->left->tav;
  2927. TypeAndValue hi_tav = ie->right->tav;
  2928. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  2929. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  2930. TokenKind op = ie->op.kind;
  2931. i64 lo = exact_value_to_i64(lo_tav.value);
  2932. i64 hi = exact_value_to_i64(hi_tav.value);
  2933. i64 corrected_index = index;
  2934. if (is_type_enumerated_array(node->tav.type)) {
  2935. Type *bt = base_type(node->tav.type);
  2936. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  2937. corrected_index = index + exact_value_to_i64(bt->EnumeratedArray.min_value);
  2938. }
  2939. if (op == Token_Ellipsis) {
  2940. if (lo <= corrected_index && corrected_index <= hi) {
  2941. TypeAndValue tav = fv->value->tav;
  2942. if (success_) *success_ = true;
  2943. if (finish_) *finish_ = false;
  2944. return tav.value;
  2945. }
  2946. } else {
  2947. if (lo <= corrected_index && corrected_index < hi) {
  2948. TypeAndValue tav = fv->value->tav;
  2949. if (success_) *success_ = true;
  2950. if (finish_) *finish_ = false;
  2951. return tav.value;
  2952. }
  2953. }
  2954. } else {
  2955. TypeAndValue index_tav = fv->field->tav;
  2956. GB_ASSERT(index_tav.mode == Addressing_Constant);
  2957. ExactValue index_value = index_tav.value;
  2958. if (is_type_enumerated_array(node->tav.type)) {
  2959. Type *bt = base_type(node->tav.type);
  2960. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  2961. index_value = exact_value_sub(index_value, bt->EnumeratedArray.min_value);
  2962. }
  2963. i64 field_index = exact_value_to_i64(index_value);
  2964. if (index == field_index) {
  2965. TypeAndValue tav = fv->value->tav;
  2966. if (success_) *success_ = true;
  2967. if (finish_) *finish_ = false;
  2968. return tav.value;;
  2969. }
  2970. }
  2971. }
  2972. }
  2973. } else {
  2974. i32 count = (i32)cl->elems.count;
  2975. if (count < index) {
  2976. if (success_) *success_ = false;
  2977. if (finish_) *finish_ = true;
  2978. return empty_exact_value;
  2979. }
  2980. if (cl->elems.count <= index) {
  2981. if (success_) *success_ = false;
  2982. if (finish_) *finish_ = false;
  2983. return value;
  2984. }
  2985. TypeAndValue tav = cl->elems[index]->tav;
  2986. if (tav.mode == Addressing_Constant) {
  2987. if (success_) *success_ = true;
  2988. if (finish_) *finish_ = false;
  2989. return tav.value;
  2990. } else {
  2991. GB_ASSERT(is_type_untyped_nil(tav.type));
  2992. if (success_) *success_ = true;
  2993. if (finish_) *finish_ = false;
  2994. return tav.value;
  2995. }
  2996. }
  2997. case_end;
  2998. default:
  2999. // TODO(bill): Should this be a general fallback?
  3000. if (success_) *success_ = true;
  3001. if (finish_) *finish_ = true;
  3002. return empty_exact_value;
  3003. }
  3004. if (finish_) *finish_ = false;
  3005. return value;
  3006. }
  3007. ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3008. if (operand->mode != Addressing_Constant) {
  3009. if (success_) *success_ = false;
  3010. return empty_exact_value;
  3011. }
  3012. if (sel.indirect) {
  3013. if (success_) *success_ = false;
  3014. return empty_exact_value;
  3015. }
  3016. if (sel.index.count == 0) {
  3017. if (success_) *success_ = false;
  3018. return empty_exact_value;
  3019. }
  3020. ExactValue value = operand->value;
  3021. if (value.kind == ExactValue_Compound) {
  3022. i32 depth = 0;
  3023. while (sel.index.count > 0) {
  3024. i32 index = sel.index[0];
  3025. sel = sub_selection(sel, 1);
  3026. bool finish = false;
  3027. value = get_constant_field_single(c, value, index, success_, &finish);
  3028. if (finish) {
  3029. return value;
  3030. }
  3031. }
  3032. if (success_) *success_ = true;
  3033. return value;
  3034. } else if (value.kind == ExactValue_Quaternion) {
  3035. // @QuaternionLayout
  3036. Quaternion256 q = *value.value_quaternion;
  3037. GB_ASSERT(sel.index.count == 1);
  3038. switch (sel.index[0]) {
  3039. case 3: // w
  3040. if (success_) *success_ = true;
  3041. return exact_value_float(q.real);
  3042. case 0: // x
  3043. if (success_) *success_ = true;
  3044. return exact_value_float(q.imag);
  3045. case 1: // y
  3046. if (success_) *success_ = true;
  3047. return exact_value_float(q.jmag);
  3048. case 2: // z
  3049. if (success_) *success_ = true;
  3050. return exact_value_float(q.kmag);
  3051. }
  3052. if (success_) *success_ = false;
  3053. return empty_exact_value;
  3054. } else if (value.kind == ExactValue_Complex) {
  3055. // @QuaternionLayout
  3056. Complex128 c = *value.value_complex;
  3057. GB_ASSERT(sel.index.count == 1);
  3058. switch (sel.index[0]) {
  3059. case 0: // real
  3060. if (success_) *success_ = true;
  3061. return exact_value_float(c.real);
  3062. case 1: // imag
  3063. if (success_) *success_ = true;
  3064. return exact_value_float(c.imag);
  3065. }
  3066. if (success_) *success_ = false;
  3067. return empty_exact_value;
  3068. }
  3069. if (success_) *success_ = true;
  3070. return empty_exact_value;
  3071. }
  3072. Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  3073. ast_node(se, SelectorExpr, node);
  3074. bool check_op_expr = true;
  3075. Entity *expr_entity = nullptr;
  3076. Entity *entity = nullptr;
  3077. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  3078. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  3079. error(node, "Illegal use of -> selector shorthand outside of a call");
  3080. operand->mode = Addressing_Invalid;
  3081. operand->expr = node;
  3082. return nullptr;
  3083. }
  3084. operand->expr = node;
  3085. Ast *op_expr = se->expr;
  3086. Ast *selector = unparen_expr(se->selector);
  3087. if (selector == nullptr) {
  3088. operand->mode = Addressing_Invalid;
  3089. operand->expr = node;
  3090. return nullptr;
  3091. }
  3092. if (selector->kind != Ast_Ident) {
  3093. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  3094. operand->mode = Addressing_Invalid;
  3095. operand->expr = node;
  3096. return nullptr;
  3097. }
  3098. if (op_expr->kind == Ast_Ident) {
  3099. String op_name = op_expr->Ident.token.string;
  3100. Entity *e = scope_lookup(c->scope, op_name);
  3101. add_entity_use(c, op_expr, e);
  3102. expr_entity = e;
  3103. Entity *original_e = e;
  3104. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  3105. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  3106. // It pretty much needs to be in this order and this way
  3107. // If you can clean this up, please do but be really careful
  3108. String import_name = op_name;
  3109. Scope *import_scope = e->ImportName.scope;
  3110. String entity_name = selector->Ident.token.string;
  3111. check_op_expr = false;
  3112. entity = scope_lookup_current(import_scope, entity_name);
  3113. bool is_declared = entity != nullptr;
  3114. bool allow_builtin = false;
  3115. if (is_declared) {
  3116. if (entity->kind == Entity_Builtin) {
  3117. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  3118. // This means that we should just ignore the found result through it
  3119. allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  3120. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  3121. is_declared = false;
  3122. }
  3123. }
  3124. if (!is_declared) {
  3125. error(op_expr, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  3126. operand->mode = Addressing_Invalid;
  3127. operand->expr = node;
  3128. return nullptr;
  3129. }
  3130. check_entity_decl(c, entity, nullptr, nullptr);
  3131. if (entity->kind == Entity_ProcGroup) {
  3132. operand->mode = Addressing_ProcGroup;
  3133. operand->proc_group = entity;
  3134. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3135. return entity;
  3136. }
  3137. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  3138. if (!is_entity_exported(entity, allow_builtin)) {
  3139. gbString sel_str = expr_to_string(selector);
  3140. error(op_expr, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  3141. gb_string_free(sel_str);
  3142. // NOTE(bill): make the state valid still, even if it's "invalid"
  3143. // operand->mode = Addressing_Invalid;
  3144. // operand->expr = node;
  3145. // return nullptr;
  3146. }
  3147. if (entity->kind == Entity_ProcGroup) {
  3148. Array<Entity *> procs = entity->ProcGroup.entities;
  3149. bool skip = false;
  3150. for_array(i, procs) {
  3151. Entity *p = procs[i];
  3152. Type *t = base_type(p->type);
  3153. if (t == t_invalid) {
  3154. continue;
  3155. }
  3156. Operand x = {};
  3157. x.mode = Addressing_Value;
  3158. x.type = t;
  3159. if (type_hint != nullptr) {
  3160. if (check_is_assignable_to(c, &x, type_hint)) {
  3161. entity = p;
  3162. skip = true;
  3163. break;
  3164. }
  3165. }
  3166. }
  3167. if (!skip) {
  3168. GB_ASSERT(entity != nullptr);
  3169. operand->mode = Addressing_ProcGroup;
  3170. operand->type = t_invalid;
  3171. operand->expr = node;
  3172. operand->proc_group = entity;
  3173. return entity;
  3174. }
  3175. }
  3176. }
  3177. }
  3178. if (check_op_expr) {
  3179. check_expr_base(c, operand, op_expr, nullptr);
  3180. if (operand->mode == Addressing_Invalid) {
  3181. operand->mode = Addressing_Invalid;
  3182. operand->expr = node;
  3183. return nullptr;
  3184. }
  3185. }
  3186. if (entity == nullptr && selector->kind == Ast_Ident) {
  3187. String field_name = selector->Ident.token.string;
  3188. if (is_type_dynamic_array(type_deref(operand->type))) {
  3189. init_mem_allocator(c->checker);
  3190. }
  3191. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  3192. entity = sel.entity;
  3193. // NOTE(bill): Add type info needed for fields like 'names'
  3194. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  3195. add_type_info_type(c, operand->type);
  3196. }
  3197. if (is_type_enum(operand->type)) {
  3198. add_type_info_type(c, operand->type);
  3199. }
  3200. }
  3201. if (entity == nullptr) {
  3202. gbString op_str = expr_to_string(op_expr);
  3203. gbString type_str = type_to_string(operand->type);
  3204. gbString sel_str = expr_to_string(selector);
  3205. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  3206. gb_string_free(sel_str);
  3207. gb_string_free(type_str);
  3208. gb_string_free(op_str);
  3209. operand->mode = Addressing_Invalid;
  3210. operand->expr = node;
  3211. return nullptr;
  3212. }
  3213. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  3214. bool success = false;
  3215. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  3216. if (success) {
  3217. operand->mode = Addressing_Constant;
  3218. operand->expr = node;
  3219. operand->value = field_value;
  3220. operand->type = entity->type;
  3221. add_entity_use(c, selector, entity);
  3222. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3223. return entity;
  3224. }
  3225. gbString op_str = expr_to_string(op_expr);
  3226. gbString type_str = type_to_string(operand->type);
  3227. gbString sel_str = expr_to_string(selector);
  3228. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  3229. gb_string_free(sel_str);
  3230. gb_string_free(type_str);
  3231. gb_string_free(op_str);
  3232. operand->mode = Addressing_Invalid;
  3233. operand->expr = node;
  3234. return nullptr;
  3235. }
  3236. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  3237. bool success = false;
  3238. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  3239. if (success) {
  3240. operand->mode = Addressing_Constant;
  3241. operand->expr = node;
  3242. operand->value = field_value;
  3243. operand->type = entity->type;
  3244. add_entity_use(c, selector, entity);
  3245. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3246. return entity;
  3247. }
  3248. gbString op_str = expr_to_string(op_expr);
  3249. gbString type_str = type_to_string(operand->type);
  3250. gbString sel_str = expr_to_string(selector);
  3251. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  3252. gb_string_free(sel_str);
  3253. gb_string_free(type_str);
  3254. gb_string_free(op_str);
  3255. operand->mode = Addressing_Invalid;
  3256. operand->expr = node;
  3257. return nullptr;
  3258. }
  3259. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  3260. gbString op_str = expr_to_string(op_expr);
  3261. gbString type_str = type_to_string(operand->type);
  3262. gbString sel_str = expr_to_string(selector);
  3263. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  3264. gb_string_free(sel_str);
  3265. gb_string_free(type_str);
  3266. gb_string_free(op_str);
  3267. operand->mode = Addressing_Invalid;
  3268. operand->expr = node;
  3269. return nullptr;
  3270. }
  3271. add_entity_use(c, selector, entity);
  3272. operand->type = entity->type;
  3273. operand->expr = node;
  3274. switch (entity->kind) {
  3275. case Entity_Constant:
  3276. operand->value = entity->Constant.value;
  3277. operand->mode = Addressing_Constant;
  3278. if (operand->value.kind == ExactValue_Procedure) {
  3279. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  3280. if (proc != nullptr) {
  3281. operand->mode = Addressing_Value;
  3282. operand->type = proc->type;
  3283. }
  3284. }
  3285. break;
  3286. case Entity_Variable:
  3287. if (sel.indirect) {
  3288. operand->mode = Addressing_Variable;
  3289. } else if (operand->mode == Addressing_Context) {
  3290. // Do nothing
  3291. } else if (operand->mode == Addressing_MapIndex) {
  3292. operand->mode = Addressing_Value;
  3293. } else if (entity->flags & EntityFlag_SoaPtrField) {
  3294. operand->mode = Addressing_SoaVariable;
  3295. } else if (operand->mode == Addressing_OptionalOk) {
  3296. operand->mode = Addressing_Value;
  3297. } else if (operand->mode == Addressing_SoaVariable) {
  3298. operand->mode = Addressing_Variable;
  3299. } else if (operand->mode != Addressing_Value) {
  3300. operand->mode = Addressing_Variable;
  3301. } else {
  3302. operand->mode = Addressing_Value;
  3303. }
  3304. break;
  3305. case Entity_TypeName:
  3306. operand->mode = Addressing_Type;
  3307. break;
  3308. case Entity_Procedure:
  3309. operand->mode = Addressing_Value;
  3310. operand->value = exact_value_procedure(node);
  3311. break;
  3312. case Entity_Builtin:
  3313. operand->mode = Addressing_Builtin;
  3314. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  3315. break;
  3316. case Entity_ProcGroup:
  3317. operand->mode = Addressing_ProcGroup;
  3318. operand->proc_group = entity;
  3319. break;
  3320. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  3321. case Entity_Nil:
  3322. operand->mode = Addressing_Value;
  3323. break;
  3324. }
  3325. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3326. return entity;
  3327. }
  3328. bool is_type_normal_pointer(Type *ptr, Type **elem) {
  3329. ptr = base_type(ptr);
  3330. if (is_type_pointer(ptr)) {
  3331. if (is_type_rawptr(ptr)) {
  3332. return false;
  3333. }
  3334. if (elem) *elem = ptr->Pointer.elem;
  3335. return true;
  3336. }
  3337. return false;
  3338. }
  3339. bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  3340. switch (node->kind) {
  3341. case_ast_node(i, Ident, node);
  3342. String name = i->token.string;
  3343. if (nested) {
  3344. Entity *e = scope_lookup_current(s, name);
  3345. if (e != nullptr) {
  3346. if (out_scope) *out_scope = e->scope;
  3347. return true;
  3348. }
  3349. } else {
  3350. Entity *e = scope_lookup(s, name);
  3351. if (e != nullptr) {
  3352. if (out_scope) *out_scope = e->scope;
  3353. return true;
  3354. }
  3355. }
  3356. case_end;
  3357. case_ast_node(se, SelectorExpr, node);
  3358. Ast *lhs = se->expr;
  3359. Ast *rhs = se->selector;
  3360. Scope *lhs_scope = nullptr;
  3361. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  3362. return check_identifier_exists(lhs_scope, rhs, true);
  3363. }
  3364. case_end;
  3365. }
  3366. return false;
  3367. }
  3368. typedef bool (BuiltinTypeIsProc)(Type *t);
  3369. BuiltinTypeIsProc *builtin_type_is_procs[BuiltinProc__type_simple_boolean_end - BuiltinProc__type_simple_boolean_begin] = {
  3370. nullptr, // BuiltinProc__type_simple_boolean_begin
  3371. is_type_boolean,
  3372. is_type_integer,
  3373. is_type_rune,
  3374. is_type_float,
  3375. is_type_complex,
  3376. is_type_quaternion,
  3377. is_type_string,
  3378. is_type_typeid,
  3379. is_type_any,
  3380. is_type_endian_little,
  3381. is_type_endian_big,
  3382. is_type_unsigned,
  3383. is_type_numeric,
  3384. is_type_ordered,
  3385. is_type_ordered_numeric,
  3386. is_type_indexable,
  3387. is_type_sliceable,
  3388. is_type_comparable,
  3389. is_type_simple_compare,
  3390. is_type_dereferenceable,
  3391. is_type_valid_for_keys,
  3392. is_type_named,
  3393. is_type_pointer,
  3394. is_type_array,
  3395. is_type_enumerated_array,
  3396. is_type_slice,
  3397. is_type_dynamic_array,
  3398. is_type_map,
  3399. is_type_struct,
  3400. is_type_union,
  3401. is_type_enum,
  3402. is_type_proc,
  3403. is_type_bit_set,
  3404. is_type_simd_vector,
  3405. is_type_polymorphic_record_specialized,
  3406. is_type_polymorphic_record_unspecialized,
  3407. type_has_nil,
  3408. };
  3409. bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint) {
  3410. ast_node(ce, CallExpr, call);
  3411. if (ce->inlining != ProcInlining_none) {
  3412. error(call, "Inlining operators are not allowed on built-in procedures");
  3413. }
  3414. BuiltinProc *bp = &builtin_procs[id];
  3415. {
  3416. char const *err = nullptr;
  3417. if (ce->args.count < bp->arg_count) {
  3418. err = "Too few";
  3419. } else if (ce->args.count > bp->arg_count && !bp->variadic) {
  3420. err = "Too many";
  3421. }
  3422. if (err != nullptr) {
  3423. gbString expr = expr_to_string(ce->proc);
  3424. error(ce->close, "%s arguments for '%s', expected %td, got %td",
  3425. err, expr,
  3426. bp->arg_count, ce->args.count);
  3427. gb_string_free(expr);
  3428. return false;
  3429. }
  3430. }
  3431. switch (id) {
  3432. case BuiltinProc_size_of:
  3433. case BuiltinProc_align_of:
  3434. case BuiltinProc_offset_of:
  3435. case BuiltinProc_type_info_of:
  3436. case BuiltinProc_typeid_of:
  3437. case BuiltinProc_len:
  3438. case BuiltinProc_min:
  3439. case BuiltinProc_max:
  3440. // NOTE(bill): The first arg may be a Type, this will be checked case by case
  3441. break;
  3442. case BuiltinProc_DIRECTIVE: {
  3443. ast_node(bd, BasicDirective, ce->proc);
  3444. String name = bd->name;
  3445. if (name == "defined") {
  3446. break;
  3447. }
  3448. if (name == "config") {
  3449. break;
  3450. }
  3451. /*fallthrough*/
  3452. }
  3453. default:
  3454. if (BuiltinProc__type_begin < id && id < BuiltinProc__type_end) {
  3455. check_expr_or_type(c, operand, ce->args[0]);
  3456. } else if (ce->args.count > 0) {
  3457. check_multi_expr(c, operand, ce->args[0]);
  3458. }
  3459. break;
  3460. }
  3461. String builtin_name = builtin_procs[id].name;
  3462. if (ce->args.count > 0) {
  3463. if (ce->args[0]->kind == Ast_FieldValue) {
  3464. if (id != BuiltinProc_soa_zip) {
  3465. error(call, "'field = value' calling is not allowed on built-in procedures");
  3466. return false;
  3467. }
  3468. }
  3469. }
  3470. switch (id) {
  3471. default:
  3472. GB_PANIC("Implement built-in procedure: %.*s", LIT(builtin_name));
  3473. break;
  3474. case BuiltinProc_DIRECTIVE: {
  3475. ast_node(bd, BasicDirective, ce->proc);
  3476. String name = bd->name;
  3477. if (name == "location") {
  3478. if (ce->args.count > 1) {
  3479. error(ce->args[0], "'#location' expects either 0 or 1 arguments, got %td", ce->args.count);
  3480. }
  3481. if (ce->args.count > 0) {
  3482. Ast *arg = ce->args[0];
  3483. Entity *e = nullptr;
  3484. Operand o = {};
  3485. if (arg->kind == Ast_Ident) {
  3486. e = check_ident(c, &o, arg, nullptr, nullptr, true);
  3487. } else if (arg->kind == Ast_SelectorExpr) {
  3488. e = check_selector(c, &o, arg, nullptr);
  3489. }
  3490. if (e == nullptr) {
  3491. error(ce->args[0], "'#location' expected a valid entity name");
  3492. }
  3493. }
  3494. operand->type = t_source_code_location;
  3495. operand->mode = Addressing_Value;
  3496. } else if (name == "load") {
  3497. if (ce->args.count != 1) {
  3498. error(ce->args[0], "'#load' expects 1 argument, got %td", ce->args.count);
  3499. return false;
  3500. }
  3501. Ast *arg = ce->args[0];
  3502. Operand o = {};
  3503. check_expr(c, &o, arg);
  3504. if (o.mode != Addressing_Constant) {
  3505. error(arg, "'#load' expected a constant string argument");
  3506. return false;
  3507. }
  3508. if (!is_type_string(o.type)) {
  3509. gbString str = type_to_string(o.type);
  3510. error(arg, "'#load' expected a constant string, got %s", str);
  3511. gb_string_free(str);
  3512. return false;
  3513. }
  3514. gbAllocator a = heap_allocator();
  3515. GB_ASSERT(o.value.kind == ExactValue_String);
  3516. String base_dir = dir_from_path(get_file_path_string(bd->token.pos.file_id));
  3517. String original_string = o.value.value_string;
  3518. gbMutex *ignore_mutex = nullptr;
  3519. String path = {};
  3520. bool ok = determine_path_from_string(ignore_mutex, call, base_dir, original_string, &path);
  3521. char *c_str = alloc_cstring(a, path);
  3522. defer (gb_free(a, c_str));
  3523. gbFile f = {};
  3524. gbFileError file_err = gb_file_open(&f, c_str);
  3525. defer (gb_file_close(&f));
  3526. switch (file_err) {
  3527. default:
  3528. case gbFileError_Invalid:
  3529. error(ce->proc, "Failed to `#load` file: %s; invalid file or cannot be found", c_str);
  3530. return false;
  3531. case gbFileError_NotExists:
  3532. error(ce->proc, "Failed to `#load` file: %s; file cannot be found", c_str);
  3533. return false;
  3534. case gbFileError_Permission:
  3535. error(ce->proc, "Failed to `#load` file: %s; file permissions problem", c_str);
  3536. return false;
  3537. case gbFileError_None:
  3538. // Okay
  3539. break;
  3540. }
  3541. String result = {};
  3542. isize file_size = cast(isize)gb_file_size(&f);
  3543. if (file_size > 0) {
  3544. u8 *data = cast(u8 *)gb_alloc(a, file_size+1);
  3545. gb_file_read_at(&f, data, file_size, 0);
  3546. data[file_size] = '\0';
  3547. result.text = data;
  3548. result.len = file_size;
  3549. }
  3550. operand->type = t_u8_slice;
  3551. operand->mode = Addressing_Constant;
  3552. operand->value = exact_value_string(result);
  3553. } else if (name == "assert") {
  3554. if (ce->args.count != 1) {
  3555. error(call, "'#assert' expects 1 argument, got %td", ce->args.count);
  3556. return false;
  3557. }
  3558. if (!is_type_boolean(operand->type) || operand->mode != Addressing_Constant) {
  3559. gbString str = expr_to_string(ce->args[0]);
  3560. error(call, "'%s' is not a constant boolean", str);
  3561. gb_string_free(str);
  3562. return false;
  3563. }
  3564. if (!operand->value.value_bool) {
  3565. gbString arg = expr_to_string(ce->args[0]);
  3566. error(call, "Compile time assertion: %s", arg);
  3567. if (c->proc_name != "") {
  3568. gbString str = type_to_string(c->curr_proc_sig);
  3569. error_line("\tCalled within '%.*s' :: %s\n", LIT(c->proc_name), str);
  3570. gb_string_free(str);
  3571. }
  3572. gb_string_free(arg);
  3573. }
  3574. operand->type = t_untyped_bool;
  3575. operand->mode = Addressing_Constant;
  3576. } else if (name == "panic") {
  3577. if (ce->args.count != 1) {
  3578. error(call, "'#panic' expects 1 argument, got %td", ce->args.count);
  3579. return false;
  3580. }
  3581. if (!is_type_string(operand->type) && operand->mode != Addressing_Constant) {
  3582. gbString str = expr_to_string(ce->args[0]);
  3583. error(call, "'%s' is not a constant string", str);
  3584. gb_string_free(str);
  3585. return false;
  3586. }
  3587. error(call, "Compile time panic: %.*s", LIT(operand->value.value_string));
  3588. if (c->proc_name != "") {
  3589. gbString str = type_to_string(c->curr_proc_sig);
  3590. error_line("\tCalled within '%.*s' :: %s\n", LIT(c->proc_name), str);
  3591. gb_string_free(str);
  3592. }
  3593. operand->type = t_invalid;
  3594. operand->mode = Addressing_NoValue;
  3595. } else if (name == "defined") {
  3596. if (ce->args.count != 1) {
  3597. error(call, "'#defined' expects 1 argument, got %td", ce->args.count);
  3598. return false;
  3599. }
  3600. Ast *arg = unparen_expr(ce->args[0]);
  3601. if (arg == nullptr || (arg->kind != Ast_Ident && arg->kind != Ast_SelectorExpr)) {
  3602. error(call, "'#defined' expects an identifier or selector expression, got %.*s", LIT(ast_strings[arg->kind]));
  3603. return false;
  3604. }
  3605. if (c->curr_proc_decl == nullptr) {
  3606. error(call, "'#defined' is only allowed within a procedure, prefer the replacement '#config(NAME, default_value)'");
  3607. return false;
  3608. }
  3609. bool is_defined = check_identifier_exists(c->scope, arg);
  3610. operand->type = t_untyped_bool;
  3611. operand->mode = Addressing_Constant;
  3612. operand->value = exact_value_bool(false);
  3613. } else if (name == "config") {
  3614. if (ce->args.count != 2) {
  3615. error(call, "'#config' expects 2 argument, got %td", ce->args.count);
  3616. return false;
  3617. }
  3618. Ast *arg = unparen_expr(ce->args[0]);
  3619. if (arg == nullptr || arg->kind != Ast_Ident) {
  3620. error(call, "'#config' expects an identifier, got %.*s", LIT(ast_strings[arg->kind]));
  3621. return false;
  3622. }
  3623. Ast *def_arg = unparen_expr(ce->args[1]);
  3624. Operand def = {};
  3625. check_expr(c, &def, def_arg);
  3626. if (def.mode != Addressing_Constant) {
  3627. error(def_arg, "'#config' default value must be a constant");
  3628. return false;
  3629. }
  3630. String name = arg->Ident.token.string;
  3631. operand->type = def.type;
  3632. operand->mode = def.mode;
  3633. operand->value = def.value;
  3634. Entity *found = scope_lookup_current(config_pkg->scope, name);
  3635. if (found != nullptr) {
  3636. if (found->kind != Entity_Constant) {
  3637. error(arg, "'#config' entity '%.*s' found but expected a constant", LIT(name));
  3638. } else {
  3639. operand->type = found->type;
  3640. operand->mode = Addressing_Constant;
  3641. operand->value = found->Constant.value;
  3642. }
  3643. }
  3644. } else {
  3645. GB_PANIC("Unhandled #%.*s", LIT(name));
  3646. }
  3647. break;
  3648. }
  3649. case BuiltinProc_len:
  3650. check_expr_or_type(c, operand, ce->args[0]);
  3651. if (operand->mode == Addressing_Invalid) {
  3652. return false;
  3653. }
  3654. /* fallthrough */
  3655. case BuiltinProc_cap:
  3656. {
  3657. // len :: proc(Type) -> int
  3658. // cap :: proc(Type) -> int
  3659. Type *op_type = type_deref(operand->type);
  3660. Type *type = t_int;
  3661. AddressingMode mode = Addressing_Invalid;
  3662. ExactValue value = {};
  3663. if (is_type_string(op_type) && id == BuiltinProc_len) {
  3664. if (operand->mode == Addressing_Constant) {
  3665. mode = Addressing_Constant;
  3666. String str = operand->value.value_string;
  3667. value = exact_value_i64(str.len);
  3668. type = t_untyped_integer;
  3669. } else {
  3670. mode = Addressing_Value;
  3671. if (is_type_cstring(op_type)) {
  3672. add_package_dependency(c, "runtime", "cstring_len");
  3673. }
  3674. }
  3675. } else if (is_type_array(op_type)) {
  3676. Type *at = core_type(op_type);
  3677. mode = Addressing_Constant;
  3678. value = exact_value_i64(at->Array.count);
  3679. type = t_untyped_integer;
  3680. } else if (is_type_enumerated_array(op_type) && id == BuiltinProc_len) {
  3681. Type *at = core_type(op_type);
  3682. mode = Addressing_Constant;
  3683. value = exact_value_i64(at->EnumeratedArray.count);
  3684. type = t_untyped_integer;
  3685. } else if (is_type_slice(op_type) && id == BuiltinProc_len) {
  3686. mode = Addressing_Value;
  3687. } else if (is_type_dynamic_array(op_type)) {
  3688. mode = Addressing_Value;
  3689. } else if (is_type_map(op_type)) {
  3690. mode = Addressing_Value;
  3691. } else if (operand->mode == Addressing_Type && is_type_enum(op_type) && id == BuiltinProc_len) {
  3692. Type *bt = base_type(op_type);
  3693. mode = Addressing_Constant;
  3694. value = exact_value_i64(bt->Enum.fields.count);
  3695. type = t_untyped_integer;
  3696. } else if (is_type_struct(op_type)) {
  3697. Type *bt = base_type(op_type);
  3698. if (bt->Struct.soa_kind == StructSoa_Fixed) {
  3699. mode = Addressing_Constant;
  3700. value = exact_value_i64(bt->Struct.soa_count);
  3701. type = t_untyped_integer;
  3702. } else if ((bt->Struct.soa_kind == StructSoa_Slice && id == BuiltinProc_len) ||
  3703. bt->Struct.soa_kind == StructSoa_Dynamic) {
  3704. mode = Addressing_Value;
  3705. }
  3706. }
  3707. if (operand->mode == Addressing_Type && mode != Addressing_Constant) {
  3708. mode = Addressing_Invalid;
  3709. }
  3710. if (mode == Addressing_Invalid) {
  3711. gbString t = type_to_string(operand->type);
  3712. error(call, "'%.*s' is not supported for '%s'", LIT(builtin_name), t);
  3713. return false;
  3714. }
  3715. operand->mode = mode;
  3716. operand->value = value;
  3717. operand->type = type;
  3718. break;
  3719. }
  3720. case BuiltinProc_size_of: {
  3721. // size_of :: proc(Type or expr) -> untyped int
  3722. Operand o = {};
  3723. check_expr_or_type(c, &o, ce->args[0]);
  3724. if (o.mode == Addressing_Invalid) {
  3725. return false;
  3726. }
  3727. Type *t = o.type;
  3728. if (t == nullptr || t == t_invalid) {
  3729. error(ce->args[0], "Invalid argument for 'size_of'");
  3730. return false;
  3731. }
  3732. t = default_type(t);
  3733. operand->mode = Addressing_Constant;
  3734. operand->value = exact_value_i64(type_size_of(t));
  3735. operand->type = t_untyped_integer;
  3736. break;
  3737. }
  3738. case BuiltinProc_align_of: {
  3739. // align_of :: proc(Type or expr) -> untyped int
  3740. Operand o = {};
  3741. check_expr_or_type(c, &o, ce->args[0]);
  3742. if (o.mode == Addressing_Invalid) {
  3743. return false;
  3744. }
  3745. Type *t = o.type;
  3746. if (t == nullptr || t == t_invalid) {
  3747. error(ce->args[0], "Invalid argument for 'align_of'");
  3748. return false;
  3749. }
  3750. t = default_type(t);
  3751. operand->mode = Addressing_Constant;
  3752. operand->value = exact_value_i64(type_align_of(t));
  3753. operand->type = t_untyped_integer;
  3754. break;
  3755. }
  3756. case BuiltinProc_offset_of: {
  3757. // offset_of :: proc(Type, field) -> uintptr
  3758. Operand op = {};
  3759. Type *bt = check_type(c, ce->args[0]);
  3760. Type *type = base_type(bt);
  3761. if (type == nullptr || type == t_invalid) {
  3762. error(ce->args[0], "Expected a type for 'offset_of'");
  3763. return false;
  3764. }
  3765. Ast *field_arg = unparen_expr(ce->args[1]);
  3766. if (field_arg == nullptr ||
  3767. field_arg->kind != Ast_Ident) {
  3768. error(field_arg, "Expected an identifier for field argument");
  3769. return false;
  3770. }
  3771. if (is_type_array(type)) {
  3772. error(field_arg, "Invalid type for 'offset_of'");
  3773. return false;
  3774. }
  3775. ast_node(arg, Ident, field_arg);
  3776. Selection sel = lookup_field(type, arg->token.string, operand->mode == Addressing_Type);
  3777. if (sel.entity == nullptr) {
  3778. gbString type_str = type_to_string(bt);
  3779. error(ce->args[0],
  3780. "'%s' has no field named '%.*s'", type_str, LIT(arg->token.string));
  3781. gb_string_free(type_str);
  3782. return false;
  3783. }
  3784. if (sel.indirect) {
  3785. gbString type_str = type_to_string(bt);
  3786. error(ce->args[0],
  3787. "Field '%.*s' is embedded via a pointer in '%s'", LIT(arg->token.string), type_str);
  3788. gb_string_free(type_str);
  3789. return false;
  3790. }
  3791. operand->mode = Addressing_Constant;
  3792. operand->value = exact_value_i64(type_offset_of_from_selection(type, sel));
  3793. operand->type = t_uintptr;
  3794. break;
  3795. }
  3796. case BuiltinProc_type_of: {
  3797. // type_of :: proc(val: Type) -> type(Type)
  3798. Ast *expr = ce->args[0];
  3799. Operand o = {};
  3800. check_expr_or_type(c, &o, expr);
  3801. // check_assignment(c, operand, nullptr, str_lit("argument of 'type_of'"));
  3802. if (o.mode == Addressing_Invalid || o.mode == Addressing_Builtin) {
  3803. return false;
  3804. }
  3805. if (o.type == nullptr || o.type == t_invalid || is_type_asm_proc(o.type)) {
  3806. error(o.expr, "Invalid argument to 'type_of'");
  3807. return false;
  3808. }
  3809. // NOTE(bill): Prevent type cycles for procedure declarations
  3810. if (c->curr_proc_sig == o.type) {
  3811. gbString s = expr_to_string(o.expr);
  3812. error(o.expr, "Invalid cyclic type usage from 'type_of', got '%s'", s);
  3813. gb_string_free(s);
  3814. return false;
  3815. }
  3816. if (is_type_polymorphic(o.type)) {
  3817. error(o.expr, "'type_of' of polymorphic type cannot be determined");
  3818. return false;
  3819. }
  3820. operand->mode = Addressing_Type;
  3821. operand->type = o.type;
  3822. break;
  3823. }
  3824. case BuiltinProc_type_info_of: {
  3825. // type_info_of :: proc(Type) -> ^Type_Info
  3826. if (c->scope->flags&ScopeFlag_Global) {
  3827. compiler_error("'type_info_of' Cannot be declared within the runtime package due to how the internals of the compiler works");
  3828. }
  3829. // NOTE(bill): The type information may not be setup yet
  3830. init_core_type_info(c->checker);
  3831. Ast *expr = ce->args[0];
  3832. Operand o = {};
  3833. check_expr_or_type(c, &o, expr);
  3834. if (o.mode == Addressing_Invalid) {
  3835. return false;
  3836. }
  3837. Type *t = o.type;
  3838. if (t == nullptr || t == t_invalid || is_type_asm_proc(o.type) || is_type_polymorphic(t)) {
  3839. if (is_type_polymorphic(t)) {
  3840. error(ce->args[0], "Invalid argument for 'type_info_of', unspecialized polymorphic type");
  3841. } else {
  3842. error(ce->args[0], "Invalid argument for 'type_info_of'");
  3843. }
  3844. return false;
  3845. }
  3846. t = default_type(t);
  3847. add_type_info_type(c, t);
  3848. if (is_operand_value(o) && is_type_typeid(t)) {
  3849. add_package_dependency(c, "runtime", "__type_info_of");
  3850. } else if (o.mode != Addressing_Type) {
  3851. error(expr, "Expected a type or typeid for 'type_info_of'");
  3852. return false;
  3853. }
  3854. operand->mode = Addressing_Value;
  3855. operand->type = t_type_info_ptr;
  3856. break;
  3857. }
  3858. case BuiltinProc_typeid_of: {
  3859. // typeid_of :: proc(Type) -> typeid
  3860. if (c->scope->flags&ScopeFlag_Global) {
  3861. compiler_error("'typeid_of' Cannot be declared within the runtime package due to how the internals of the compiler works");
  3862. }
  3863. // NOTE(bill): The type information may not be setup yet
  3864. init_core_type_info(c->checker);
  3865. Ast *expr = ce->args[0];
  3866. Operand o = {};
  3867. check_expr_or_type(c, &o, expr);
  3868. if (o.mode == Addressing_Invalid) {
  3869. return false;
  3870. }
  3871. Type *t = o.type;
  3872. if (t == nullptr || t == t_invalid || is_type_asm_proc(o.type) || is_type_polymorphic(operand->type)) {
  3873. error(ce->args[0], "Invalid argument for 'typeid_of'");
  3874. return false;
  3875. }
  3876. t = default_type(t);
  3877. add_type_info_type(c, t);
  3878. if (o.mode != Addressing_Type) {
  3879. error(expr, "Expected a type for 'typeid_of'");
  3880. return false;
  3881. }
  3882. operand->mode = Addressing_Value;
  3883. operand->type = t_typeid;
  3884. operand->value = exact_value_typeid(t);
  3885. break;
  3886. }
  3887. case BuiltinProc_swizzle: {
  3888. // swizzle :: proc(v: [N]T, ..int) -> [M]T
  3889. Type *type = base_type(operand->type);
  3890. i64 max_count = 0;
  3891. Type *elem_type = nullptr;
  3892. if (!is_type_array(type) && !is_type_simd_vector(type)) {
  3893. gbString type_str = type_to_string(operand->type);
  3894. error(call,
  3895. "'swizzle' is only allowed on an array or #simd vector, got '%s'",
  3896. type_str);
  3897. gb_string_free(type_str);
  3898. return false;
  3899. }
  3900. if (type->kind == Type_Array) {
  3901. max_count = type->Array.count;
  3902. elem_type = type->Array.elem;
  3903. } else if (type->kind == Type_SimdVector) {
  3904. max_count = type->SimdVector.count;
  3905. elem_type = type->SimdVector.elem;
  3906. if (!build_context.use_llvm_api) {
  3907. error(call, "'swizzle' with #simd vector is not supported on this backend");
  3908. }
  3909. }
  3910. i64 arg_count = 0;
  3911. for_array(i, ce->args) {
  3912. if (i == 0) {
  3913. continue;
  3914. }
  3915. Ast *arg = ce->args[i];
  3916. Operand op = {};
  3917. check_expr(c, &op, arg);
  3918. if (op.mode == Addressing_Invalid) {
  3919. return false;
  3920. }
  3921. Type *arg_type = base_type(op.type);
  3922. if (!is_type_integer(arg_type) || op.mode != Addressing_Constant) {
  3923. error(op.expr, "Indices to 'swizzle' must be constant integers");
  3924. return false;
  3925. }
  3926. if (op.value.value_integer.neg) {
  3927. error(op.expr, "Negative 'swizzle' index");
  3928. return false;
  3929. }
  3930. BigInt mc = {};
  3931. big_int_from_i64(&mc, max_count);
  3932. if (big_int_cmp(&mc, &op.value.value_integer) <= 0) {
  3933. error(op.expr, "'swizzle' index exceeds length");
  3934. return false;
  3935. }
  3936. arg_count++;
  3937. }
  3938. if (arg_count > max_count) {
  3939. error(call, "Too many 'swizzle' indices, %td > %td", arg_count, max_count);
  3940. return false;
  3941. }
  3942. if (arg_count < max_count) {
  3943. operand->type = alloc_type_array(elem_type, arg_count);
  3944. }
  3945. operand->mode = Addressing_Value;
  3946. if (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {
  3947. operand->type = type_hint;
  3948. }
  3949. break;
  3950. }
  3951. case BuiltinProc_complex: {
  3952. // complex :: proc(real, imag: float_type) -> complex_type
  3953. Operand x = *operand;
  3954. Operand y = {};
  3955. // NOTE(bill): Invalid will be the default till fixed
  3956. operand->type = t_invalid;
  3957. operand->mode = Addressing_Invalid;
  3958. check_expr(c, &y, ce->args[1]);
  3959. if (y.mode == Addressing_Invalid) {
  3960. return false;
  3961. }
  3962. convert_to_typed(c, &x, y.type); if (x.mode == Addressing_Invalid) return false;
  3963. convert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;
  3964. if (x.mode == Addressing_Constant &&
  3965. y.mode == Addressing_Constant) {
  3966. if (is_type_numeric(x.type) && exact_value_imag(x.value).value_float == 0) {
  3967. x.type = t_untyped_float;
  3968. }
  3969. if (is_type_numeric(y.type) && exact_value_imag(y.value).value_float == 0) {
  3970. y.type = t_untyped_float;
  3971. }
  3972. }
  3973. if (!are_types_identical(x.type, y.type)) {
  3974. gbString tx = type_to_string(x.type);
  3975. gbString ty = type_to_string(y.type);
  3976. error(call, "Mismatched types to 'complex', '%s' vs '%s'", tx, ty);
  3977. gb_string_free(ty);
  3978. gb_string_free(tx);
  3979. return false;
  3980. }
  3981. if (!is_type_float(x.type)) {
  3982. gbString s = type_to_string(x.type);
  3983. error(call, "Arguments have type '%s', expected a floating point", s);
  3984. gb_string_free(s);
  3985. return false;
  3986. }
  3987. if (is_type_endian_specific(x.type)) {
  3988. gbString s = type_to_string(x.type);
  3989. error(call, "Arguments with a specified endian are not allow, expected a normal floating point, got '%s'", s);
  3990. gb_string_free(s);
  3991. return false;
  3992. }
  3993. if (x.mode == Addressing_Constant && y.mode == Addressing_Constant) {
  3994. f64 r = exact_value_to_float(x.value).value_float;
  3995. f64 i = exact_value_to_float(y.value).value_float;
  3996. operand->value = exact_value_complex(r, i);
  3997. operand->mode = Addressing_Constant;
  3998. } else {
  3999. operand->mode = Addressing_Value;
  4000. }
  4001. BasicKind kind = core_type(x.type)->Basic.kind;
  4002. switch (kind) {
  4003. case Basic_f16: operand->type = t_complex32; break;
  4004. case Basic_f32: operand->type = t_complex64; break;
  4005. case Basic_f64: operand->type = t_complex128; break;
  4006. case Basic_UntypedFloat: operand->type = t_untyped_complex; break;
  4007. default: GB_PANIC("Invalid type"); break;
  4008. }
  4009. if (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {
  4010. operand->type = type_hint;
  4011. }
  4012. break;
  4013. }
  4014. case BuiltinProc_quaternion: {
  4015. // quaternion :: proc(real, imag, jmag, kmag: float_type) -> complex_type
  4016. Operand x = *operand;
  4017. Operand y = {};
  4018. Operand z = {};
  4019. Operand w = {};
  4020. // NOTE(bill): Invalid will be the default till fixed
  4021. operand->type = t_invalid;
  4022. operand->mode = Addressing_Invalid;
  4023. check_expr(c, &y, ce->args[1]);
  4024. if (y.mode == Addressing_Invalid) {
  4025. return false;
  4026. }
  4027. check_expr(c, &z, ce->args[2]);
  4028. if (y.mode == Addressing_Invalid) {
  4029. return false;
  4030. }
  4031. check_expr(c, &w, ce->args[3]);
  4032. if (y.mode == Addressing_Invalid) {
  4033. return false;
  4034. }
  4035. convert_to_typed(c, &x, y.type); if (x.mode == Addressing_Invalid) return false;
  4036. convert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;
  4037. convert_to_typed(c, &z, x.type); if (z.mode == Addressing_Invalid) return false;
  4038. convert_to_typed(c, &w, x.type); if (w.mode == Addressing_Invalid) return false;
  4039. if (x.mode == Addressing_Constant &&
  4040. y.mode == Addressing_Constant &&
  4041. z.mode == Addressing_Constant &&
  4042. w.mode == Addressing_Constant) {
  4043. if (is_type_numeric(x.type) && exact_value_imag(x.value).value_float == 0) {
  4044. x.type = t_untyped_float;
  4045. }
  4046. if (is_type_numeric(y.type) && exact_value_imag(y.value).value_float == 0) {
  4047. y.type = t_untyped_float;
  4048. }
  4049. if (is_type_numeric(z.type) && exact_value_imag(z.value).value_float == 0) {
  4050. z.type = t_untyped_float;
  4051. }
  4052. if (is_type_numeric(w.type) && exact_value_imag(w.value).value_float == 0) {
  4053. w.type = t_untyped_float;
  4054. }
  4055. }
  4056. if (!(are_types_identical(x.type, y.type) && are_types_identical(x.type, z.type) && are_types_identical(x.type, w.type))) {
  4057. gbString tx = type_to_string(x.type);
  4058. gbString ty = type_to_string(y.type);
  4059. gbString tz = type_to_string(z.type);
  4060. gbString tw = type_to_string(w.type);
  4061. error(call, "Mismatched types to 'quaternion', '%s' vs '%s' vs '%s' vs '%s'", tx, ty, tz, tw);
  4062. gb_string_free(tw);
  4063. gb_string_free(tz);
  4064. gb_string_free(ty);
  4065. gb_string_free(tx);
  4066. return false;
  4067. }
  4068. if (!is_type_float(x.type)) {
  4069. gbString s = type_to_string(x.type);
  4070. error(call, "Arguments have type '%s', expected a floating point", s);
  4071. gb_string_free(s);
  4072. return false;
  4073. }
  4074. if (is_type_endian_specific(x.type)) {
  4075. gbString s = type_to_string(x.type);
  4076. error(call, "Arguments with a specified endian are not allow, expected a normal floating point, got '%s'", s);
  4077. gb_string_free(s);
  4078. return false;
  4079. }
  4080. if (x.mode == Addressing_Constant && y.mode == Addressing_Constant && z.mode == Addressing_Constant && w.mode == Addressing_Constant) {
  4081. f64 r = exact_value_to_float(x.value).value_float;
  4082. f64 i = exact_value_to_float(y.value).value_float;
  4083. f64 j = exact_value_to_float(z.value).value_float;
  4084. f64 k = exact_value_to_float(w.value).value_float;
  4085. operand->value = exact_value_quaternion(r, i, j, k);
  4086. operand->mode = Addressing_Constant;
  4087. } else {
  4088. operand->mode = Addressing_Value;
  4089. }
  4090. BasicKind kind = core_type(x.type)->Basic.kind;
  4091. switch (kind) {
  4092. case Basic_f16: operand->type = t_quaternion64; break;
  4093. case Basic_f32: operand->type = t_quaternion128; break;
  4094. case Basic_f64: operand->type = t_quaternion256; break;
  4095. case Basic_UntypedFloat: operand->type = t_untyped_quaternion; 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_real:
  4104. case BuiltinProc_imag: {
  4105. // real :: proc(x: type) -> float_type
  4106. // imag :: proc(x: type) -> float_type
  4107. Operand *x = operand;
  4108. if (is_type_untyped(x->type)) {
  4109. if (x->mode == Addressing_Constant) {
  4110. if (is_type_numeric(x->type)) {
  4111. x->type = t_untyped_complex;
  4112. }
  4113. } else if (is_type_quaternion(x->type)) {
  4114. convert_to_typed(c, x, t_quaternion256);
  4115. if (x->mode == Addressing_Invalid) {
  4116. return false;
  4117. }
  4118. } else{
  4119. convert_to_typed(c, x, t_complex128);
  4120. if (x->mode == Addressing_Invalid) {
  4121. return false;
  4122. }
  4123. }
  4124. }
  4125. if (!is_type_complex(x->type) && !is_type_quaternion(x->type)) {
  4126. gbString s = type_to_string(x->type);
  4127. error(call, "Argument has type '%s', expected a complex or quaternion type", s);
  4128. gb_string_free(s);
  4129. return false;
  4130. }
  4131. if (x->mode == Addressing_Constant) {
  4132. switch (id) {
  4133. case BuiltinProc_real: x->value = exact_value_real(x->value); break;
  4134. case BuiltinProc_imag: x->value = exact_value_imag(x->value); break;
  4135. }
  4136. } else {
  4137. x->mode = Addressing_Value;
  4138. }
  4139. BasicKind kind = core_type(x->type)->Basic.kind;
  4140. switch (kind) {
  4141. case Basic_complex32: x->type = t_f16; break;
  4142. case Basic_complex64: x->type = t_f32; break;
  4143. case Basic_complex128: x->type = t_f64; break;
  4144. case Basic_quaternion64: x->type = t_f16; break;
  4145. case Basic_quaternion128: x->type = t_f32; break;
  4146. case Basic_quaternion256: x->type = t_f64; break;
  4147. case Basic_UntypedComplex: x->type = t_untyped_float; break;
  4148. case Basic_UntypedQuaternion: x->type = t_untyped_float; break;
  4149. default: GB_PANIC("Invalid type"); break;
  4150. }
  4151. if (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {
  4152. operand->type = type_hint;
  4153. }
  4154. break;
  4155. }
  4156. case BuiltinProc_jmag:
  4157. case BuiltinProc_kmag: {
  4158. // jmag :: proc(x: type) -> float_type
  4159. // kmag :: proc(x: type) -> float_type
  4160. Operand *x = operand;
  4161. if (is_type_untyped(x->type)) {
  4162. if (x->mode == Addressing_Constant) {
  4163. if (is_type_numeric(x->type)) {
  4164. x->type = t_untyped_complex;
  4165. }
  4166. } else{
  4167. convert_to_typed(c, x, t_quaternion256);
  4168. if (x->mode == Addressing_Invalid) {
  4169. return false;
  4170. }
  4171. }
  4172. }
  4173. if (!is_type_quaternion(x->type)) {
  4174. gbString s = type_to_string(x->type);
  4175. error(call, "Argument has type '%s', expected a quaternion type", s);
  4176. gb_string_free(s);
  4177. return false;
  4178. }
  4179. if (x->mode == Addressing_Constant) {
  4180. switch (id) {
  4181. case BuiltinProc_jmag: x->value = exact_value_jmag(x->value); break;
  4182. case BuiltinProc_kmag: x->value = exact_value_kmag(x->value); break;
  4183. }
  4184. } else {
  4185. x->mode = Addressing_Value;
  4186. }
  4187. BasicKind kind = core_type(x->type)->Basic.kind;
  4188. switch (kind) {
  4189. case Basic_quaternion64: x->type = t_f16; break;
  4190. case Basic_quaternion128: x->type = t_f32; break;
  4191. case Basic_quaternion256: x->type = t_f64; break;
  4192. case Basic_UntypedComplex: x->type = t_untyped_float; break;
  4193. case Basic_UntypedQuaternion: x->type = t_untyped_float; break;
  4194. default: GB_PANIC("Invalid type"); break;
  4195. }
  4196. if (type_hint != nullptr && check_is_castable_to(c, operand, type_hint)) {
  4197. operand->type = type_hint;
  4198. }
  4199. break;
  4200. }
  4201. case BuiltinProc_conj: {
  4202. // conj :: proc(x: type) -> type
  4203. Operand *x = operand;
  4204. if (is_type_complex(x->type)) {
  4205. if (x->mode == Addressing_Constant) {
  4206. ExactValue v = exact_value_to_complex(x->value);
  4207. f64 r = v.value_complex->real;
  4208. f64 i = -v.value_complex->imag;
  4209. x->value = exact_value_complex(r, i);
  4210. x->mode = Addressing_Constant;
  4211. } else {
  4212. x->mode = Addressing_Value;
  4213. }
  4214. } else if (is_type_quaternion(x->type)) {
  4215. if (x->mode == Addressing_Constant) {
  4216. ExactValue v = exact_value_to_quaternion(x->value);
  4217. f64 r = +v.value_quaternion->real;
  4218. f64 i = -v.value_quaternion->imag;
  4219. f64 j = -v.value_quaternion->jmag;
  4220. f64 k = -v.value_quaternion->kmag;
  4221. x->value = exact_value_quaternion(r, i, j, k);
  4222. x->mode = Addressing_Constant;
  4223. } else {
  4224. x->mode = Addressing_Value;
  4225. }
  4226. } else {
  4227. gbString s = type_to_string(x->type);
  4228. error(call, "Expected a complex or quaternion, got '%s'", s);
  4229. gb_string_free(s);
  4230. return false;
  4231. }
  4232. break;
  4233. }
  4234. case BuiltinProc_expand_to_tuple: {
  4235. Type *type = base_type(operand->type);
  4236. if (!is_type_struct(type) && !is_type_array(type)) {
  4237. gbString type_str = type_to_string(operand->type);
  4238. error(call, "Expected a struct or array type, got '%s'", type_str);
  4239. gb_string_free(type_str);
  4240. return false;
  4241. }
  4242. gbAllocator a = permanent_allocator();
  4243. Type *tuple = alloc_type_tuple();
  4244. if (is_type_struct(type)) {
  4245. isize variable_count = type->Struct.fields.count;
  4246. array_init(&tuple->Tuple.variables, a, variable_count);
  4247. // TODO(bill): Should I copy each of the entities or is this good enough?
  4248. gb_memmove_array(tuple->Tuple.variables.data, type->Struct.fields.data, variable_count);
  4249. } else if (is_type_array(type)) {
  4250. isize variable_count = type->Array.count;
  4251. array_init(&tuple->Tuple.variables, a, variable_count);
  4252. for (isize i = 0; i < variable_count; i++) {
  4253. tuple->Tuple.variables[i] = alloc_entity_array_elem(nullptr, blank_token, type->Array.elem, cast(i32)i);
  4254. }
  4255. }
  4256. operand->type = tuple;
  4257. operand->mode = Addressing_Value;
  4258. if (tuple->Tuple.variables.count == 1) {
  4259. operand->type = tuple->Tuple.variables[0]->type;
  4260. }
  4261. break;
  4262. }
  4263. case BuiltinProc_min: {
  4264. // min :: proc($T: typeid) -> ordered
  4265. // min :: proc(a: ..ordered) -> ordered
  4266. check_multi_expr_or_type(c, operand, ce->args[0]);
  4267. Type *original_type = operand->type;
  4268. Type *type = base_type(operand->type);
  4269. if (operand->mode == Addressing_Type && is_type_enumerated_array(type)) {
  4270. // Okay
  4271. } else if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {
  4272. gbString type_str = type_to_string(original_type);
  4273. error(call, "Expected a ordered numeric type to 'min', got '%s'", type_str);
  4274. gb_string_free(type_str);
  4275. return false;
  4276. }
  4277. if (operand->mode == Addressing_Type) {
  4278. if (ce->args.count != 1) {
  4279. error(call, "If 'min' gets a type, only 1 arguments is allowed, got %td", ce->args.count);
  4280. return false;
  4281. }
  4282. if (is_type_boolean(type)) {
  4283. operand->mode = Addressing_Constant;
  4284. operand->type = original_type;
  4285. operand->value = exact_value_bool(false);
  4286. return true;
  4287. } else if (is_type_integer(type)) {
  4288. operand->mode = Addressing_Constant;
  4289. operand->type = original_type;
  4290. if (is_type_unsigned(type)) {
  4291. operand->value = exact_value_u64(0);
  4292. return true;
  4293. } else {
  4294. i64 sz = 8*type_size_of(type);
  4295. ExactValue a = exact_value_i64(1);
  4296. ExactValue b = exact_value_i64(sz-1);
  4297. ExactValue v = exact_binary_operator_value(Token_Shl, a, b);
  4298. v = exact_unary_operator_value(Token_Sub, v, cast(i32)sz, false);
  4299. operand->value = v;
  4300. return true;
  4301. }
  4302. } else if (is_type_float(type)) {
  4303. operand->mode = Addressing_Constant;
  4304. operand->type = original_type;
  4305. switch (type_size_of(type)) {
  4306. case 2:
  4307. operand->value = exact_value_float(-65504.0f);
  4308. break;
  4309. case 4:
  4310. operand->value = exact_value_float(-3.402823466e+38f);
  4311. break;
  4312. case 8:
  4313. operand->value = exact_value_float(-1.7976931348623158e+308);
  4314. break;
  4315. default:
  4316. GB_PANIC("Unhandled float type");
  4317. break;
  4318. }
  4319. return true;
  4320. } else if (is_type_enum(type)) {
  4321. operand->mode = Addressing_Constant;
  4322. operand->type = original_type;
  4323. operand->value = type->Enum.min_value;
  4324. return true;
  4325. } else if (is_type_enumerated_array(type)) {
  4326. Type *bt = base_type(type);
  4327. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4328. operand->mode = Addressing_Constant;
  4329. operand->type = bt->EnumeratedArray.index;
  4330. operand->value = bt->EnumeratedArray.min_value;
  4331. return true;
  4332. }
  4333. gbString type_str = type_to_string(original_type);
  4334. error(call, "Invalid type for 'min', got %s", type_str);
  4335. gb_string_free(type_str);
  4336. return false;
  4337. }
  4338. bool all_constant = operand->mode == Addressing_Constant;
  4339. auto operands = array_make<Operand>(heap_allocator(), 0, ce->args.count);
  4340. defer (array_free(&operands));
  4341. array_add(&operands, *operand);
  4342. for (isize i = 1; i < ce->args.count; i++) {
  4343. Ast *other_arg = ce->args[i];
  4344. Operand b = {};
  4345. check_expr(c, &b, other_arg);
  4346. if (b.mode == Addressing_Invalid) {
  4347. return false;
  4348. }
  4349. if (!is_type_ordered(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) {
  4350. gbString type_str = type_to_string(b.type);
  4351. error(call,
  4352. "Expected a ordered numeric type to 'min', got '%s'",
  4353. type_str);
  4354. gb_string_free(type_str);
  4355. return false;
  4356. }
  4357. array_add(&operands, b);
  4358. if (all_constant) {
  4359. all_constant = b.mode == Addressing_Constant;
  4360. }
  4361. }
  4362. if (all_constant) {
  4363. ExactValue value = operands[0].value;
  4364. Type *type = operands[0].type;
  4365. for (isize i = 1; i < operands.count; i++) {
  4366. Operand y = operands[i];
  4367. if (compare_exact_values(Token_Lt, value, y.value)) {
  4368. // okay
  4369. } else {
  4370. value = y.value;
  4371. type = y.type;
  4372. }
  4373. }
  4374. operand->value = value;
  4375. operand->type = type;
  4376. } else {
  4377. operand->mode = Addressing_Value;
  4378. operand->type = original_type;
  4379. for_array(i, operands) {
  4380. Operand *a = &operands[i];
  4381. for_array(j, operands) {
  4382. if (i == j) {
  4383. continue;
  4384. }
  4385. Operand *b = &operands[j];
  4386. convert_to_typed(c, a, b->type);
  4387. if (a->mode == Addressing_Invalid) {
  4388. return false;
  4389. }
  4390. convert_to_typed(c, b, a->type);
  4391. if (b->mode == Addressing_Invalid) {
  4392. return false;
  4393. }
  4394. }
  4395. }
  4396. for (isize i = 0; i < operands.count-1; i++) {
  4397. Operand *a = &operands[i];
  4398. Operand *b = &operands[i+1];
  4399. if (!are_types_identical(a->type, b->type)) {
  4400. gbString type_a = type_to_string(a->type);
  4401. gbString type_b = type_to_string(b->type);
  4402. error(a->expr,
  4403. "Mismatched types to 'min', '%s' vs '%s'",
  4404. type_a, type_b);
  4405. gb_string_free(type_b);
  4406. gb_string_free(type_a);
  4407. return false;
  4408. }
  4409. }
  4410. {
  4411. Type *bt = base_type(operands[0].type);
  4412. if (are_types_identical(bt, t_f32)) add_package_dependency(c, "runtime", "min_f32");
  4413. if (are_types_identical(bt, t_f64)) add_package_dependency(c, "runtime", "min_f64");
  4414. operand->type = operands[0].type;
  4415. }
  4416. }
  4417. break;
  4418. }
  4419. case BuiltinProc_max: {
  4420. // max :: proc($T: typeid) -> ordered
  4421. // max :: proc(a: ..ordered) -> ordered
  4422. check_multi_expr_or_type(c, operand, ce->args[0]);
  4423. Type *original_type = operand->type;
  4424. Type *type = base_type(operand->type);
  4425. if (operand->mode == Addressing_Type && is_type_enumerated_array(type)) {
  4426. // Okay
  4427. } else if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {
  4428. gbString type_str = type_to_string(original_type);
  4429. error(call, "Expected a ordered numeric type to 'max', got '%s'", type_str);
  4430. gb_string_free(type_str);
  4431. return false;
  4432. }
  4433. if (operand->mode == Addressing_Type) {
  4434. if (ce->args.count != 1) {
  4435. error(call, "If 'max' gets a type, only 1 arguments is allowed, got %td", ce->args.count);
  4436. return false;
  4437. }
  4438. if (is_type_boolean(type)) {
  4439. operand->mode = Addressing_Constant;
  4440. operand->type = original_type;
  4441. operand->value = exact_value_bool(true);
  4442. return true;
  4443. } else if (is_type_integer(type)) {
  4444. operand->mode = Addressing_Constant;
  4445. operand->type = original_type;
  4446. if (is_type_unsigned(type)) {
  4447. i64 sz = 8*type_size_of(type);
  4448. ExactValue a = exact_value_i64(1);
  4449. ExactValue b = exact_value_i64(sz);
  4450. ExactValue v = exact_binary_operator_value(Token_Shl, a, b);
  4451. v = exact_binary_operator_value(Token_Sub, v, a);
  4452. operand->value = v;
  4453. return true;
  4454. } else {
  4455. i64 sz = 8*type_size_of(type);
  4456. ExactValue a = exact_value_i64(1);
  4457. ExactValue b = exact_value_i64(sz-1);
  4458. ExactValue v = exact_binary_operator_value(Token_Shl, a, b);
  4459. v = exact_binary_operator_value(Token_Sub, v, a);
  4460. operand->value = v;
  4461. return true;
  4462. }
  4463. } else if (is_type_float(type)) {
  4464. operand->mode = Addressing_Constant;
  4465. operand->type = original_type;
  4466. switch (type_size_of(type)) {
  4467. case 2:
  4468. operand->value = exact_value_float(65504.0f);
  4469. break;
  4470. case 4:
  4471. operand->value = exact_value_float(3.402823466e+38f);
  4472. break;
  4473. case 8:
  4474. operand->value = exact_value_float(1.7976931348623158e+308);
  4475. break;
  4476. default:
  4477. GB_PANIC("Unhandled float type");
  4478. break;
  4479. }
  4480. return true;
  4481. } else if (is_type_enum(type)) {
  4482. operand->mode = Addressing_Constant;
  4483. operand->type = original_type;
  4484. operand->value = type->Enum.max_value;
  4485. return true;
  4486. } else if (is_type_enumerated_array(type)) {
  4487. Type *bt = base_type(type);
  4488. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4489. operand->mode = Addressing_Constant;
  4490. operand->type = bt->EnumeratedArray.index;
  4491. operand->value = bt->EnumeratedArray.max_value;
  4492. return true;
  4493. }
  4494. gbString type_str = type_to_string(original_type);
  4495. error(call, "Invalid type for 'max', got %s", type_str);
  4496. gb_string_free(type_str);
  4497. return false;
  4498. }
  4499. bool all_constant = operand->mode == Addressing_Constant;
  4500. auto operands = array_make<Operand>(heap_allocator(), 0, ce->args.count);
  4501. defer (array_free(&operands));
  4502. array_add(&operands, *operand);
  4503. for (isize i = 1; i < ce->args.count; i++) {
  4504. Ast *arg = ce->args[i];
  4505. Operand b = {};
  4506. check_expr(c, &b, arg);
  4507. if (b.mode == Addressing_Invalid) {
  4508. return false;
  4509. }
  4510. if (!is_type_ordered(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) {
  4511. gbString type_str = type_to_string(b.type);
  4512. error(arg,
  4513. "Expected a ordered numeric type to 'max', got '%s'",
  4514. type_str);
  4515. gb_string_free(type_str);
  4516. return false;
  4517. }
  4518. array_add(&operands, b);
  4519. if (all_constant) {
  4520. all_constant = b.mode == Addressing_Constant;
  4521. }
  4522. }
  4523. if (all_constant) {
  4524. ExactValue value = operands[0].value;
  4525. Type *type = operands[0].type;
  4526. for (isize i = 1; i < operands.count; i++) {
  4527. Operand y = operands[i];
  4528. if (compare_exact_values(Token_Gt, value, y.value)) {
  4529. // okay
  4530. } else {
  4531. type = y.type;
  4532. value = y.value;
  4533. }
  4534. }
  4535. operand->value = value;
  4536. operand->type = type;
  4537. } else {
  4538. operand->mode = Addressing_Value;
  4539. operand->type = original_type;
  4540. for_array(i, operands) {
  4541. Operand *a = &operands[i];
  4542. for_array(j, operands) {
  4543. if (i == j) {
  4544. continue;
  4545. }
  4546. Operand *b = &operands[j];
  4547. convert_to_typed(c, a, b->type);
  4548. if (a->mode == Addressing_Invalid) {
  4549. return false;
  4550. }
  4551. convert_to_typed(c, b, a->type);
  4552. if (b->mode == Addressing_Invalid) {
  4553. return false;
  4554. }
  4555. }
  4556. }
  4557. for (isize i = 0; i < operands.count-1; i++) {
  4558. Operand *a = &operands[i];
  4559. Operand *b = &operands[i+1];
  4560. if (!are_types_identical(a->type, b->type)) {
  4561. gbString type_a = type_to_string(a->type);
  4562. gbString type_b = type_to_string(b->type);
  4563. error(a->expr,
  4564. "Mismatched types to 'max', '%s' vs '%s'",
  4565. type_a, type_b);
  4566. gb_string_free(type_b);
  4567. gb_string_free(type_a);
  4568. return false;
  4569. }
  4570. }
  4571. {
  4572. Type *bt = base_type(operands[0].type);
  4573. if (are_types_identical(bt, t_f32)) add_package_dependency(c, "runtime", "max_f32");
  4574. if (are_types_identical(bt, t_f64)) add_package_dependency(c, "runtime", "max_f64");
  4575. operand->type = operands[0].type;
  4576. }
  4577. }
  4578. break;
  4579. }
  4580. case BuiltinProc_abs: {
  4581. // abs :: proc(n: numeric) -> numeric
  4582. if (!(is_type_numeric(operand->type) && !is_type_array(operand->type))) {
  4583. gbString type_str = type_to_string(operand->type);
  4584. error(call, "Expected a numeric type to 'abs', got '%s'", type_str);
  4585. gb_string_free(type_str);
  4586. return false;
  4587. }
  4588. if (operand->mode == Addressing_Constant) {
  4589. switch (operand->value.kind) {
  4590. case ExactValue_Integer:
  4591. operand->value.value_integer.neg = false;
  4592. break;
  4593. case ExactValue_Float:
  4594. operand->value.value_float = gb_abs(operand->value.value_float);
  4595. break;
  4596. case ExactValue_Complex: {
  4597. f64 r = operand->value.value_complex->real;
  4598. f64 i = operand->value.value_complex->imag;
  4599. operand->value = exact_value_float(gb_sqrt(r*r + i*i));
  4600. break;
  4601. }
  4602. default:
  4603. GB_PANIC("Invalid numeric constant");
  4604. break;
  4605. }
  4606. } else {
  4607. operand->mode = Addressing_Value;
  4608. {
  4609. Type *bt = base_type(operand->type);
  4610. if (are_types_identical(bt, t_f32)) add_package_dependency(c, "runtime", "abs_f32");
  4611. if (are_types_identical(bt, t_f64)) add_package_dependency(c, "runtime", "abs_f64");
  4612. if (are_types_identical(bt, t_complex64)) add_package_dependency(c, "runtime", "abs_complex64");
  4613. if (are_types_identical(bt, t_complex128)) add_package_dependency(c, "runtime", "abs_complex128");
  4614. if (are_types_identical(bt, t_quaternion128)) add_package_dependency(c, "runtime", "abs_quaternion128");
  4615. if (are_types_identical(bt, t_quaternion256)) add_package_dependency(c, "runtime", "abs_quaternion256");
  4616. }
  4617. }
  4618. if (is_type_complex(operand->type)) {
  4619. operand->type = base_complex_elem_type(operand->type);
  4620. }
  4621. GB_ASSERT(!is_type_complex(operand->type));
  4622. break;
  4623. }
  4624. case BuiltinProc_clamp: {
  4625. // clamp :: proc(a, min, max: ordered) -> ordered
  4626. Type *type = operand->type;
  4627. if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {
  4628. gbString type_str = type_to_string(operand->type);
  4629. error(call, "Expected a ordered numeric or string type to 'clamp', got '%s'", type_str);
  4630. gb_string_free(type_str);
  4631. return false;
  4632. }
  4633. Ast *min_arg = ce->args[1];
  4634. Ast *max_arg = ce->args[2];
  4635. Operand x = *operand;
  4636. Operand y = {};
  4637. Operand z = {};
  4638. check_expr(c, &y, min_arg);
  4639. if (y.mode == Addressing_Invalid) {
  4640. return false;
  4641. }
  4642. if (!is_type_ordered(y.type) || !(is_type_numeric(y.type) || is_type_string(y.type))) {
  4643. gbString type_str = type_to_string(y.type);
  4644. error(call, "Expected a ordered numeric or string type to 'clamp', got '%s'", type_str);
  4645. gb_string_free(type_str);
  4646. return false;
  4647. }
  4648. check_expr(c, &z, max_arg);
  4649. if (z.mode == Addressing_Invalid) {
  4650. return false;
  4651. }
  4652. if (!is_type_ordered(z.type) || !(is_type_numeric(z.type) || is_type_string(z.type))) {
  4653. gbString type_str = type_to_string(z.type);
  4654. error(call, "Expected a ordered numeric or string type to 'clamp', got '%s'", type_str);
  4655. gb_string_free(type_str);
  4656. return false;
  4657. }
  4658. if (x.mode == Addressing_Constant &&
  4659. y.mode == Addressing_Constant &&
  4660. z.mode == Addressing_Constant) {
  4661. ExactValue a = x.value;
  4662. ExactValue b = y.value;
  4663. ExactValue c = z.value;
  4664. operand->mode = Addressing_Constant;
  4665. if (compare_exact_values(Token_Lt, a, b)) {
  4666. operand->value = b;
  4667. operand->type = y.type;
  4668. } else if (compare_exact_values(Token_Gt, a, c)) {
  4669. operand->value = c;
  4670. operand->type = z.type;
  4671. } else {
  4672. operand->value = a;
  4673. operand->type = x.type;
  4674. }
  4675. } else {
  4676. operand->mode = Addressing_Value;
  4677. operand->type = type;
  4678. Operand *ops[3] = {&x, &y, &z};
  4679. for (isize i = 0; i < 3; i++) {
  4680. Operand *a = ops[i];
  4681. for (isize j = 0; j < 3; j++) {
  4682. if (i == j) continue;
  4683. Operand *b = ops[j];
  4684. convert_to_typed(c, a, b->type);
  4685. if (a->mode == Addressing_Invalid) { return false; }
  4686. }
  4687. }
  4688. if (!are_types_identical(x.type, y.type) || !are_types_identical(x.type, z.type)) {
  4689. gbString type_x = type_to_string(x.type);
  4690. gbString type_y = type_to_string(y.type);
  4691. gbString type_z = type_to_string(z.type);
  4692. error(call,
  4693. "Mismatched types to 'clamp', '%s', '%s', '%s'",
  4694. type_x, type_y, type_z);
  4695. gb_string_free(type_z);
  4696. gb_string_free(type_y);
  4697. gb_string_free(type_x);
  4698. return false;
  4699. }
  4700. {
  4701. Type *bt = base_type(x.type);
  4702. if (are_types_identical(bt, t_f32)) {
  4703. add_package_dependency(c, "runtime", "min_f32");
  4704. add_package_dependency(c, "runtime", "max_f32");
  4705. }
  4706. if (are_types_identical(bt, t_f64)) {
  4707. add_package_dependency(c, "runtime", "min_f64");
  4708. add_package_dependency(c, "runtime", "max_f64");
  4709. }
  4710. operand->type = ops[0]->type;
  4711. }
  4712. }
  4713. break;
  4714. }
  4715. case BuiltinProc_soa_zip: {
  4716. if (!build_context.use_llvm_api) {
  4717. error(call, "'soa_zip' is not supported with this backend");
  4718. return false;
  4719. }
  4720. auto types = array_make<Type *>(temporary_allocator(), 0, ce->args.count);
  4721. auto names = array_make<String>(temporary_allocator(), 0, ce->args.count);
  4722. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  4723. bool fail = false;
  4724. for_array(i, ce->args) {
  4725. Ast *arg = ce->args[i];
  4726. bool mix = false;
  4727. if (first_is_field_value) {
  4728. mix = arg->kind != Ast_FieldValue;
  4729. } else {
  4730. mix = arg->kind == Ast_FieldValue;
  4731. }
  4732. if (mix) {
  4733. error(arg, "Mixture of 'field = value' and value elements in the procedure call 'soa_zip' is not allowed");
  4734. fail = true;
  4735. break;
  4736. }
  4737. }
  4738. StringSet name_set = {};
  4739. string_set_init(&name_set, temporary_allocator(), 2*ce->args.count);
  4740. for_array(i, ce->args) {
  4741. String name = {};
  4742. Ast *arg = ce->args[i];
  4743. if (arg->kind == Ast_FieldValue) {
  4744. Ast *ename = arg->FieldValue.field;
  4745. if (!fail && ename->kind != Ast_Ident) {
  4746. error(ename, "Expected an identifier for field argument");
  4747. } else if (ename->kind == Ast_Ident) {
  4748. name = ename->Ident.token.string;
  4749. }
  4750. arg = arg->FieldValue.value;
  4751. }
  4752. Operand op = {};
  4753. check_expr(c, &op, arg);
  4754. if (op.mode == Addressing_Invalid) {
  4755. return false;
  4756. }
  4757. Type *arg_type = base_type(op.type);
  4758. if (!is_type_slice(arg_type)) {
  4759. gbString s = type_to_string(op.type);
  4760. error(op.expr, "Indices to 'soa_zip' must be slices, got %s", s);
  4761. gb_string_free(s);
  4762. return false;
  4763. }
  4764. GB_ASSERT(arg_type->kind == Type_Slice);
  4765. if (name == "_") {
  4766. error(op.expr, "Field argument name '%.*s' is not allowed", LIT(name));
  4767. name = {};
  4768. }
  4769. if (name.len == 0) {
  4770. gbString field_name = gb_string_make(permanent_allocator(), "_");
  4771. field_name = gb_string_append_fmt(field_name, "%td", types.count);
  4772. name = make_string_c(field_name);
  4773. }
  4774. if (string_set_exists(&name_set, name)) {
  4775. error(op.expr, "Field argument name '%.*s' already exists", LIT(name));
  4776. } else {
  4777. array_add(&types, arg_type->Slice.elem);
  4778. array_add(&names, name);
  4779. string_set_add(&name_set, name);
  4780. }
  4781. }
  4782. Ast *dummy_node_struct = alloc_ast_node(nullptr, Ast_Invalid);
  4783. Ast *dummy_node_soa = alloc_ast_node(nullptr, Ast_Invalid);
  4784. Scope *s = create_scope(builtin_pkg->scope);
  4785. auto fields = array_make<Entity *>(permanent_allocator(), 0, types.count);
  4786. for_array(i, types) {
  4787. Type *type = types[i];
  4788. String name = names[i];
  4789. GB_ASSERT(name != "");
  4790. Entity *e = alloc_entity_field(s, make_token_ident(name), type, false, cast(i32)i, EntityState_Resolved);
  4791. array_add(&fields, e);
  4792. scope_insert(s, e);
  4793. }
  4794. Type *elem = nullptr;
  4795. if (type_hint != nullptr && is_type_struct(type_hint)) {
  4796. Type *soa_type = base_type(type_hint);
  4797. if (soa_type->Struct.soa_kind != StructSoa_Slice) {
  4798. goto soa_zip_end;
  4799. }
  4800. Type *soa_elem_type = soa_type->Struct.soa_elem;
  4801. Type *et = base_type(soa_elem_type);
  4802. if (et->kind != Type_Struct) {
  4803. goto soa_zip_end;
  4804. }
  4805. if (et->Struct.fields.count != fields.count) {
  4806. goto soa_zip_end;
  4807. }
  4808. if (!fail && first_is_field_value) {
  4809. for_array(i, names) {
  4810. Selection sel = lookup_field(et, names[i], false);
  4811. if (sel.entity == nullptr) {
  4812. goto soa_zip_end;
  4813. }
  4814. if (sel.index.count != 1) {
  4815. goto soa_zip_end;
  4816. }
  4817. if (!are_types_identical(sel.entity->type, types[i])) {
  4818. goto soa_zip_end;
  4819. }
  4820. }
  4821. } else {
  4822. for_array(i, et->Struct.fields) {
  4823. if (!are_types_identical(et->Struct.fields[i]->type, types[i])) {
  4824. goto soa_zip_end;
  4825. }
  4826. }
  4827. }
  4828. elem = soa_elem_type;
  4829. }
  4830. soa_zip_end:;
  4831. if (elem == nullptr) {
  4832. elem = alloc_type_struct();
  4833. elem->Struct.scope = s;
  4834. elem->Struct.fields = fields;
  4835. elem->Struct.tags = array_make<String>(permanent_allocator(), fields.count);
  4836. elem->Struct.node = dummy_node_struct;
  4837. type_set_offsets(elem);
  4838. }
  4839. Type *soa_type = make_soa_struct_slice(c, dummy_node_soa, nullptr, elem);
  4840. type_set_offsets(soa_type);
  4841. operand->type = soa_type;
  4842. operand->mode = Addressing_Value;
  4843. break;
  4844. }
  4845. case BuiltinProc_soa_unzip: {
  4846. if (!build_context.use_llvm_api) {
  4847. error(call, "'soa_unzip' is not supported with this backend");
  4848. return false;
  4849. }
  4850. Operand x = {};
  4851. check_expr(c, &x, ce->args[0]);
  4852. if (x.mode == Addressing_Invalid) {
  4853. return false;
  4854. }
  4855. if (!is_operand_value(x)) {
  4856. error(call, "'soa_unzip' expects an #soa slice");
  4857. return false;
  4858. }
  4859. Type *t = base_type(x.type);
  4860. if (!is_type_soa_struct(t) || t->Struct.soa_kind != StructSoa_Slice) {
  4861. gbString s = type_to_string(x.type);
  4862. error(call, "'soa_unzip' expects an #soa slice, got %s", s);
  4863. gb_string_free(s);
  4864. return false;
  4865. }
  4866. auto types = slice_make<Type *>(permanent_allocator(), t->Struct.fields.count-1);
  4867. for_array(i, types) {
  4868. Entity *f = t->Struct.fields[i];
  4869. GB_ASSERT(f->type->kind == Type_Pointer);
  4870. types[i] = alloc_type_slice(f->type->Pointer.elem);
  4871. }
  4872. operand->type = alloc_type_tuple_from_field_types(types.data, types.count, false, false);
  4873. operand->mode = Addressing_Value;
  4874. break;
  4875. }
  4876. case BuiltinProc_simd_vector: {
  4877. Operand x = {};
  4878. Operand y = {};
  4879. x = *operand;
  4880. if (!is_type_integer(x.type) || x.mode != Addressing_Constant) {
  4881. error(call, "Expected a constant integer for 'intrinsics.simd_vector'");
  4882. operand->mode = Addressing_Type;
  4883. operand->type = t_invalid;
  4884. return false;
  4885. }
  4886. if (x.value.value_integer.neg) {
  4887. error(call, "Negative vector element length");
  4888. operand->mode = Addressing_Type;
  4889. operand->type = t_invalid;
  4890. return false;
  4891. }
  4892. i64 count = big_int_to_i64(&x.value.value_integer);
  4893. check_expr_or_type(c, &y, ce->args[1]);
  4894. if (y.mode != Addressing_Type) {
  4895. error(call, "Expected a type 'intrinsics.simd_vector'");
  4896. operand->mode = Addressing_Type;
  4897. operand->type = t_invalid;
  4898. return false;
  4899. }
  4900. Type *elem = y.type;
  4901. if (!is_type_valid_vector_elem(elem)) {
  4902. gbString str = type_to_string(elem);
  4903. error(call, "Invalid element type for 'intrinsics.simd_vector', expected an integer or float with no specific endianness, got '%s'", str);
  4904. gb_string_free(str);
  4905. operand->mode = Addressing_Type;
  4906. operand->type = t_invalid;
  4907. return false;
  4908. }
  4909. operand->mode = Addressing_Type;
  4910. operand->type = alloc_type_simd_vector(count, elem);
  4911. break;
  4912. }
  4913. case BuiltinProc_soa_struct: {
  4914. Operand x = {};
  4915. Operand y = {};
  4916. x = *operand;
  4917. if (!is_type_integer(x.type) || x.mode != Addressing_Constant) {
  4918. error(call, "Expected a constant integer for 'intrinsics.soa_struct'");
  4919. operand->mode = Addressing_Type;
  4920. operand->type = t_invalid;
  4921. return false;
  4922. }
  4923. if (x.value.value_integer.neg) {
  4924. error(call, "Negative array element length");
  4925. operand->mode = Addressing_Type;
  4926. operand->type = t_invalid;
  4927. return false;
  4928. }
  4929. i64 count = big_int_to_i64(&x.value.value_integer);
  4930. check_expr_or_type(c, &y, ce->args[1]);
  4931. if (y.mode != Addressing_Type) {
  4932. error(call, "Expected a type 'intrinsics.soa_struct'");
  4933. operand->mode = Addressing_Type;
  4934. operand->type = t_invalid;
  4935. return false;
  4936. }
  4937. Type *elem = y.type;
  4938. Type *bt_elem = base_type(elem);
  4939. if (!is_type_struct(elem) && !is_type_raw_union(elem) && !(is_type_array(elem) && bt_elem->Array.count <= 4)) {
  4940. gbString str = type_to_string(elem);
  4941. error(call, "Invalid type for 'intrinsics.soa_struct', expected a struct or array of length 4 or below, got '%s'", str);
  4942. gb_string_free(str);
  4943. operand->mode = Addressing_Type;
  4944. operand->type = t_invalid;
  4945. return false;
  4946. }
  4947. operand->mode = Addressing_Type;
  4948. Type *soa_struct = nullptr;
  4949. Scope *scope = nullptr;
  4950. if (is_type_array(elem)) {
  4951. Type *old_array = base_type(elem);
  4952. soa_struct = alloc_type_struct();
  4953. soa_struct->Struct.fields = array_make<Entity *>(heap_allocator(), old_array->Array.count);
  4954. soa_struct->Struct.tags = array_make<String>(heap_allocator(), old_array->Array.count);
  4955. soa_struct->Struct.node = operand->expr;
  4956. soa_struct->Struct.soa_kind = StructSoa_Fixed;
  4957. soa_struct->Struct.soa_elem = elem;
  4958. soa_struct->Struct.soa_count = count;
  4959. scope = create_scope(c->scope);
  4960. soa_struct->Struct.scope = scope;
  4961. String params_xyzw[4] = {
  4962. str_lit("x"),
  4963. str_lit("y"),
  4964. str_lit("z"),
  4965. str_lit("w")
  4966. };
  4967. for (i64 i = 0; i < old_array->Array.count; i++) {
  4968. Type *array_type = alloc_type_array(old_array->Array.elem, count);
  4969. Token token = {};
  4970. token.string = params_xyzw[i];
  4971. Entity *new_field = alloc_entity_field(scope, token, array_type, false, cast(i32)i);
  4972. soa_struct->Struct.fields[i] = new_field;
  4973. add_entity(c->checker, scope, nullptr, new_field);
  4974. add_entity_use(c, nullptr, new_field);
  4975. }
  4976. } else {
  4977. GB_ASSERT(is_type_struct(elem));
  4978. Type *old_struct = base_type(elem);
  4979. soa_struct = alloc_type_struct();
  4980. soa_struct->Struct.fields = array_make<Entity *>(heap_allocator(), old_struct->Struct.fields.count);
  4981. soa_struct->Struct.tags = array_make<String>(heap_allocator(), old_struct->Struct.tags.count);
  4982. soa_struct->Struct.node = operand->expr;
  4983. soa_struct->Struct.soa_kind = StructSoa_Fixed;
  4984. soa_struct->Struct.soa_elem = elem;
  4985. soa_struct->Struct.soa_count = count;
  4986. scope = create_scope(old_struct->Struct.scope->parent);
  4987. soa_struct->Struct.scope = scope;
  4988. for_array(i, old_struct->Struct.fields) {
  4989. Entity *old_field = old_struct->Struct.fields[i];
  4990. if (old_field->kind == Entity_Variable) {
  4991. Type *array_type = alloc_type_array(old_field->type, count);
  4992. Entity *new_field = alloc_entity_field(scope, old_field->token, array_type, false, old_field->Variable.field_src_index);
  4993. soa_struct->Struct.fields[i] = new_field;
  4994. add_entity(c->checker, scope, nullptr, new_field);
  4995. } else {
  4996. soa_struct->Struct.fields[i] = old_field;
  4997. }
  4998. soa_struct->Struct.tags[i] = old_struct->Struct.tags[i];
  4999. }
  5000. }
  5001. Token token = {};
  5002. token.string = str_lit("Base_Type");
  5003. Entity *base_type_entity = alloc_entity_type_name(scope, token, elem, EntityState_Resolved);
  5004. add_entity(c->checker, scope, nullptr, base_type_entity);
  5005. add_type_info_type(c, soa_struct);
  5006. operand->type = soa_struct;
  5007. break;
  5008. }
  5009. case BuiltinProc_alloca:
  5010. {
  5011. Operand sz = {};
  5012. Operand al = {};
  5013. check_expr(c, &sz, ce->args[0]);
  5014. if (sz.mode == Addressing_Invalid) {
  5015. return false;
  5016. }
  5017. check_expr(c, &al, ce->args[1]);
  5018. if (al.mode == Addressing_Invalid) {
  5019. return false;
  5020. }
  5021. convert_to_typed(c, &sz, t_int); if (sz.mode == Addressing_Invalid) return false;
  5022. convert_to_typed(c, &al, t_int); if (al.mode == Addressing_Invalid) return false;
  5023. if (!is_type_integer(sz.type) || !is_type_integer(al.type)) {
  5024. error(operand->expr, "Both parameters to '%.*s' must integers", LIT(builtin_name));
  5025. return false;
  5026. }
  5027. if (sz.mode == Addressing_Constant) {
  5028. i64 i_sz = exact_value_to_i64(sz.value);
  5029. if (i_sz < 0) {
  5030. error(sz.expr, "Size parameter to '%.*s' must be non-negative, got %lld", LIT(builtin_name), cast(long long)i_sz);
  5031. return false;
  5032. }
  5033. }
  5034. if (al.mode == Addressing_Constant) {
  5035. i64 i_al = exact_value_to_i64(al.value);
  5036. if (i_al < 0) {
  5037. error(al.expr, "Alignment parameter to '%.*s' must be non-negative, got %lld", LIT(builtin_name), cast(long long)i_al);
  5038. return false;
  5039. }
  5040. if (i_al > 1<<29) {
  5041. error(al.expr, "Alignment parameter to '%.*s' must not exceed '1<<29', got %lld", LIT(builtin_name), cast(long long)i_al);
  5042. return false;
  5043. }
  5044. if (!gb_is_power_of_two(cast(isize)i_al) && i_al != 0) {
  5045. 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);
  5046. return false;
  5047. }
  5048. } else {
  5049. error(al.expr, "Alignment parameter to '%.*s' must be constant", LIT(builtin_name));
  5050. }
  5051. operand->type = t_u8_ptr;
  5052. operand->mode = Addressing_Value;
  5053. break;
  5054. }
  5055. case BuiltinProc_cpu_relax:
  5056. operand->mode = Addressing_NoValue;
  5057. break;
  5058. case BuiltinProc_atomic_fence:
  5059. case BuiltinProc_atomic_fence_acq:
  5060. case BuiltinProc_atomic_fence_rel:
  5061. case BuiltinProc_atomic_fence_acqrel:
  5062. operand->mode = Addressing_NoValue;
  5063. break;
  5064. case BuiltinProc_volatile_store:
  5065. /*fallthrough*/
  5066. case BuiltinProc_atomic_store:
  5067. case BuiltinProc_atomic_store_rel:
  5068. case BuiltinProc_atomic_store_relaxed:
  5069. case BuiltinProc_atomic_store_unordered:
  5070. {
  5071. Type *elem = nullptr;
  5072. if (!is_type_normal_pointer(operand->type, &elem)) {
  5073. error(operand->expr, "Expected a pointer for '%.*s'", LIT(builtin_name));
  5074. return false;
  5075. }
  5076. Operand x = {};
  5077. check_expr_with_type_hint(c, &x, ce->args[1], elem);
  5078. check_assignment(c, &x, elem, builtin_name);
  5079. operand->type = nullptr;
  5080. operand->mode = Addressing_NoValue;
  5081. break;
  5082. }
  5083. case BuiltinProc_volatile_load:
  5084. /*fallthrough*/
  5085. case BuiltinProc_atomic_load:
  5086. case BuiltinProc_atomic_load_acq:
  5087. case BuiltinProc_atomic_load_relaxed:
  5088. case BuiltinProc_atomic_load_unordered:
  5089. {
  5090. Type *elem = nullptr;
  5091. if (!is_type_normal_pointer(operand->type, &elem)) {
  5092. error(operand->expr, "Expected a pointer for '%.*s'", LIT(builtin_name));
  5093. return false;
  5094. }
  5095. operand->type = elem;
  5096. operand->mode = Addressing_Value;
  5097. break;
  5098. }
  5099. case BuiltinProc_atomic_add:
  5100. case BuiltinProc_atomic_add_acq:
  5101. case BuiltinProc_atomic_add_rel:
  5102. case BuiltinProc_atomic_add_acqrel:
  5103. case BuiltinProc_atomic_add_relaxed:
  5104. case BuiltinProc_atomic_sub:
  5105. case BuiltinProc_atomic_sub_acq:
  5106. case BuiltinProc_atomic_sub_rel:
  5107. case BuiltinProc_atomic_sub_acqrel:
  5108. case BuiltinProc_atomic_sub_relaxed:
  5109. case BuiltinProc_atomic_and:
  5110. case BuiltinProc_atomic_and_acq:
  5111. case BuiltinProc_atomic_and_rel:
  5112. case BuiltinProc_atomic_and_acqrel:
  5113. case BuiltinProc_atomic_and_relaxed:
  5114. case BuiltinProc_atomic_nand:
  5115. case BuiltinProc_atomic_nand_acq:
  5116. case BuiltinProc_atomic_nand_rel:
  5117. case BuiltinProc_atomic_nand_acqrel:
  5118. case BuiltinProc_atomic_nand_relaxed:
  5119. case BuiltinProc_atomic_or:
  5120. case BuiltinProc_atomic_or_acq:
  5121. case BuiltinProc_atomic_or_rel:
  5122. case BuiltinProc_atomic_or_acqrel:
  5123. case BuiltinProc_atomic_or_relaxed:
  5124. case BuiltinProc_atomic_xor:
  5125. case BuiltinProc_atomic_xor_acq:
  5126. case BuiltinProc_atomic_xor_rel:
  5127. case BuiltinProc_atomic_xor_acqrel:
  5128. case BuiltinProc_atomic_xor_relaxed:
  5129. case BuiltinProc_atomic_xchg:
  5130. case BuiltinProc_atomic_xchg_acq:
  5131. case BuiltinProc_atomic_xchg_rel:
  5132. case BuiltinProc_atomic_xchg_acqrel:
  5133. case BuiltinProc_atomic_xchg_relaxed:
  5134. {
  5135. Type *elem = nullptr;
  5136. if (!is_type_normal_pointer(operand->type, &elem)) {
  5137. error(operand->expr, "Expected a pointer for '%.*s'", LIT(builtin_name));
  5138. return false;
  5139. }
  5140. Operand x = {};
  5141. check_expr_with_type_hint(c, &x, ce->args[1], elem);
  5142. check_assignment(c, &x, elem, builtin_name);
  5143. operand->type = elem;
  5144. operand->mode = Addressing_Value;
  5145. break;
  5146. }
  5147. case BuiltinProc_atomic_cxchg:
  5148. case BuiltinProc_atomic_cxchg_acq:
  5149. case BuiltinProc_atomic_cxchg_rel:
  5150. case BuiltinProc_atomic_cxchg_acqrel:
  5151. case BuiltinProc_atomic_cxchg_relaxed:
  5152. case BuiltinProc_atomic_cxchg_failrelaxed:
  5153. case BuiltinProc_atomic_cxchg_failacq:
  5154. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  5155. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  5156. case BuiltinProc_atomic_cxchgweak:
  5157. case BuiltinProc_atomic_cxchgweak_acq:
  5158. case BuiltinProc_atomic_cxchgweak_rel:
  5159. case BuiltinProc_atomic_cxchgweak_acqrel:
  5160. case BuiltinProc_atomic_cxchgweak_relaxed:
  5161. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  5162. case BuiltinProc_atomic_cxchgweak_failacq:
  5163. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  5164. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed:
  5165. {
  5166. Type *elem = nullptr;
  5167. if (!is_type_normal_pointer(operand->type, &elem)) {
  5168. error(operand->expr, "Expected a pointer for '%.*s'", LIT(builtin_name));
  5169. return false;
  5170. }
  5171. Operand x = {};
  5172. Operand y = {};
  5173. check_expr_with_type_hint(c, &x, ce->args[1], elem);
  5174. check_expr_with_type_hint(c, &y, ce->args[2], elem);
  5175. check_assignment(c, &x, elem, builtin_name);
  5176. check_assignment(c, &y, elem, builtin_name);
  5177. operand->mode = Addressing_Value;
  5178. operand->type = make_optional_ok_type(elem, /*typed*/false);
  5179. break;
  5180. }
  5181. break;
  5182. case BuiltinProc_fixed_point_mul:
  5183. case BuiltinProc_fixed_point_div:
  5184. case BuiltinProc_fixed_point_mul_sat:
  5185. case BuiltinProc_fixed_point_div_sat:
  5186. {
  5187. if (!build_context.use_llvm_api) {
  5188. error(ce->args[0], "%.*s is not supported on this backend", LIT(builtin_procs[id].name));
  5189. return false;
  5190. }
  5191. Operand x = {};
  5192. Operand y = {};
  5193. Operand z = {};
  5194. check_expr(c, &x, ce->args[0]);
  5195. if (x.mode == Addressing_Invalid) {
  5196. return false;
  5197. }
  5198. check_expr(c, &y, ce->args[1]);
  5199. if (y.mode == Addressing_Invalid) {
  5200. return false;
  5201. }
  5202. convert_to_typed(c, &x, y.type);
  5203. if (x.mode == Addressing_Invalid) {
  5204. return false;
  5205. }
  5206. convert_to_typed(c, &y, x.type);
  5207. if (x.mode == Addressing_Invalid) {
  5208. return false;
  5209. }
  5210. if (!are_types_identical(x.type, y.type)) {
  5211. gbString xts = type_to_string(x.type);
  5212. gbString yts = type_to_string(y.type);
  5213. error(x.expr, "Mismatched types for %.*s, %s vs %s", LIT(builtin_procs[id].name), xts, yts);
  5214. gb_string_free(yts);
  5215. gb_string_free(xts);
  5216. return false;
  5217. }
  5218. if (!is_type_integer(x.type) || is_type_untyped(x.type)) {
  5219. gbString xts = type_to_string(x.type);
  5220. error(x.expr, "Expected an integer type for %.*s, got %s", LIT(builtin_procs[id].name), xts);
  5221. gb_string_free(xts);
  5222. return false;
  5223. }
  5224. check_expr(c, &z, ce->args[2]);
  5225. if (z.mode == Addressing_Invalid) {
  5226. return false;
  5227. }
  5228. if (z.mode != Addressing_Constant || !is_type_integer(z.type)) {
  5229. error(z.expr, "Expected a constant integer for the scale in %.*s", LIT(builtin_procs[id].name));
  5230. return false;
  5231. }
  5232. i64 n = exact_value_to_i64(z.value);
  5233. if (n <= 0) {
  5234. error(z.expr, "Scale parameter in %.*s must be positive, got %lld", LIT(builtin_procs[id].name), n);
  5235. return false;
  5236. }
  5237. i64 sz = 8*type_size_of(x.type);
  5238. if (n > sz) {
  5239. error(z.expr, "Scale parameter in %.*s is larger than the base integer bit width, got %lld, expected a maximum of %lld", LIT(builtin_procs[id].name), n, sz);
  5240. return false;
  5241. }
  5242. operand->type = x.type;
  5243. operand->mode = Addressing_Value;
  5244. }
  5245. break;
  5246. case BuiltinProc_type_base_type:
  5247. if (operand->mode != Addressing_Type) {
  5248. error(operand->expr, "Expected a type for '%.*s'", LIT(builtin_name));
  5249. } else {
  5250. operand->type = base_type(operand->type);
  5251. }
  5252. operand->mode = Addressing_Type;
  5253. break;
  5254. case BuiltinProc_type_core_type:
  5255. if (operand->mode != Addressing_Type) {
  5256. error(operand->expr, "Expected a type for '%.*s'", LIT(builtin_name));
  5257. } else {
  5258. operand->type = core_type(operand->type);
  5259. }
  5260. operand->mode = Addressing_Type;
  5261. break;
  5262. case BuiltinProc_type_elem_type:
  5263. if (operand->mode != Addressing_Type) {
  5264. error(operand->expr, "Expected a type for '%.*s'", LIT(builtin_name));
  5265. } else {
  5266. Type *bt = base_type(operand->type);
  5267. switch (bt->kind) {
  5268. case Type_Basic:
  5269. switch (bt->Basic.kind) {
  5270. case Basic_complex64: operand->type = t_f32; break;
  5271. case Basic_complex128: operand->type = t_f64; break;
  5272. case Basic_quaternion128: operand->type = t_f32; break;
  5273. case Basic_quaternion256: operand->type = t_f64; break;
  5274. }
  5275. break;
  5276. case Type_Pointer: operand->type = bt->Pointer.elem; break;
  5277. case Type_Array: operand->type = bt->Array.elem; break;
  5278. case Type_EnumeratedArray: operand->type = bt->EnumeratedArray.elem; break;
  5279. case Type_Slice: operand->type = bt->Slice.elem; break;
  5280. case Type_DynamicArray: operand->type = bt->DynamicArray.elem; break;
  5281. }
  5282. }
  5283. operand->mode = Addressing_Type;
  5284. break;
  5285. case BuiltinProc_type_is_boolean:
  5286. case BuiltinProc_type_is_integer:
  5287. case BuiltinProc_type_is_rune:
  5288. case BuiltinProc_type_is_float:
  5289. case BuiltinProc_type_is_complex:
  5290. case BuiltinProc_type_is_quaternion:
  5291. case BuiltinProc_type_is_string:
  5292. case BuiltinProc_type_is_typeid:
  5293. case BuiltinProc_type_is_any:
  5294. case BuiltinProc_type_is_endian_little:
  5295. case BuiltinProc_type_is_endian_big:
  5296. case BuiltinProc_type_is_unsigned:
  5297. case BuiltinProc_type_is_numeric:
  5298. case BuiltinProc_type_is_ordered:
  5299. case BuiltinProc_type_is_ordered_numeric:
  5300. case BuiltinProc_type_is_indexable:
  5301. case BuiltinProc_type_is_sliceable:
  5302. case BuiltinProc_type_is_comparable:
  5303. case BuiltinProc_type_is_simple_compare:
  5304. case BuiltinProc_type_is_dereferenceable:
  5305. case BuiltinProc_type_is_valid_map_key:
  5306. case BuiltinProc_type_is_named:
  5307. case BuiltinProc_type_is_pointer:
  5308. case BuiltinProc_type_is_array:
  5309. case BuiltinProc_type_is_slice:
  5310. case BuiltinProc_type_is_dynamic_array:
  5311. case BuiltinProc_type_is_map:
  5312. case BuiltinProc_type_is_struct:
  5313. case BuiltinProc_type_is_union:
  5314. case BuiltinProc_type_is_enum:
  5315. case BuiltinProc_type_is_proc:
  5316. case BuiltinProc_type_is_bit_field:
  5317. case BuiltinProc_type_is_bit_field_value:
  5318. case BuiltinProc_type_is_bit_set:
  5319. case BuiltinProc_type_is_simd_vector:
  5320. case BuiltinProc_type_is_specialized_polymorphic_record:
  5321. case BuiltinProc_type_is_unspecialized_polymorphic_record:
  5322. case BuiltinProc_type_has_nil:
  5323. GB_ASSERT(BuiltinProc__type_simple_boolean_begin < id && id < BuiltinProc__type_simple_boolean_end);
  5324. operand->value = exact_value_bool(false);
  5325. if (operand->mode != Addressing_Type) {
  5326. gbString str = expr_to_string(ce->args[0]);
  5327. error(operand->expr, "Expected a type for '%.*s', got '%s'", LIT(builtin_name), str);
  5328. gb_string_free(str);
  5329. } else {
  5330. i32 i = id - cast(i32)BuiltinProc__type_simple_boolean_begin;
  5331. auto procedure = builtin_type_is_procs[i];
  5332. GB_ASSERT_MSG(procedure != nullptr, "%.*s", LIT(builtin_name));
  5333. bool ok = procedure(operand->type);
  5334. operand->value = exact_value_bool(ok);
  5335. }
  5336. operand->mode = Addressing_Constant;
  5337. operand->type = t_untyped_bool;
  5338. break;
  5339. case BuiltinProc_type_has_field:
  5340. {
  5341. Operand op = {};
  5342. Type *bt = check_type(c, ce->args[0]);
  5343. Type *type = base_type(bt);
  5344. if (type == nullptr || type == t_invalid) {
  5345. error(ce->args[0], "Expected a type for '%.*s'", LIT(builtin_name));
  5346. return false;
  5347. }
  5348. Operand x = {};
  5349. check_expr(c, &x, ce->args[1]);
  5350. if (!is_type_string(x.type) || x.mode != Addressing_Constant || x.value.kind != ExactValue_String) {
  5351. error(ce->args[1], "Expected a const string for field argument");
  5352. return false;
  5353. }
  5354. String field_name = x.value.value_string;
  5355. Selection sel = lookup_field(type, field_name, false);
  5356. operand->mode = Addressing_Constant;
  5357. operand->value = exact_value_bool(sel.index.count != 0);
  5358. operand->type = t_untyped_bool;
  5359. break;
  5360. }
  5361. break;
  5362. case BuiltinProc_type_is_specialization_of:
  5363. {
  5364. if (operand->mode != Addressing_Type) {
  5365. error(operand->expr, "Expected a type for '%.*s'", LIT(builtin_name));
  5366. operand->mode = Addressing_Invalid;
  5367. operand->type = t_invalid;
  5368. return false;
  5369. }
  5370. Type *t = operand->type;
  5371. Type *s = nullptr;
  5372. bool prev_ips = c->in_polymorphic_specialization;
  5373. c->in_polymorphic_specialization = true;
  5374. s = check_type(c, ce->args[1]);
  5375. c->in_polymorphic_specialization = prev_ips;
  5376. if (s == t_invalid) {
  5377. error(ce->args[1], "Invalid specialization type for '%.*s'", LIT(builtin_name));
  5378. operand->mode = Addressing_Invalid;
  5379. operand->type = t_invalid;
  5380. return false;
  5381. }
  5382. operand->mode = Addressing_Constant;
  5383. operand->type = t_untyped_bool;
  5384. operand->value = exact_value_bool(check_type_specialization_to(c, s, t, false, false));
  5385. }
  5386. break;
  5387. case BuiltinProc_type_struct_field_count:
  5388. operand->value = exact_value_i64(0);
  5389. if (operand->mode != Addressing_Type) {
  5390. error(operand->expr, "Expected a struct type for '%.*s'", LIT(builtin_name));
  5391. } else if (!is_type_struct(operand->type)) {
  5392. error(operand->expr, "Expected a struct type for '%.*s'", LIT(builtin_name));
  5393. } else {
  5394. Type *bt = base_type(operand->type);
  5395. operand->value = exact_value_i64(bt->Struct.fields.count);
  5396. }
  5397. operand->mode = Addressing_Constant;
  5398. operand->type = t_untyped_integer;
  5399. break;
  5400. case BuiltinProc_type_proc_parameter_count:
  5401. operand->value = exact_value_i64(0);
  5402. if (operand->mode != Addressing_Type) {
  5403. error(operand->expr, "Expected a procedure type for '%.*s'", LIT(builtin_name));
  5404. } else if (!is_type_proc(operand->type)) {
  5405. error(operand->expr, "Expected a procedure type for '%.*s'", LIT(builtin_name));
  5406. } else {
  5407. Type *bt = base_type(operand->type);
  5408. operand->value = exact_value_i64(bt->Proc.param_count);
  5409. }
  5410. operand->mode = Addressing_Constant;
  5411. operand->type = t_untyped_integer;
  5412. break;
  5413. case BuiltinProc_type_proc_return_count:
  5414. operand->value = exact_value_i64(0);
  5415. if (operand->mode != Addressing_Type) {
  5416. error(operand->expr, "Expected a procedure type for '%.*s'", LIT(builtin_name));
  5417. } else if (!is_type_proc(operand->type)) {
  5418. error(operand->expr, "Expected a procedure type for '%.*s'", LIT(builtin_name));
  5419. } else {
  5420. Type *bt = base_type(operand->type);
  5421. operand->value = exact_value_i64(bt->Proc.result_count);
  5422. }
  5423. operand->mode = Addressing_Constant;
  5424. operand->type = t_untyped_integer;
  5425. break;
  5426. case BuiltinProc_type_proc_parameter_type:
  5427. if (operand->mode != Addressing_Type || !is_type_proc(operand->type)) {
  5428. error(operand->expr, "Expected a procedure type for '%.*s'", LIT(builtin_name));
  5429. return false;
  5430. } else {
  5431. if (is_type_polymorphic(operand->type)) {
  5432. error(operand->expr, "Expected a non-polymorphic procedure type for '%.*s'", LIT(builtin_name));
  5433. return false;
  5434. }
  5435. Operand op = {};
  5436. check_expr(c, &op, ce->args[1]);
  5437. if (op.mode != Addressing_Constant && !is_type_integer(op.type)) {
  5438. error(op.expr, "Expected a constant integer for the index of procedure parameter value");
  5439. return false;
  5440. }
  5441. i64 index = exact_value_to_i64(op.value);
  5442. if (index < 0) {
  5443. error(op.expr, "Expected a non-negative integer for the index of procedure parameter value, got %lld", cast(long long)index);
  5444. return false;
  5445. }
  5446. Entity *param = nullptr;
  5447. i64 count = 0;
  5448. Type *bt = base_type(operand->type);
  5449. if (bt->kind == Type_Proc) {
  5450. count = bt->Proc.param_count;
  5451. if (index < count) {
  5452. param = bt->Proc.params->Tuple.variables[index];
  5453. }
  5454. }
  5455. if (index >= count) {
  5456. error(op.expr, "Index of procedure parameter value out of bounds, expected 0..<%lld, got %lld", cast(long long)count, cast(long long)index);
  5457. return false;
  5458. }
  5459. GB_ASSERT(param != nullptr);
  5460. switch (param->kind) {
  5461. case Entity_Constant:
  5462. operand->mode = Addressing_Constant;
  5463. operand->type = param->type;
  5464. operand->value = param->Constant.value;
  5465. break;
  5466. case Entity_TypeName:
  5467. case Entity_Variable:
  5468. operand->mode = Addressing_Type;
  5469. operand->type = param->type;
  5470. break;
  5471. default:
  5472. GB_PANIC("Unhandled procedure entity type %d", param->kind);
  5473. break;
  5474. }
  5475. }
  5476. break;
  5477. case BuiltinProc_type_proc_return_type:
  5478. if (operand->mode != Addressing_Type || !is_type_proc(operand->type)) {
  5479. error(operand->expr, "Expected a procedure type for '%.*s'", LIT(builtin_name));
  5480. return false;
  5481. } else {
  5482. if (is_type_polymorphic(operand->type)) {
  5483. error(operand->expr, "Expected a non-polymorphic procedure type for '%.*s'", LIT(builtin_name));
  5484. return false;
  5485. }
  5486. Operand op = {};
  5487. check_expr(c, &op, ce->args[1]);
  5488. if (op.mode != Addressing_Constant && !is_type_integer(op.type)) {
  5489. error(op.expr, "Expected a constant integer for the index of procedure parameter value");
  5490. return false;
  5491. }
  5492. i64 index = exact_value_to_i64(op.value);
  5493. if (index < 0) {
  5494. error(op.expr, "Expected a non-negative integer for the index of procedure parameter value, got %lld", cast(long long)index);
  5495. return false;
  5496. }
  5497. Entity *param = nullptr;
  5498. i64 count = 0;
  5499. Type *bt = base_type(operand->type);
  5500. if (bt->kind == Type_Proc) {
  5501. count = bt->Proc.result_count;
  5502. if (index < count) {
  5503. param = bt->Proc.results->Tuple.variables[index];
  5504. }
  5505. }
  5506. if (index >= count) {
  5507. error(op.expr, "Index of procedure parameter value out of bounds, expected 0..<%lld, got %lld", cast(long long)count, cast(long long)index);
  5508. return false;
  5509. }
  5510. GB_ASSERT(param != nullptr);
  5511. switch (param->kind) {
  5512. case Entity_Constant:
  5513. operand->mode = Addressing_Constant;
  5514. operand->type = param->type;
  5515. operand->value = param->Constant.value;
  5516. break;
  5517. case Entity_TypeName:
  5518. case Entity_Variable:
  5519. operand->mode = Addressing_Type;
  5520. operand->type = param->type;
  5521. break;
  5522. default:
  5523. GB_PANIC("Unhandled procedure entity type %d", param->kind);
  5524. break;
  5525. }
  5526. }
  5527. break;
  5528. case BuiltinProc_type_polymorphic_record_parameter_count:
  5529. operand->value = exact_value_i64(0);
  5530. if (operand->mode != Addressing_Type) {
  5531. error(operand->expr, "Expected a record type for '%.*s'", LIT(builtin_name));
  5532. } else {
  5533. Type *bt = base_type(operand->type);
  5534. if (bt->kind == Type_Struct) {
  5535. if (bt->Struct.polymorphic_params != nullptr) {
  5536. operand->value = exact_value_i64(bt->Struct.polymorphic_params->Tuple.variables.count);
  5537. }
  5538. } else if (bt->kind == Type_Union) {
  5539. if (bt->Union.polymorphic_params != nullptr) {
  5540. operand->value = exact_value_i64(bt->Union.polymorphic_params->Tuple.variables.count);
  5541. }
  5542. } else {
  5543. error(operand->expr, "Expected a record type for '%.*s'", LIT(builtin_name));
  5544. }
  5545. }
  5546. operand->mode = Addressing_Constant;
  5547. operand->type = t_untyped_integer;
  5548. break;
  5549. case BuiltinProc_type_polymorphic_record_parameter_value:
  5550. if (operand->mode != Addressing_Type) {
  5551. error(operand->expr, "Expected a record type for '%.*s'", LIT(builtin_name));
  5552. return false;
  5553. } else if (!is_type_polymorphic_record_specialized(operand->type)) {
  5554. error(operand->expr, "Expected a specialized polymorphic record type for '%.*s'", LIT(builtin_name));
  5555. return false;
  5556. } else {
  5557. Operand op = {};
  5558. check_expr(c, &op, ce->args[1]);
  5559. if (op.mode != Addressing_Constant && !is_type_integer(op.type)) {
  5560. error(op.expr, "Expected a constant integer for the index of record parameter value");
  5561. return false;
  5562. }
  5563. i64 index = exact_value_to_i64(op.value);
  5564. if (index < 0) {
  5565. error(op.expr, "Expected a non-negative integer for the index of record parameter value, got %lld", cast(long long)index);
  5566. return false;
  5567. }
  5568. Entity *param = nullptr;
  5569. i64 count = 0;
  5570. Type *bt = base_type(operand->type);
  5571. if (bt->kind == Type_Struct) {
  5572. if (bt->Struct.polymorphic_params != nullptr) {
  5573. count = bt->Struct.polymorphic_params->Tuple.variables.count;
  5574. if (index < count) {
  5575. param = bt->Struct.polymorphic_params->Tuple.variables[cast(isize)index];
  5576. }
  5577. }
  5578. } else if (bt->kind == Type_Union) {
  5579. if (bt->Union.polymorphic_params != nullptr) {
  5580. count = bt->Union.polymorphic_params->Tuple.variables.count;
  5581. if (index < count) {
  5582. param = bt->Union.polymorphic_params->Tuple.variables[cast(isize)index];
  5583. }
  5584. }
  5585. } else {
  5586. error(operand->expr, "Expected a specialized polymorphic record type for '%.*s'", LIT(builtin_name));
  5587. return false;
  5588. }
  5589. if (index >= count) {
  5590. error(op.expr, "Index of record parameter value out of bounds, expected 0..<%lld, got %lld", cast(long long)count, cast(long long)index);
  5591. return false;
  5592. }
  5593. GB_ASSERT(param != nullptr);
  5594. switch (param->kind) {
  5595. case Entity_Constant:
  5596. operand->mode = Addressing_Constant;
  5597. operand->type = param->type;
  5598. operand->value = param->Constant.value;
  5599. break;
  5600. case Entity_TypeName:
  5601. operand->mode = Addressing_Type;
  5602. operand->type = param->type;
  5603. break;
  5604. default:
  5605. GB_PANIC("Unhandled polymorphic record type");
  5606. break;
  5607. }
  5608. }
  5609. break;
  5610. case BuiltinProc_type_field_index_of:
  5611. {
  5612. Operand op = {};
  5613. Type *bt = check_type(c, ce->args[0]);
  5614. Type *type = base_type(bt);
  5615. if (type == nullptr || type == t_invalid) {
  5616. error(ce->args[0], "Expected a type for '%.*s'", LIT(builtin_name));
  5617. return false;
  5618. }
  5619. Operand x = {};
  5620. check_expr(c, &x, ce->args[1]);
  5621. if (!is_type_string(x.type) || x.mode != Addressing_Constant || x.value.kind != ExactValue_String) {
  5622. error(ce->args[1], "Expected a const string for field argument");
  5623. return false;
  5624. }
  5625. String field_name = x.value.value_string;
  5626. Selection sel = lookup_field(type, field_name, false);
  5627. if (sel.entity == nullptr) {
  5628. gbString type_str = type_to_string(bt);
  5629. error(ce->args[0],
  5630. "'%s' has no field named '%.*s'", type_str, LIT(field_name));
  5631. gb_string_free(type_str);
  5632. return false;
  5633. }
  5634. if (sel.indirect) {
  5635. gbString type_str = type_to_string(bt);
  5636. error(ce->args[0],
  5637. "Field '%.*s' is embedded via a pointer in '%s'", LIT(field_name), type_str);
  5638. gb_string_free(type_str);
  5639. return false;
  5640. }
  5641. operand->mode = Addressing_Constant;
  5642. operand->value = exact_value_u64(sel.index[0]);
  5643. operand->type = t_uintptr;
  5644. break;
  5645. }
  5646. break;
  5647. case BuiltinProc_type_equal_proc:
  5648. {
  5649. Operand op = {};
  5650. Type *bt = check_type(c, ce->args[0]);
  5651. Type *type = base_type(bt);
  5652. if (type == nullptr || type == t_invalid) {
  5653. error(ce->args[0], "Expected a type for '%.*s'", LIT(builtin_name));
  5654. return false;
  5655. }
  5656. if (!is_type_comparable(type)) {
  5657. gbString t = type_to_string(type);
  5658. error(ce->args[0], "Expected a comparable type for '%.*s', got %s", LIT(builtin_name), t);
  5659. gb_string_free(t);
  5660. return false;
  5661. }
  5662. operand->mode = Addressing_Value;
  5663. operand->type = t_equal_proc;
  5664. break;
  5665. }
  5666. case BuiltinProc_type_hasher_proc:
  5667. {
  5668. Operand op = {};
  5669. Type *bt = check_type(c, ce->args[0]);
  5670. Type *type = base_type(bt);
  5671. if (type == nullptr || type == t_invalid) {
  5672. error(ce->args[0], "Expected a type for '%.*s'", LIT(builtin_name));
  5673. return false;
  5674. }
  5675. if (!is_type_valid_for_keys(type)) {
  5676. gbString t = type_to_string(type);
  5677. error(ce->args[0], "Expected a valid type for map keys for '%.*s', got %s", LIT(builtin_name), t);
  5678. gb_string_free(t);
  5679. return false;
  5680. }
  5681. add_map_key_type_dependencies(c, type);
  5682. operand->mode = Addressing_Value;
  5683. operand->type = t_hasher_proc;
  5684. break;
  5685. }
  5686. }
  5687. return true;
  5688. }
  5689. isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) {
  5690. if (lhs != nullptr) {
  5691. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5692. Entity *e = lhs[tuple_index + j];
  5693. if (e != nullptr) {
  5694. DeclInfo *decl = decl_info_of_entity(e);
  5695. if (decl != nullptr) {
  5696. c->decl = decl; // will be reset by the 'defer' any way
  5697. for_array(k, decl->deps.entries) {
  5698. Entity *dep = decl->deps.entries[k].ptr;
  5699. add_declaration_dependency(c, dep); // TODO(bill): Should this be here?
  5700. }
  5701. }
  5702. }
  5703. }
  5704. }
  5705. return tuple_count;
  5706. }
  5707. bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5708. bool optional_ok = false;
  5709. isize tuple_index = 0;
  5710. for_array(i, rhs) {
  5711. CheckerContext c_ = *ctx;
  5712. CheckerContext *c = &c_;
  5713. Operand o = {};
  5714. Type *type_hint = nullptr;
  5715. if (tuple_index < lhs.count) {
  5716. type_hint = lhs[tuple_index].type;
  5717. }
  5718. check_expr_base(c, &o, rhs[i], type_hint);
  5719. if (o.mode == Addressing_NoValue) {
  5720. error_operand_no_value(&o);
  5721. o.mode = Addressing_Invalid;
  5722. }
  5723. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5724. if (lhs.count == 2 && rhs.count == 1 &&
  5725. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk)) {
  5726. bool do_normal = true;
  5727. Ast *expr = unparen_expr(o.expr);
  5728. Operand val0 = o;
  5729. Operand val1 = o;
  5730. val0.mode = Addressing_Value;
  5731. val1.mode = Addressing_Value;
  5732. val1.type = t_untyped_bool;
  5733. if (expr->kind == Ast_CallExpr) {
  5734. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  5735. if (is_type_proc(pt)) {
  5736. do_normal = false;
  5737. Type *tuple = pt->Proc.results;
  5738. add_type_and_value(&c->checker->info, o.expr, o.mode, tuple, o.value);
  5739. if (pt->Proc.result_count >= 2) {
  5740. Type *t1 = tuple->Tuple.variables[1]->type;
  5741. val1.type = t1;
  5742. }
  5743. expr->CallExpr.optional_ok_one = false;
  5744. }
  5745. }
  5746. if (do_normal) {
  5747. Type *tuple = make_optional_ok_type(o.type);
  5748. add_type_and_value(&c->checker->info, o.expr, o.mode, tuple, o.value);
  5749. }
  5750. array_add(operands, val0);
  5751. array_add(operands, val1);
  5752. optional_ok = true;
  5753. tuple_index += 2;
  5754. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5755. Type *tuple = o.type;
  5756. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5757. Ast *expr = unparen_expr(o.expr);
  5758. if (expr->kind == Ast_CallExpr) {
  5759. expr->CallExpr.optional_ok_one = true;
  5760. }
  5761. Operand val = o;
  5762. val.type = tuple->Tuple.variables[0]->type;
  5763. val.mode = Addressing_Value;
  5764. array_add(operands, val);
  5765. tuple_index += tuple->Tuple.variables.count;
  5766. } else {
  5767. array_add(operands, o);
  5768. tuple_index += 1;
  5769. }
  5770. } else {
  5771. TypeTuple *tuple = &o.type->Tuple;
  5772. for_array(j, tuple->variables) {
  5773. o.type = tuple->variables[j]->type;
  5774. array_add(operands, o);
  5775. }
  5776. tuple_index += tuple->variables.count;
  5777. }
  5778. }
  5779. return optional_ok;
  5780. }
  5781. bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs, bool allow_ok, bool is_variadic) {
  5782. bool optional_ok = false;
  5783. isize tuple_index = 0;
  5784. for_array(i, rhs) {
  5785. CheckerContext c_ = *ctx;
  5786. CheckerContext *c = &c_;
  5787. Operand o = {};
  5788. Type *type_hint = nullptr;
  5789. if (lhs != nullptr && tuple_index < lhs_count) {
  5790. // NOTE(bill): override DeclInfo for dependency
  5791. Entity *e = lhs[tuple_index];
  5792. if (e != nullptr) {
  5793. // DeclInfo *decl = decl_info_of_entity(e);
  5794. // if (decl) c->decl = decl;
  5795. type_hint = e->type;
  5796. if (e->flags & EntityFlag_Ellipsis) {
  5797. GB_ASSERT(is_type_slice(e->type));
  5798. GB_ASSERT(e->type->kind == Type_Slice);
  5799. type_hint = e->type->Slice.elem;
  5800. }
  5801. }
  5802. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  5803. // NOTE(bill): override DeclInfo for dependency
  5804. Entity *e = lhs[lhs_count-1];
  5805. if (e != nullptr) {
  5806. // DeclInfo *decl = decl_info_of_entity(e);
  5807. // if (decl) c->decl = decl;
  5808. type_hint = e->type;
  5809. if (e->flags & EntityFlag_Ellipsis) {
  5810. GB_ASSERT(is_type_slice(e->type));
  5811. GB_ASSERT(e->type->kind == Type_Slice);
  5812. type_hint = e->type->Slice.elem;
  5813. }
  5814. }
  5815. }
  5816. check_expr_base(c, &o, rhs[i], type_hint);
  5817. if (o.mode == Addressing_NoValue) {
  5818. error_operand_no_value(&o);
  5819. o.mode = Addressing_Invalid;
  5820. }
  5821. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5822. if (allow_ok && lhs_count == 2 && rhs.count == 1 &&
  5823. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk)) {
  5824. bool do_normal = true;
  5825. Ast *expr = unparen_expr(o.expr);
  5826. Operand val0 = o;
  5827. Operand val1 = o;
  5828. val0.mode = Addressing_Value;
  5829. val1.mode = Addressing_Value;
  5830. val1.type = t_untyped_bool;
  5831. if (expr->kind == Ast_CallExpr) {
  5832. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  5833. if (is_type_proc(pt)) {
  5834. do_normal = false;
  5835. Type *tuple = pt->Proc.results;
  5836. add_type_and_value(&c->checker->info, o.expr, o.mode, tuple, o.value);
  5837. if (pt->Proc.result_count >= 2) {
  5838. Type *t1 = tuple->Tuple.variables[1]->type;
  5839. val1.type = t1;
  5840. }
  5841. expr->CallExpr.optional_ok_one = false;
  5842. }
  5843. }
  5844. if (do_normal) {
  5845. Type *tuple = make_optional_ok_type(o.type);
  5846. add_type_and_value(&c->checker->info, o.expr, o.mode, tuple, o.value);
  5847. }
  5848. array_add(operands, val0);
  5849. array_add(operands, val1);
  5850. optional_ok = true;
  5851. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5852. } else {
  5853. array_add(operands, o);
  5854. tuple_index += 1;
  5855. }
  5856. } else {
  5857. TypeTuple *tuple = &o.type->Tuple;
  5858. for_array(j, tuple->variables) {
  5859. o.type = tuple->variables[j]->type;
  5860. array_add(operands, o);
  5861. }
  5862. isize count = tuple->variables.count;
  5863. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5864. }
  5865. }
  5866. return optional_ok;
  5867. }
  5868. CALL_ARGUMENT_CHECKER(check_call_arguments_internal) {
  5869. ast_node(ce, CallExpr, call);
  5870. GB_ASSERT(is_type_proc(proc_type));
  5871. proc_type = base_type(proc_type);
  5872. TypeProc *pt = &proc_type->Proc;
  5873. isize param_count = 0;
  5874. isize param_count_excluding_defaults = 0;
  5875. bool variadic = pt->variadic;
  5876. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5877. i64 score = 0;
  5878. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  5879. TypeTuple *param_tuple = nullptr;
  5880. if (pt->params != nullptr) {
  5881. param_tuple = &pt->params->Tuple;
  5882. param_count = param_tuple->variables.count;
  5883. if (variadic) {
  5884. for (isize i = param_count-1; i >= 0; i--) {
  5885. Entity *e = param_tuple->variables[i];
  5886. if (e->kind == Entity_TypeName) {
  5887. break;
  5888. }
  5889. if (e->kind == Entity_Variable) {
  5890. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5891. param_count--;
  5892. continue;
  5893. }
  5894. }
  5895. break;
  5896. }
  5897. param_count--;
  5898. }
  5899. }
  5900. param_count_excluding_defaults = param_count;
  5901. if (param_tuple != nullptr) {
  5902. for (isize i = param_count-1; i >= 0; i--) {
  5903. Entity *e = param_tuple->variables[i];
  5904. if (e->kind == Entity_TypeName) {
  5905. break;
  5906. }
  5907. if (e->kind == Entity_Variable) {
  5908. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5909. param_count_excluding_defaults--;
  5910. continue;
  5911. }
  5912. }
  5913. break;
  5914. }
  5915. }
  5916. CallArgumentError err = CallArgumentError_None;
  5917. Type *final_proc_type = proc_type;
  5918. Entity *gen_entity = nullptr;
  5919. if (vari_expand && !variadic) {
  5920. if (show_error) {
  5921. error(ce->ellipsis,
  5922. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5923. LIT(ce->proc->Ident.token.string));
  5924. }
  5925. err = CallArgumentError_NonVariadicExpand;
  5926. } else if (vari_expand && pt->c_vararg) {
  5927. if (show_error) {
  5928. error(ce->ellipsis,
  5929. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5930. LIT(ce->proc->Ident.token.string));
  5931. }
  5932. err = CallArgumentError_NonVariadicExpand;
  5933. } else if (operands.count == 0 && param_count_excluding_defaults == 0) {
  5934. err = CallArgumentError_None;
  5935. if (variadic) {
  5936. GB_ASSERT(param_tuple != nullptr && param_tuple->variables.count > 0);
  5937. Type *t = param_tuple->variables[0]->type;
  5938. if (is_type_polymorphic(t)) {
  5939. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5940. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5941. }
  5942. }
  5943. } else {
  5944. i32 error_code = 0;
  5945. if (operands.count < param_count_excluding_defaults) {
  5946. error_code = -1;
  5947. } else if (!variadic && operands.count > param_count) {
  5948. error_code = +1;
  5949. }
  5950. if (error_code != 0) {
  5951. err = CallArgumentError_TooManyArguments;
  5952. char const *err_fmt = "Too many arguments for '%s', expected %td arguments";
  5953. if (error_code < 0) {
  5954. err = CallArgumentError_TooFewArguments;
  5955. err_fmt = "Too few arguments for '%s', expected %td arguments";
  5956. }
  5957. if (show_error) {
  5958. gbString proc_str = expr_to_string(ce->proc);
  5959. error(call, err_fmt, proc_str, param_count_excluding_defaults);
  5960. gb_string_free(proc_str);
  5961. }
  5962. } else {
  5963. // NOTE(bill): Generate the procedure type for this generic instance
  5964. PolyProcData poly_proc_data = {};
  5965. if (pt->is_polymorphic && !pt->is_poly_specialized) {
  5966. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &operands, call, &poly_proc_data)) {
  5967. gen_entity = poly_proc_data.gen_entity;
  5968. GB_ASSERT(is_type_proc(gen_entity->type));
  5969. final_proc_type = gen_entity->type;
  5970. } else {
  5971. err = CallArgumentError_WrongTypes;
  5972. }
  5973. }
  5974. GB_ASSERT(is_type_proc(final_proc_type));
  5975. TypeProc *pt = &final_proc_type->Proc;
  5976. GB_ASSERT(pt->params != nullptr);
  5977. auto sig_params = pt->params->Tuple.variables;
  5978. isize operand_index = 0;
  5979. isize max_operand_count = gb_min(param_count, operands.count);
  5980. for (; operand_index < max_operand_count; operand_index++) {
  5981. Entity *e = sig_params[operand_index];
  5982. Type *t = e->type;
  5983. Operand o = operands[operand_index];
  5984. if (o.expr != nullptr) {
  5985. call->viral_state_flags |= o.expr->viral_state_flags;
  5986. }
  5987. if (e->kind == Entity_TypeName) {
  5988. // GB_ASSERT(!variadic);
  5989. if (o.mode == Addressing_Invalid) {
  5990. continue;
  5991. } else if (o.mode != Addressing_Type) {
  5992. if (show_error) {
  5993. error(o.expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5994. }
  5995. err = CallArgumentError_WrongTypes;
  5996. }
  5997. if (are_types_identical(e->type, o.type)) {
  5998. score += assign_score_function(1);
  5999. } else {
  6000. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6001. }
  6002. continue;
  6003. }
  6004. bool param_is_variadic = pt->variadic && pt->variadic_index == operand_index;
  6005. i64 s = 0;
  6006. if (!check_is_assignable_to_with_score(c, &o, t, &s, param_is_variadic)) {
  6007. bool ok = false;
  6008. if (e->flags & EntityFlag_AutoCast) {
  6009. ok = check_is_castable_to(c, &o, t);
  6010. }
  6011. if (ok) {
  6012. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6013. } else {
  6014. if (show_error) {
  6015. check_assignment(c, &o, t, str_lit("argument"));
  6016. }
  6017. err = CallArgumentError_WrongTypes;
  6018. }
  6019. }
  6020. score += s;
  6021. if (e->flags & EntityFlag_ConstInput) {
  6022. if (o.mode != Addressing_Constant) {
  6023. if (show_error) {
  6024. error(o.expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  6025. }
  6026. err = CallArgumentError_NoneConstantParameter;
  6027. }
  6028. }
  6029. if (o.mode == Addressing_Type && is_type_typeid(e->type)) {
  6030. add_type_info_type(c, o.type);
  6031. add_type_and_value(c->info, o.expr, Addressing_Value, e->type, exact_value_typeid(o.type));
  6032. }
  6033. }
  6034. if (variadic) {
  6035. bool variadic_expand = false;
  6036. Type *slice = sig_params[param_count]->type;
  6037. GB_ASSERT(is_type_slice(slice));
  6038. Type *elem = base_type(slice)->Slice.elem;
  6039. Type *t = elem;
  6040. if (is_type_polymorphic(t)) {
  6041. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  6042. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  6043. }
  6044. for (; operand_index < operands.count; operand_index++) {
  6045. Operand o = operands[operand_index];
  6046. if (vari_expand) {
  6047. variadic_expand = true;
  6048. t = slice;
  6049. if (operand_index != param_count) {
  6050. if (show_error) {
  6051. error(o.expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  6052. }
  6053. if (data) {
  6054. data->score = score;
  6055. data->result_type = final_proc_type->Proc.results;
  6056. data->gen_entity = gen_entity;
  6057. }
  6058. return CallArgumentError_MultipleVariadicExpand;
  6059. }
  6060. }
  6061. i64 s = 0;
  6062. if (!check_is_assignable_to_with_score(c, &o, t, &s, true)) {
  6063. if (show_error) {
  6064. check_assignment(c, &o, t, str_lit("argument"));
  6065. }
  6066. err = CallArgumentError_WrongTypes;
  6067. }
  6068. score += s;
  6069. if (is_type_any(elem)) {
  6070. add_type_info_type(c, o.type);
  6071. }
  6072. if (o.mode == Addressing_Type && is_type_typeid(t)) {
  6073. add_type_info_type(c, o.type);
  6074. add_type_and_value(c->info, o.expr, Addressing_Value, t, exact_value_typeid(o.type));
  6075. }
  6076. }
  6077. }
  6078. }
  6079. }
  6080. if (data) {
  6081. data->score = score;
  6082. data->result_type = final_proc_type->Proc.results;
  6083. data->gen_entity = gen_entity;
  6084. add_type_and_value(c->info, ce->proc, Addressing_Value, final_proc_type, {});
  6085. }
  6086. return err;
  6087. }
  6088. bool is_call_expr_field_value(AstCallExpr *ce) {
  6089. GB_ASSERT(ce != nullptr);
  6090. if (ce->args.count == 0) {
  6091. return false;
  6092. }
  6093. return ce->args[0]->kind == Ast_FieldValue;
  6094. }
  6095. isize lookup_procedure_parameter(TypeProc *pt, String parameter_name) {
  6096. isize param_count = pt->param_count;
  6097. for (isize i = 0; i < param_count; i++) {
  6098. Entity *e = pt->params->Tuple.variables[i];
  6099. String name = e->token.string;
  6100. if (is_blank_ident(name)) {
  6101. continue;
  6102. }
  6103. if (name == parameter_name) {
  6104. return i;
  6105. }
  6106. }
  6107. return -1;
  6108. }
  6109. isize lookup_procedure_result(TypeProc *pt, String result_name) {
  6110. isize result_count = pt->result_count;
  6111. for (isize i = 0; i < result_count; i++) {
  6112. Entity *e = pt->results->Tuple.variables[i];
  6113. String name = e->token.string;
  6114. if (is_blank_ident(name)) {
  6115. continue;
  6116. }
  6117. if (name == result_name) {
  6118. return i;
  6119. }
  6120. }
  6121. return -1;
  6122. }
  6123. CALL_ARGUMENT_CHECKER(check_named_call_arguments) {
  6124. ast_node(ce, CallExpr, call);
  6125. GB_ASSERT(is_type_proc(proc_type));
  6126. proc_type = base_type(proc_type);
  6127. TypeProc *pt = &proc_type->Proc;
  6128. i64 score = 0;
  6129. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  6130. CallArgumentError err = CallArgumentError_None;
  6131. isize param_count = pt->param_count;
  6132. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6133. auto ordered_operands = array_make<Operand>(temporary_allocator(), param_count);
  6134. defer ({
  6135. for_array(i, ordered_operands) {
  6136. Operand const &o = ordered_operands[i];
  6137. if (o.expr != nullptr) {
  6138. call->viral_state_flags |= o.expr->viral_state_flags;
  6139. }
  6140. }
  6141. });
  6142. for_array(i, ce->args) {
  6143. Ast *arg = ce->args[i];
  6144. ast_node(fv, FieldValue, arg);
  6145. if (fv->field->kind != Ast_Ident) {
  6146. if (show_error) {
  6147. gbString expr_str = expr_to_string(fv->field);
  6148. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6149. gb_string_free(expr_str);
  6150. }
  6151. err = CallArgumentError_InvalidFieldValue;
  6152. continue;
  6153. }
  6154. String name = fv->field->Ident.token.string;
  6155. isize index = lookup_procedure_parameter(pt, name);
  6156. if (index < 0) {
  6157. if (show_error) {
  6158. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  6159. }
  6160. err = CallArgumentError_ParameterNotFound;
  6161. continue;
  6162. }
  6163. if (visited[index]) {
  6164. if (show_error) {
  6165. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  6166. }
  6167. err = CallArgumentError_DuplicateParameter;
  6168. continue;
  6169. }
  6170. visited[index] = true;
  6171. ordered_operands[index] = operands[i];
  6172. }
  6173. // NOTE(bill): Check for default values and missing parameters
  6174. isize param_count_to_check = param_count;
  6175. if (pt->variadic) {
  6176. param_count_to_check--;
  6177. }
  6178. for (isize i = 0; i < param_count_to_check; i++) {
  6179. if (!visited[i]) {
  6180. Entity *e = pt->params->Tuple.variables[i];
  6181. if (is_blank_ident(e->token)) {
  6182. continue;
  6183. }
  6184. if (e->kind == Entity_Variable) {
  6185. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  6186. score += assign_score_function(1);
  6187. continue;
  6188. }
  6189. }
  6190. if (show_error) {
  6191. if (e->kind == Entity_TypeName) {
  6192. error(call, "Type parameter '%.*s' is missing in procedure call",
  6193. LIT(e->token.string));
  6194. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  6195. // Ignore
  6196. } else {
  6197. gbString str = type_to_string(e->type);
  6198. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  6199. LIT(e->token.string), str);
  6200. gb_string_free(str);
  6201. }
  6202. }
  6203. err = CallArgumentError_ParameterMissing;
  6204. }
  6205. }
  6206. Entity *gen_entity = nullptr;
  6207. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  6208. PolyProcData poly_proc_data = {};
  6209. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  6210. gen_entity = poly_proc_data.gen_entity;
  6211. Type *gept = base_type(gen_entity->type);
  6212. GB_ASSERT(is_type_proc(gept));
  6213. proc_type = gept;
  6214. pt = &gept->Proc;
  6215. }
  6216. }
  6217. for (isize i = 0; i < param_count; i++) {
  6218. Entity *e = pt->params->Tuple.variables[i];
  6219. Operand *o = &ordered_operands[i];
  6220. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  6221. if (o->mode == Addressing_Invalid) {
  6222. if (param_is_variadic) {
  6223. Type *slice = e->type;
  6224. GB_ASSERT(is_type_slice(slice));
  6225. Type *elem = base_type(slice)->Slice.elem;
  6226. if (is_type_polymorphic(elem)) {
  6227. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  6228. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  6229. return err;
  6230. }
  6231. }
  6232. continue;
  6233. }
  6234. if (e->kind == Entity_TypeName) {
  6235. GB_ASSERT(pt->is_polymorphic);
  6236. if (o->mode != Addressing_Type) {
  6237. if (show_error) {
  6238. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  6239. }
  6240. err = CallArgumentError_WrongTypes;
  6241. }
  6242. if (are_types_identical(e->type, o->type)) {
  6243. score += assign_score_function(1);
  6244. } else {
  6245. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6246. }
  6247. } else {
  6248. i64 s = 0;
  6249. if (!check_is_assignable_to_with_score(c, o, e->type, &s, param_is_variadic)) {
  6250. bool ok = false;
  6251. if (e->flags & EntityFlag_AutoCast) {
  6252. ok = check_is_castable_to(c, o, e->type);
  6253. }
  6254. if (ok) {
  6255. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6256. } else {
  6257. if (show_error) {
  6258. check_assignment(c, o, e->type, str_lit("procedure argument"));
  6259. }
  6260. err = CallArgumentError_WrongTypes;
  6261. }
  6262. if (e->flags & EntityFlag_ConstInput) {
  6263. if (o->mode != Addressing_Constant) {
  6264. if (show_error) {
  6265. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  6266. }
  6267. err = CallArgumentError_NoneConstantParameter;
  6268. }
  6269. }
  6270. }
  6271. score += s;
  6272. }
  6273. if (o->mode == Addressing_Type && is_type_typeid(e->type)) {
  6274. add_type_info_type(c, o->type);
  6275. add_type_and_value(c->info, o->expr, Addressing_Value, e->type, exact_value_typeid(o->type));
  6276. }
  6277. }
  6278. if (data) {
  6279. data->score = score;
  6280. data->result_type = pt->results;
  6281. data->gen_entity = gen_entity;
  6282. add_type_and_value(c->info, ce->proc, Addressing_Value, proc_type, {});
  6283. }
  6284. return err;
  6285. }
  6286. Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  6287. Entity **lhs = nullptr;
  6288. isize lhs_count = -1;
  6289. if (proc_type == nullptr) {
  6290. return nullptr;
  6291. }
  6292. GB_ASSERT(is_type_proc(proc_type));
  6293. TypeProc *pt = &base_type(proc_type)->Proc;
  6294. *is_variadic = pt->variadic;
  6295. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  6296. if (pt->params != nullptr) {
  6297. lhs = pt->params->Tuple.variables.data;
  6298. lhs_count = pt->params->Tuple.variables.count;
  6299. }
  6300. } else {
  6301. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  6302. if (pt->params == nullptr) {
  6303. lhs_count = 0;
  6304. } else {
  6305. lhs_count = pt->params->Tuple.variables.count;
  6306. }
  6307. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6308. for (isize i = 0; i < lhs_count; i++) {
  6309. Entity *e = pt->params->Tuple.variables[i];
  6310. if (!is_type_polymorphic(e->type)) {
  6311. lhs[i] = e;
  6312. }
  6313. }
  6314. }
  6315. if (lhs_count_) *lhs_count_ = lhs_count;
  6316. return lhs;
  6317. }
  6318. bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  6319. if (clauses != nullptr) {
  6320. for_array(i, *clauses) {
  6321. Ast *clause = (*clauses)[i];
  6322. Operand o = {};
  6323. check_expr(ctx, &o, clause);
  6324. if (o.mode != Addressing_Constant) {
  6325. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  6326. if (print_err && call_expr) error(call_expr, "at caller location");
  6327. return false;
  6328. } else if (o.value.kind != ExactValue_Bool) {
  6329. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  6330. if (print_err && call_expr) error(call_expr, "at caller location");
  6331. return false;
  6332. } else if (!o.value.value_bool) {
  6333. if (print_err) {
  6334. gbString str = expr_to_string(clause);
  6335. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  6336. gb_string_free(str);
  6337. if (scope != nullptr) {
  6338. isize print_count = 0;
  6339. for_array(j, scope->elements.entries) {
  6340. Entity *e = scope->elements.entries[j].value;
  6341. switch (e->kind) {
  6342. case Entity_TypeName: {
  6343. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  6344. gbString str = type_to_string(e->type);
  6345. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  6346. gb_string_free(str);
  6347. print_count += 1;
  6348. break;
  6349. }
  6350. case Entity_Constant: {
  6351. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  6352. gbString str = exact_value_to_string(e->Constant.value);
  6353. if (is_type_untyped(e->type)) {
  6354. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  6355. } else {
  6356. gbString t = type_to_string(e->type);
  6357. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  6358. gb_string_free(t);
  6359. }
  6360. gb_string_free(str);
  6361. print_count += 1;
  6362. break;
  6363. }
  6364. }
  6365. }
  6366. }
  6367. if (call_expr) error(call_expr, "at caller location");
  6368. }
  6369. return false;
  6370. }
  6371. }
  6372. }
  6373. return true;
  6374. }
  6375. CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Type *proc_type, Ast *call, Slice<Ast *> const &args) {
  6376. ast_node(ce, CallExpr, call);
  6377. CallArgumentCheckerType *call_checker = check_call_arguments_internal;
  6378. Array<Operand> operands = {};
  6379. defer (array_free(&operands));
  6380. Type *result_type = t_invalid;
  6381. if (is_call_expr_field_value(ce)) {
  6382. call_checker = check_named_call_arguments;
  6383. operands = array_make<Operand>(heap_allocator(), args.count);
  6384. // NOTE(bill): This is give type hints for the named parameters
  6385. // in order to improve the type inference system
  6386. StringMap<Type *> type_hint_map = {}; // Key: String
  6387. string_map_init(&type_hint_map, heap_allocator(), 2*args.count);
  6388. defer (string_map_destroy(&type_hint_map));
  6389. Type *ptype = nullptr;
  6390. bool single_case = true;
  6391. if (operand->mode == Addressing_ProcGroup) {
  6392. single_case = false;
  6393. Array<Entity *> procs = proc_group_entities(c, *operand);
  6394. if (procs.count == 1) {
  6395. ptype = procs[0]->type;
  6396. single_case = true;
  6397. }
  6398. } else {
  6399. ptype = proc_type;
  6400. }
  6401. if (single_case) {
  6402. Type *bptype = base_type(ptype);
  6403. if (is_type_proc(bptype)) {
  6404. TypeProc *pt = &bptype->Proc;
  6405. TypeTuple *param_tuple = nullptr;
  6406. if (pt->params != nullptr) {
  6407. param_tuple = &pt->params->Tuple;
  6408. }
  6409. if (param_tuple != nullptr) {
  6410. for_array(i, param_tuple->variables) {
  6411. Entity *e = param_tuple->variables[i];
  6412. if (is_blank_ident(e->token)) {
  6413. continue;
  6414. }
  6415. string_map_set(&type_hint_map, e->token.string, e->type);
  6416. }
  6417. }
  6418. }
  6419. } else {
  6420. Array<Entity *> procs = proc_group_entities(c, *operand);
  6421. for_array(j, procs) {
  6422. Type *proc_type = base_type(procs[j]->type);
  6423. if (is_type_proc(proc_type)) {
  6424. TypeProc *pt = &proc_type->Proc;
  6425. TypeTuple *param_tuple = nullptr;
  6426. if (pt->params != nullptr) {
  6427. param_tuple = &pt->params->Tuple;
  6428. }
  6429. if (param_tuple == nullptr) {
  6430. continue;
  6431. }
  6432. for_array(i, param_tuple->variables) {
  6433. Entity *e = param_tuple->variables[i];
  6434. if (is_blank_ident(e->token)) {
  6435. continue;
  6436. }
  6437. StringHashKey key = string_hash_string(e->token.string);
  6438. Type **found = string_map_get(&type_hint_map, key);
  6439. if (found) {
  6440. Type *t = *found;
  6441. if (t == nullptr) {
  6442. // NOTE(bill): Ambiguous named parameter across all types
  6443. continue;
  6444. }
  6445. if (are_types_identical(t, e->type)) {
  6446. // NOTE(bill): No need to set again
  6447. } else {
  6448. // NOTE(bill): Ambiguous named parameter across all types so set it to a nullptr
  6449. string_map_set(&type_hint_map, key, cast(Type *)nullptr);
  6450. }
  6451. } else {
  6452. string_map_set(&type_hint_map, key, e->type);
  6453. }
  6454. }
  6455. }
  6456. }
  6457. }
  6458. for_array(i, args) {
  6459. Ast *arg = args[i];
  6460. ast_node(fv, FieldValue, arg);
  6461. Ast *field = fv->field;
  6462. Type *type_hint = nullptr;
  6463. if (field != nullptr && field->kind == Ast_Ident) {
  6464. String key = field->Ident.token.string;
  6465. Type **found = string_map_get(&type_hint_map, key);
  6466. if (found) {
  6467. type_hint = *found;
  6468. }
  6469. }
  6470. check_expr_or_type(c, &operands[i], fv->value, type_hint);
  6471. }
  6472. } else {
  6473. operands = array_make<Operand>(heap_allocator(), 0, 2*args.count);
  6474. Entity **lhs = nullptr;
  6475. isize lhs_count = -1;
  6476. bool is_variadic = false;
  6477. if (proc_type != nullptr && is_type_proc(proc_type)) {
  6478. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6479. }
  6480. if (operand->mode != Addressing_ProcGroup) {
  6481. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, is_variadic);
  6482. }
  6483. }
  6484. if (operand->mode == Addressing_ProcGroup) {
  6485. check_entity_decl(c, operand->proc_group, nullptr, nullptr);
  6486. Array<Entity *> procs = proc_group_entities(c, *operand);
  6487. if (procs.count == 1) {
  6488. Ast *ident = operand->expr;
  6489. while (ident->kind == Ast_SelectorExpr) {
  6490. Ast *s = ident->SelectorExpr.selector;
  6491. ident = s;
  6492. }
  6493. Entity *e = procs[0];
  6494. Entity **lhs = nullptr;
  6495. isize lhs_count = -1;
  6496. bool is_variadic = false;
  6497. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  6498. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, is_variadic);
  6499. CallArgumentData data = {};
  6500. CallArgumentError err = call_checker(c, call, e->type, e, operands, CallArgumentMode_ShowErrors, &data);
  6501. if (err != CallArgumentError_None) {
  6502. // handle error
  6503. }
  6504. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6505. add_entity_use(c, ident, entity_to_use);
  6506. if (entity_to_use != nullptr) {
  6507. update_expr_type(c, operand->expr, entity_to_use->type, true);
  6508. }
  6509. return data;
  6510. }
  6511. Entity **lhs = nullptr;
  6512. isize lhs_count = -1;
  6513. {
  6514. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6515. // where the same positional parameter has the same type value (and ellipsis)
  6516. bool proc_arg_count_all_equal = true;
  6517. isize proc_arg_count = -1;
  6518. for_array(i, procs) {
  6519. Entity *p = procs[i];
  6520. Type *pt = base_type(p->type);
  6521. if (pt != nullptr && is_type_proc(pt)) {
  6522. if (proc_arg_count < 0) {
  6523. proc_arg_count = pt->Proc.param_count;
  6524. } else {
  6525. if (proc_arg_count != pt->Proc.param_count) {
  6526. proc_arg_count_all_equal = false;
  6527. break;
  6528. }
  6529. }
  6530. }
  6531. }
  6532. if (proc_arg_count >= 0 && proc_arg_count_all_equal) {
  6533. lhs_count = proc_arg_count;
  6534. if (lhs_count > 0) {
  6535. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6536. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6537. Entity *e = nullptr;
  6538. for_array(j, procs) {
  6539. Entity *p = procs[j];
  6540. Type *pt = base_type(p->type);
  6541. if (pt != nullptr && is_type_proc(pt)) {
  6542. if (e == nullptr) {
  6543. e = pt->Proc.params->Tuple.variables[param_index];
  6544. } else {
  6545. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6546. if (e == f) {
  6547. continue;
  6548. }
  6549. if (are_types_identical(e->type, f->type)) {
  6550. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6551. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6552. if (ee == fe) {
  6553. continue;
  6554. }
  6555. }
  6556. // NOTE(bill): Entities are not close enough to be used
  6557. e = nullptr;
  6558. break;
  6559. }
  6560. }
  6561. }
  6562. lhs[param_index] = e;
  6563. }
  6564. }
  6565. }
  6566. }
  6567. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, false);
  6568. if (lhs != nullptr) {
  6569. gb_free(heap_allocator(), lhs);
  6570. }
  6571. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6572. defer (array_free(&valids));
  6573. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6574. defer (array_free(&proc_entities));
  6575. for_array(i, procs) {
  6576. array_add(&proc_entities, procs[i]);
  6577. }
  6578. gbString expr_name = expr_to_string(operand->expr);
  6579. defer (gb_string_free(expr_name));
  6580. for_array(i, procs) {
  6581. Entity *p = procs[i];
  6582. Type *pt = base_type(p->type);
  6583. if (pt != nullptr && is_type_proc(pt)) {
  6584. CallArgumentError err = CallArgumentError_None;
  6585. CallArgumentData data = {};
  6586. CheckerContext ctx = *c;
  6587. ctx.no_polymorphic_errors = true;
  6588. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6589. ctx.hide_polymorphic_errors = true;
  6590. err = call_checker(&ctx, call, pt, p, operands, CallArgumentMode_NoErrors, &data);
  6591. if (err != CallArgumentError_None) {
  6592. continue;
  6593. }
  6594. isize index = i;
  6595. if (data.gen_entity != nullptr) {
  6596. Entity *e = data.gen_entity;
  6597. DeclInfo *decl = data.gen_entity->decl_info;
  6598. ctx.scope = decl->scope;
  6599. ctx.decl = decl;
  6600. ctx.proc_name = e->token.string;
  6601. ctx.curr_proc_decl = decl;
  6602. ctx.curr_proc_sig = e->type;
  6603. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6604. if (!evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, false)) {
  6605. continue;
  6606. }
  6607. array_add(&proc_entities, data.gen_entity);
  6608. index = proc_entities.count-1;
  6609. }
  6610. ValidIndexAndScore item = {};
  6611. item.index = index;
  6612. item.score = data.score;
  6613. array_add(&valids, item);
  6614. }
  6615. }
  6616. if (valids.count > 1) {
  6617. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  6618. i64 best_score = valids[0].score;
  6619. Entity *best_entity = proc_entities[valids[0].index];
  6620. GB_ASSERT(best_entity != nullptr);
  6621. for (isize i = 1; i < valids.count; i++) {
  6622. if (best_score > valids[i].score) {
  6623. valids.count = i;
  6624. break;
  6625. }
  6626. if (best_entity == proc_entities[valids[i].index]) {
  6627. valids.count = i;
  6628. break;
  6629. }
  6630. }
  6631. }
  6632. if (valids.count == 0) {
  6633. begin_error_block();
  6634. defer (end_error_block());
  6635. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6636. if (operands.count == 0) {
  6637. error_line("\tNo given arguments\n");
  6638. } else {
  6639. error_line("\tGiven argument types: (");
  6640. for_array(i, operands) {
  6641. Operand o = operands[i];
  6642. if (i > 0) error_line(", ");
  6643. gbString type = type_to_string(o.type);
  6644. defer (gb_string_free(type));
  6645. error_line("%s", type);
  6646. }
  6647. error_line(")\n");
  6648. }
  6649. if (procs.count > 0) {
  6650. error_line("Did you mean to use one of the following:\n");
  6651. }
  6652. for_array(i, procs) {
  6653. Entity *proc = procs[i];
  6654. TokenPos pos = proc->token.pos;
  6655. Type *t = base_type(proc->type);
  6656. if (t == t_invalid) continue;
  6657. GB_ASSERT(t->kind == Type_Proc);
  6658. gbString pt;
  6659. defer (gb_string_free(pt));
  6660. if (t->Proc.node != nullptr) {
  6661. pt = expr_to_string(t->Proc.node);
  6662. } else {
  6663. pt = type_to_string(t);
  6664. }
  6665. String prefix = {};
  6666. String prefix_sep = {};
  6667. if (proc->pkg) {
  6668. prefix = proc->pkg->name;
  6669. prefix_sep = str_lit(".");
  6670. }
  6671. String name = proc->token.string;
  6672. char const *sep = "::";
  6673. if (proc->kind == Entity_Variable) {
  6674. sep = ":=";
  6675. }
  6676. error_line("\t%.*s%.*s%.*s %s %s at %s\n", LIT(prefix), LIT(prefix_sep), LIT(name), sep, pt, token_pos_to_string(pos));
  6677. }
  6678. if (procs.count > 0) {
  6679. error_line("\n");
  6680. }
  6681. result_type = t_invalid;
  6682. } else if (valids.count > 1) {
  6683. begin_error_block();
  6684. defer (end_error_block());
  6685. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6686. error_line("\tGiven argument types: (");
  6687. for_array(i, operands) {
  6688. Operand o = operands[i];
  6689. if (i > 0) error_line(", ");
  6690. gbString type = type_to_string(o.type);
  6691. defer (gb_string_free(type));
  6692. error_line("%s", type);
  6693. }
  6694. error_line(")\n");
  6695. for (isize i = 0; i < valids.count; i++) {
  6696. Entity *proc = proc_entities[valids[i].index];
  6697. GB_ASSERT(proc != nullptr);
  6698. TokenPos pos = proc->token.pos;
  6699. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6700. gbString pt = nullptr;
  6701. defer (gb_string_free(pt));
  6702. if (t->Proc.node != nullptr) {
  6703. pt = expr_to_string(t->Proc.node);
  6704. } else {
  6705. pt = type_to_string(t);
  6706. }
  6707. String name = proc->token.string;
  6708. char const *sep = "::";
  6709. if (proc->kind == Entity_Variable) {
  6710. sep = ":=";
  6711. }
  6712. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6713. if (proc->decl_info->proc_lit != nullptr) {
  6714. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6715. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6716. if (pl->where_token.kind != Token_Invalid) {
  6717. error_line("\n\t\twhere ");
  6718. for_array(j, pl->where_clauses) {
  6719. Ast *clause = pl->where_clauses[j];
  6720. if (j != 0) {
  6721. error_line("\t\t ");
  6722. }
  6723. gbString str = expr_to_string(clause);
  6724. error_line("%s", str);
  6725. gb_string_free(str);
  6726. if (j != pl->where_clauses.count-1) {
  6727. error_line(",");
  6728. }
  6729. }
  6730. error_line("\n\t");
  6731. }
  6732. }
  6733. error_line("at %s\n", token_pos_to_string(pos));
  6734. }
  6735. result_type = t_invalid;
  6736. } else {
  6737. Ast *ident = operand->expr;
  6738. while (ident->kind == Ast_SelectorExpr) {
  6739. Ast *s = ident->SelectorExpr.selector;
  6740. ident = s;
  6741. }
  6742. Entity *e = proc_entities[valids[0].index];
  6743. GB_ASSERT(e != nullptr);
  6744. proc_type = e->type;
  6745. CallArgumentData data = {};
  6746. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  6747. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6748. add_entity_use(c, ident, entity_to_use);
  6749. if (entity_to_use != nullptr) {
  6750. update_expr_type(c, operand->expr, entity_to_use->type, true);
  6751. }
  6752. if (data.gen_entity != nullptr) {
  6753. Entity *e = data.gen_entity;
  6754. DeclInfo *decl = data.gen_entity->decl_info;
  6755. CheckerContext ctx = *c;
  6756. ctx.scope = decl->scope;
  6757. ctx.decl = decl;
  6758. ctx.proc_name = e->token.string;
  6759. ctx.curr_proc_decl = decl;
  6760. ctx.curr_proc_sig = e->type;
  6761. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6762. evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  6763. decl->where_clauses_evaluated = true;
  6764. }
  6765. return data;
  6766. }
  6767. } else {
  6768. Ast *ident = operand->expr;
  6769. while (ident->kind == Ast_SelectorExpr) {
  6770. Ast *s = ident->SelectorExpr.selector;
  6771. ident = s;
  6772. }
  6773. Entity *e = entity_of_node(ident);
  6774. CallArgumentData data = {};
  6775. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  6776. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  6777. add_entity_use(c, ident, entity_to_use);
  6778. if (entity_to_use != nullptr) {
  6779. update_expr_type(c, operand->expr, entity_to_use->type, true);
  6780. }
  6781. if (data.gen_entity != nullptr) {
  6782. Entity *e = data.gen_entity;
  6783. DeclInfo *decl = data.gen_entity->decl_info;
  6784. CheckerContext ctx = *c;
  6785. ctx.scope = decl->scope;
  6786. ctx.decl = decl;
  6787. ctx.proc_name = e->token.string;
  6788. ctx.curr_proc_decl = decl;
  6789. ctx.curr_proc_sig = e->type;
  6790. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6791. evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  6792. decl->where_clauses_evaluated = true;
  6793. }
  6794. return data;
  6795. }
  6796. CallArgumentData data = {};
  6797. data.result_type = t_invalid;
  6798. return data;
  6799. }
  6800. isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6801. if (!is_type_polymorphic_record(t)) {
  6802. return -1;
  6803. }
  6804. TypeTuple *params = get_record_polymorphic_params(t);
  6805. if (params == nullptr) {
  6806. return -1;
  6807. }
  6808. for_array(i, params->variables) {
  6809. Entity *e = params->variables[i];
  6810. String name = e->token.string;
  6811. if (is_blank_ident(name)) {
  6812. continue;
  6813. }
  6814. if (name == parameter_name) {
  6815. return i;
  6816. }
  6817. }
  6818. return -1;
  6819. }
  6820. CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6821. ast_node(ce, CallExpr, call);
  6822. Type *original_type = operand->type;
  6823. GB_ASSERT(is_type_polymorphic_record(original_type));
  6824. bool show_error = true;
  6825. Array<Operand> operands = {};
  6826. defer (array_free(&operands));
  6827. bool named_fields = false;
  6828. {
  6829. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6830. auto prev_type_path = c->type_path;
  6831. c->type_path = new_checker_type_path();
  6832. defer ({
  6833. destroy_checker_type_path(c->type_path);
  6834. c->type_path = prev_type_path;
  6835. });
  6836. if (is_call_expr_field_value(ce)) {
  6837. named_fields = true;
  6838. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6839. for_array(i, ce->args) {
  6840. Ast *arg = ce->args[i];
  6841. ast_node(fv, FieldValue, arg);
  6842. if (fv->field->kind == Ast_Ident) {
  6843. String name = fv->field->Ident.token.string;
  6844. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6845. if (index >= 0) {
  6846. TypeTuple *params = get_record_polymorphic_params(original_type);
  6847. Entity *e = params->variables[i];
  6848. if (e->kind == Entity_Constant) {
  6849. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6850. continue;
  6851. }
  6852. }
  6853. }
  6854. check_expr_or_type(c, &operands[i], fv->value);
  6855. }
  6856. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6857. if (vari_expand) {
  6858. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6859. }
  6860. } else {
  6861. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6862. Entity **lhs = nullptr;
  6863. isize lhs_count = -1;
  6864. TypeTuple *params = get_record_polymorphic_params(original_type);
  6865. if (params != nullptr) {
  6866. lhs = params->variables.data;
  6867. lhs_count = params->variables.count;
  6868. }
  6869. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, false, false);
  6870. }
  6871. }
  6872. CallArgumentError err = CallArgumentError_None;
  6873. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6874. isize param_count = tuple->variables.count;
  6875. isize minimum_param_count = param_count;
  6876. for (minimum_param_count = tuple->variables.count-1; minimum_param_count >= 0; minimum_param_count--) {
  6877. Entity *e = tuple->variables[minimum_param_count];
  6878. if (e->kind != Entity_Constant) {
  6879. break;
  6880. }
  6881. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6882. break;
  6883. }
  6884. }
  6885. Array<Operand> ordered_operands = operands;
  6886. if (!named_fields) {
  6887. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6888. array_copy(&ordered_operands, operands, 0);
  6889. } else {
  6890. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6891. // LEAK(bill)
  6892. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6893. for_array(i, ce->args) {
  6894. Ast *arg = ce->args[i];
  6895. ast_node(fv, FieldValue, arg);
  6896. if (fv->field->kind != Ast_Ident) {
  6897. if (show_error) {
  6898. gbString expr_str = expr_to_string(fv->field);
  6899. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6900. gb_string_free(expr_str);
  6901. }
  6902. err = CallArgumentError_InvalidFieldValue;
  6903. continue;
  6904. }
  6905. String name = fv->field->Ident.token.string;
  6906. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6907. if (index < 0) {
  6908. if (show_error) {
  6909. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6910. }
  6911. err = CallArgumentError_ParameterNotFound;
  6912. continue;
  6913. }
  6914. if (visited[index]) {
  6915. if (show_error) {
  6916. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6917. }
  6918. err = CallArgumentError_DuplicateParameter;
  6919. continue;
  6920. }
  6921. visited[index] = true;
  6922. ordered_operands[index] = operands[i];
  6923. }
  6924. for (isize i = 0; i < param_count; i++) {
  6925. if (!visited[i]) {
  6926. Entity *e = tuple->variables[i];
  6927. if (is_blank_ident(e->token)) {
  6928. continue;
  6929. }
  6930. if (show_error) {
  6931. if (e->kind == Entity_TypeName) {
  6932. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6933. LIT(e->token.string));
  6934. } else {
  6935. gbString str = type_to_string(e->type);
  6936. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6937. LIT(e->token.string), str);
  6938. gb_string_free(str);
  6939. }
  6940. }
  6941. err = CallArgumentError_ParameterMissing;
  6942. }
  6943. }
  6944. }
  6945. if (err != 0) {
  6946. operand->mode = Addressing_Invalid;
  6947. return err;
  6948. }
  6949. if (minimum_param_count != param_count) {
  6950. if (param_count < ordered_operands.count) {
  6951. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6952. err = CallArgumentError_TooManyArguments;
  6953. } else if (minimum_param_count > ordered_operands.count) {
  6954. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6955. err = CallArgumentError_TooFewArguments;
  6956. }
  6957. } else {
  6958. if (param_count < ordered_operands.count) {
  6959. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6960. err = CallArgumentError_TooManyArguments;
  6961. } else if (param_count > ordered_operands.count) {
  6962. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6963. err = CallArgumentError_TooFewArguments;
  6964. }
  6965. }
  6966. if (err != 0) {
  6967. return err;
  6968. }
  6969. if (minimum_param_count != param_count) {
  6970. isize missing_count = 0;
  6971. // NOTE(bill): Replace missing operands with the default values (if possible)
  6972. for_array(i, ordered_operands) {
  6973. Operand *o = &ordered_operands[i];
  6974. if (o->expr == nullptr) {
  6975. Entity *e = tuple->variables[i];
  6976. if (e->kind == Entity_Constant) {
  6977. missing_count += 1;
  6978. o->mode = Addressing_Constant;
  6979. o->type = default_type(e->type);
  6980. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6981. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6982. o->value = e->Constant.param_value.value;
  6983. }
  6984. }
  6985. }
  6986. }
  6987. }
  6988. i64 score = 0;
  6989. for (isize i = 0; i < param_count; i++) {
  6990. Entity *e = tuple->variables[i];
  6991. Operand *o = &ordered_operands[i];
  6992. if (o->mode == Addressing_Invalid) {
  6993. continue;
  6994. }
  6995. if (e->kind == Entity_TypeName) {
  6996. if (o->mode != Addressing_Type) {
  6997. if (show_error) {
  6998. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  6999. }
  7000. err = CallArgumentError_WrongTypes;
  7001. }
  7002. if (are_types_identical(e->type, o->type)) {
  7003. score += assign_score_function(1);
  7004. } else {
  7005. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  7006. }
  7007. } else {
  7008. i64 s = 0;
  7009. if (o->type->kind == Type_Generic) {
  7010. // Polymorphic name!
  7011. score += assign_score_function(1);
  7012. continue;
  7013. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  7014. if (show_error) {
  7015. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  7016. }
  7017. err = CallArgumentError_WrongTypes;
  7018. }
  7019. o->type = e->type;
  7020. if (o->mode != Addressing_Constant) {
  7021. bool valid = false;
  7022. if (is_type_proc(o->type)) {
  7023. Entity *proc_entity = entity_from_expr(o->expr);
  7024. valid = proc_entity != nullptr;
  7025. }
  7026. if (!valid) {
  7027. if (show_error) {
  7028. error(o->expr, "Expected a constant value for this polymorphic type argument");
  7029. }
  7030. err = CallArgumentError_NoneConstantParameter;
  7031. }
  7032. }
  7033. score += s;
  7034. }
  7035. // NOTE(bill): Add type info the parameters
  7036. add_type_info_type(c, o->type);
  7037. }
  7038. {
  7039. bool failure = false;
  7040. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  7041. if (found_entity) {
  7042. operand->mode = Addressing_Type;
  7043. operand->type = found_entity->type;
  7044. return err;
  7045. }
  7046. String generated_name = make_string_c(expr_to_string(call));
  7047. CheckerContext ctx = *c;
  7048. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  7049. ctx.scope = polymorphic_record_parent_scope(original_type);
  7050. GB_ASSERT(ctx.scope != nullptr);
  7051. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  7052. Type *bt = base_type(original_type);
  7053. if (bt->kind == Type_Struct) {
  7054. Ast *node = clone_ast(bt->Struct.node);
  7055. Type *struct_type = alloc_type_struct();
  7056. struct_type->Struct.node = node;
  7057. struct_type->Struct.polymorphic_parent = original_type;
  7058. set_base_type(named_type, struct_type);
  7059. check_open_scope(&ctx, node);
  7060. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  7061. check_close_scope(&ctx);
  7062. } else if (bt->kind == Type_Union) {
  7063. Ast *node = clone_ast(bt->Union.node);
  7064. Type *union_type = alloc_type_union();
  7065. union_type->Union.node = node;
  7066. union_type->Union.polymorphic_parent = original_type;
  7067. set_base_type(named_type, union_type);
  7068. check_open_scope(&ctx, node);
  7069. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  7070. check_close_scope(&ctx);
  7071. } else {
  7072. GB_PANIC("Unsupported parametric polymorphic record type");
  7073. }
  7074. operand->mode = Addressing_Type;
  7075. operand->type = named_type;
  7076. }
  7077. return err;
  7078. }
  7079. ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  7080. if (proc != nullptr &&
  7081. proc->kind == Ast_BasicDirective) {
  7082. ast_node(bd, BasicDirective, proc);
  7083. String name = bd->name;
  7084. if (name == "location" || name == "assert" || name == "panic" || name == "defined" || name == "config" || name == "load") {
  7085. operand->mode = Addressing_Builtin;
  7086. operand->builtin_id = BuiltinProc_DIRECTIVE;
  7087. operand->expr = proc;
  7088. operand->type = t_invalid;
  7089. add_type_and_value(&c->checker->info, proc, operand->mode, operand->type, operand->value);
  7090. } else {
  7091. GB_PANIC("Unhandled #%.*s", LIT(name));
  7092. }
  7093. if (inlining != ProcInlining_none) {
  7094. error(call, "Inlining operators are not allowed on built-in procedures");
  7095. }
  7096. } else {
  7097. if (proc != nullptr) {
  7098. check_expr_or_type(c, operand, proc);
  7099. } else {
  7100. GB_ASSERT(operand->expr != nullptr);
  7101. }
  7102. }
  7103. if (args.count > 0) {
  7104. bool fail = false;
  7105. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  7106. for_array(i, args) {
  7107. Ast *arg = args[i];
  7108. bool mix = false;
  7109. if (first_is_field_value) {
  7110. mix = arg->kind != Ast_FieldValue;
  7111. } else {
  7112. mix = arg->kind == Ast_FieldValue;
  7113. }
  7114. if (mix) {
  7115. error(arg, "Mixture of 'field = value' and value elements in a procedure call is not allowed");
  7116. fail = true;
  7117. }
  7118. }
  7119. if (fail) {
  7120. operand->mode = Addressing_Invalid;
  7121. operand->expr = call;
  7122. return Expr_Stmt;
  7123. }
  7124. }
  7125. if (operand->mode == Addressing_Invalid) {
  7126. for_array(i, args) {
  7127. Ast *arg = args[i];
  7128. if (arg->kind == Ast_FieldValue) {
  7129. arg = arg->FieldValue.value;
  7130. }
  7131. check_expr_base(c, operand, arg, nullptr);
  7132. }
  7133. operand->mode = Addressing_Invalid;
  7134. operand->expr = call;
  7135. return Expr_Stmt;
  7136. }
  7137. if (operand->mode == Addressing_Type) {
  7138. Type *t = operand->type;
  7139. if (is_type_polymorphic_record(t)) {
  7140. auto err = check_polymorphic_record_type(c, operand, call);
  7141. if (err == 0) {
  7142. Ast *ident = operand->expr;
  7143. while (ident->kind == Ast_SelectorExpr) {
  7144. Ast *s = ident->SelectorExpr.selector;
  7145. ident = s;
  7146. }
  7147. Type *ot = operand->type;
  7148. GB_ASSERT(ot->kind == Type_Named);
  7149. Entity *e = ot->Named.type_name;
  7150. add_entity_use(c, ident, e);
  7151. add_type_and_value(&c->checker->info, call, Addressing_Type, ot, empty_exact_value);
  7152. } else {
  7153. operand->mode = Addressing_Invalid;
  7154. operand->type = t_invalid;
  7155. }
  7156. } else {
  7157. gbString str = type_to_string(t);
  7158. defer (gb_string_free(str));
  7159. operand->mode = Addressing_Invalid;
  7160. isize arg_count = args.count;
  7161. switch (arg_count) {
  7162. case 0: error(call, "Missing argument in conversion to '%s'", str); break;
  7163. default: error(call, "Too many arguments in conversion to '%s'", str); break;
  7164. case 1: {
  7165. Ast *arg = args[0];
  7166. if (arg->kind == Ast_FieldValue) {
  7167. error(call, "'field = value' cannot be used in a type conversion");
  7168. arg = arg->FieldValue.value;
  7169. // NOTE(bill): Carry on the cast regardless
  7170. }
  7171. check_expr(c, operand, arg);
  7172. if (operand->mode != Addressing_Invalid) {
  7173. check_cast(c, operand, t);
  7174. }
  7175. break;
  7176. }
  7177. }
  7178. }
  7179. return Expr_Expr;
  7180. }
  7181. if (operand->mode == Addressing_Builtin) {
  7182. i32 id = operand->builtin_id;
  7183. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7184. operand->mode = Addressing_Invalid;
  7185. operand->type = t_invalid;
  7186. }
  7187. operand->expr = call;
  7188. return builtin_procs[id].kind;
  7189. }
  7190. Entity *e = entity_of_node(operand->expr);
  7191. if (e != nullptr && e->kind == Entity_Procedure) {
  7192. if (e->Procedure.deferred_procedure.entity != nullptr) {
  7193. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7194. }
  7195. }
  7196. Type *proc_type = base_type(operand->type);
  7197. if (operand->mode != Addressing_ProcGroup) {
  7198. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7199. bool valid_mode = is_operand_value(*operand);
  7200. if (!valid_type || !valid_mode) {
  7201. Ast *e = operand->expr;
  7202. gbString str = expr_to_string(e);
  7203. gbString type_str = type_to_string(operand->type);
  7204. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7205. gb_string_free(type_str);
  7206. gb_string_free(str);
  7207. operand->mode = Addressing_Invalid;
  7208. operand->expr = call;
  7209. return Expr_Stmt;
  7210. }
  7211. }
  7212. CallArgumentData data = check_call_arguments(c, operand, proc_type, call, args);
  7213. Type *result_type = data.result_type;
  7214. gb_zero_item(operand);
  7215. operand->expr = call;
  7216. if (result_type == t_invalid) {
  7217. operand->mode = Addressing_Invalid;
  7218. operand->type = t_invalid;
  7219. return Expr_Stmt;
  7220. }
  7221. Type *pt = base_type(proc_type);
  7222. if (pt == t_invalid) {
  7223. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7224. pt = type_of_expr(operand->expr->CallExpr.proc);
  7225. }
  7226. if (pt == t_invalid && data.gen_entity) {
  7227. pt = data.gen_entity->type;
  7228. }
  7229. }
  7230. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7231. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7232. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7233. }
  7234. }
  7235. if (result_type == nullptr) {
  7236. operand->mode = Addressing_NoValue;
  7237. } else {
  7238. GB_ASSERT(is_type_tuple(result_type));
  7239. isize count = result_type->Tuple.variables.count;
  7240. switch (count) {
  7241. case 0:
  7242. operand->mode = Addressing_NoValue;
  7243. break;
  7244. case 1:
  7245. operand->mode = Addressing_Value;
  7246. operand->type = result_type->Tuple.variables[0]->type;
  7247. break;
  7248. default:
  7249. operand->mode = Addressing_Value;
  7250. operand->type = result_type;
  7251. break;
  7252. }
  7253. }
  7254. switch (inlining) {
  7255. case ProcInlining_inline:
  7256. if (proc != nullptr) {
  7257. Entity *e = entity_from_expr(proc);
  7258. if (e != nullptr && e->kind == Entity_Procedure) {
  7259. DeclInfo *decl = e->decl_info;
  7260. if (decl->proc_lit) {
  7261. ast_node(pl, ProcLit, decl->proc_lit);
  7262. if (pl->inlining == ProcInlining_no_inline) {
  7263. error(call, "'inline' cannot be applied to a procedure that has be marked as 'no_inline'");
  7264. }
  7265. }
  7266. }
  7267. }
  7268. break;
  7269. case ProcInlining_no_inline:
  7270. break;
  7271. }
  7272. operand->expr = call;
  7273. {
  7274. if (proc_type == t_invalid) {
  7275. // gb_printf_err("%s\n", expr_to_string(operand->expr));
  7276. }
  7277. Type *type = nullptr;
  7278. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7279. type = type_of_expr(operand->expr->CallExpr.proc);
  7280. }
  7281. if (type == nullptr) {
  7282. type = pt;
  7283. }
  7284. type = base_type(type);
  7285. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  7286. operand->mode = Addressing_OptionalOk;
  7287. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7288. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7289. operand->expr->CallExpr.optional_ok_one = true;
  7290. }
  7291. }
  7292. }
  7293. // add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  7294. return Expr_Expr;
  7295. }
  7296. void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7297. check_expr_base(c, o, e, t);
  7298. check_not_tuple(c, o);
  7299. char const *err_str = nullptr;
  7300. switch (o->mode) {
  7301. case Addressing_NoValue:
  7302. err_str = "used as a value";
  7303. break;
  7304. case Addressing_Type:
  7305. if (t == nullptr || !is_type_typeid(t)) {
  7306. err_str = "is not an expression but a type";
  7307. }
  7308. break;
  7309. case Addressing_Builtin:
  7310. err_str = "must be called";
  7311. break;
  7312. }
  7313. if (err_str != nullptr) {
  7314. gbString str = expr_to_string(e);
  7315. error(e, "'%s' %s", str, err_str);
  7316. gb_string_free(str);
  7317. o->mode = Addressing_Invalid;
  7318. }
  7319. }
  7320. bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7321. switch (t->kind) {
  7322. case Type_Basic:
  7323. if (t->Basic.kind == Basic_string) {
  7324. if (o->mode == Addressing_Constant) {
  7325. *max_count = o->value.value_string.len;
  7326. }
  7327. if (o->mode != Addressing_Constant) {
  7328. o->mode = Addressing_Value;
  7329. }
  7330. o->type = t_u8;
  7331. return true;
  7332. } else if (t->Basic.kind == Basic_UntypedString) {
  7333. if (o->mode == Addressing_Constant) {
  7334. *max_count = o->value.value_string.len;
  7335. o->type = t_u8;
  7336. return true;
  7337. }
  7338. return false;
  7339. }
  7340. break;
  7341. case Type_Array:
  7342. *max_count = t->Array.count;
  7343. if (indirection) {
  7344. o->mode = Addressing_Variable;
  7345. } else if (o->mode != Addressing_Variable &&
  7346. o->mode != Addressing_Constant) {
  7347. o->mode = Addressing_Value;
  7348. }
  7349. o->type = t->Array.elem;
  7350. return true;
  7351. case Type_EnumeratedArray:
  7352. *max_count = t->EnumeratedArray.count;
  7353. if (indirection) {
  7354. o->mode = Addressing_Variable;
  7355. } else if (o->mode != Addressing_Variable &&
  7356. o->mode != Addressing_Constant) {
  7357. o->mode = Addressing_Value;
  7358. }
  7359. o->type = t->EnumeratedArray.elem;
  7360. return true;
  7361. case Type_Slice:
  7362. o->type = t->Slice.elem;
  7363. if (o->mode != Addressing_Constant) {
  7364. o->mode = Addressing_Variable;
  7365. }
  7366. return true;
  7367. case Type_RelativeSlice:
  7368. {
  7369. Type *slice_type = base_type(t->RelativeSlice.slice_type);
  7370. GB_ASSERT(slice_type->kind == Type_Slice);
  7371. o->type = slice_type->Slice.elem;
  7372. if (o->mode != Addressing_Constant) {
  7373. o->mode = Addressing_Variable;
  7374. }
  7375. }
  7376. return true;
  7377. case Type_DynamicArray:
  7378. o->type = t->DynamicArray.elem;
  7379. if (o->mode != Addressing_Constant) {
  7380. o->mode = Addressing_Variable;
  7381. }
  7382. return true;
  7383. case Type_Struct:
  7384. if (t->Struct.soa_kind != StructSoa_None) {
  7385. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7386. *max_count = t->Struct.soa_count;
  7387. }
  7388. o->type = t->Struct.soa_elem;
  7389. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  7390. o->mode = Addressing_SoaVariable;
  7391. } else {
  7392. o->mode = Addressing_Value;
  7393. }
  7394. return true;
  7395. }
  7396. return false;
  7397. }
  7398. if (is_type_pointer(original_type) && indirection) {
  7399. Type *ptr = base_type(original_type);
  7400. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  7401. o->type = ptr->Pointer.elem;
  7402. o->mode = Addressing_Value;
  7403. return true;
  7404. }
  7405. }
  7406. return false;
  7407. }
  7408. bool ternary_compare_types(Type *x, Type *y) {
  7409. if (is_type_untyped_undef(x) && type_has_undef(y)) {
  7410. return true;
  7411. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7412. return true;
  7413. } else if (is_type_untyped_undef(y) && type_has_undef(x)) {
  7414. return true;
  7415. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7416. return true;
  7417. }
  7418. return are_types_identical(x, y);
  7419. }
  7420. bool check_range(CheckerContext *c, Ast *node, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  7421. if (!is_ast_range(node)) {
  7422. return false;
  7423. }
  7424. ast_node(ie, BinaryExpr, node);
  7425. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7426. if (x->mode == Addressing_Invalid) {
  7427. return false;
  7428. }
  7429. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7430. if (y->mode == Addressing_Invalid) {
  7431. return false;
  7432. }
  7433. convert_to_typed(c, x, y->type);
  7434. if (x->mode == Addressing_Invalid) {
  7435. return false;
  7436. }
  7437. convert_to_typed(c, y, x->type);
  7438. if (y->mode == Addressing_Invalid) {
  7439. return false;
  7440. }
  7441. convert_to_typed(c, x, default_type(y->type));
  7442. if (x->mode == Addressing_Invalid) {
  7443. return false;
  7444. }
  7445. convert_to_typed(c, y, default_type(x->type));
  7446. if (y->mode == Addressing_Invalid) {
  7447. return false;
  7448. }
  7449. if (!are_types_identical(x->type, y->type)) {
  7450. if (x->type != t_invalid &&
  7451. y->type != t_invalid) {
  7452. gbString xt = type_to_string(x->type);
  7453. gbString yt = type_to_string(y->type);
  7454. gbString expr_str = expr_to_string(x->expr);
  7455. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7456. gb_string_free(expr_str);
  7457. gb_string_free(yt);
  7458. gb_string_free(xt);
  7459. }
  7460. return false;
  7461. }
  7462. Type *type = x->type;
  7463. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7464. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7465. return false;
  7466. }
  7467. if (x->mode == Addressing_Constant &&
  7468. y->mode == Addressing_Constant) {
  7469. ExactValue a = x->value;
  7470. ExactValue b = y->value;
  7471. GB_ASSERT(are_types_identical(x->type, y->type));
  7472. TokenKind op = Token_Lt;
  7473. switch (ie->op.kind) {
  7474. case Token_Ellipsis: op = Token_LtEq; break;
  7475. case Token_RangeHalf: op = Token_Lt; break;
  7476. default: error(ie->op, "Invalid range operator"); break;
  7477. }
  7478. bool ok = compare_exact_values(op, a, b);
  7479. if (!ok) {
  7480. // TODO(bill): Better error message
  7481. error(ie->op, "Invalid interval range");
  7482. return false;
  7483. }
  7484. ExactValue inline_for_depth = exact_value_sub(b, a);
  7485. if (ie->op.kind == Token_Ellipsis) {
  7486. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7487. }
  7488. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7489. } else if (inline_for_depth_ != nullptr) {
  7490. error(ie->op, "Interval expressions must be constant");
  7491. return false;
  7492. }
  7493. add_type_and_value(&c->checker->info, ie->left, x->mode, x->type, x->value);
  7494. add_type_and_value(&c->checker->info, ie->right, y->mode, y->type, y->value);
  7495. return true;
  7496. }
  7497. bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7498. if (is_operand_nil(*o)) {
  7499. return true;
  7500. }
  7501. Ast *expr = unparen_expr(o->expr);
  7502. if (expr != nullptr) {
  7503. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7504. if (e != nullptr && e->kind == Entity_Procedure) {
  7505. return true;
  7506. }
  7507. if (expr->kind == Ast_ProcLit) {
  7508. add_type_and_value(c->info, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7509. return true;
  7510. }
  7511. }
  7512. return o->mode == Addressing_Constant;
  7513. }
  7514. ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7515. u32 prev_state_flags = c->state_flags;
  7516. defer (c->state_flags = prev_state_flags);
  7517. if (node->state_flags != 0) {
  7518. u32 in = node->state_flags;
  7519. u32 out = c->state_flags;
  7520. if (in & StateFlag_no_bounds_check) {
  7521. out |= StateFlag_no_bounds_check;
  7522. out &= ~StateFlag_bounds_check;
  7523. } else if (in & StateFlag_bounds_check) {
  7524. out |= StateFlag_bounds_check;
  7525. out &= ~StateFlag_no_bounds_check;
  7526. }
  7527. c->state_flags = out;
  7528. }
  7529. ExprKind kind = Expr_Stmt;
  7530. o->mode = Addressing_Invalid;
  7531. o->type = t_invalid;
  7532. switch (node->kind) {
  7533. default:
  7534. return kind;
  7535. case_ast_node(be, BadExpr, node)
  7536. return kind;
  7537. case_end;
  7538. case_ast_node(i, Implicit, node)
  7539. switch (i->kind) {
  7540. case Token_context:
  7541. {
  7542. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  7543. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  7544. return kind;
  7545. }
  7546. if (unparen_expr(c->assignment_lhs_hint) == node) {
  7547. c->scope->flags |= ScopeFlag_ContextDefined;
  7548. }
  7549. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7550. error(node, "'context' has not been defined within this scope");
  7551. // Continue with value
  7552. }
  7553. init_core_context(c->checker);
  7554. o->mode = Addressing_Context;
  7555. o->type = t_context;
  7556. }
  7557. break;
  7558. default:
  7559. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  7560. return kind;
  7561. }
  7562. case_end;
  7563. case_ast_node(i, Ident, node);
  7564. check_ident(c, o, node, nullptr, type_hint, false);
  7565. case_end;
  7566. case_ast_node(u, Undef, node);
  7567. o->mode = Addressing_Value;
  7568. o->type = t_untyped_undef;
  7569. case_end;
  7570. case_ast_node(bl, BasicLit, node);
  7571. Type *t = t_invalid;
  7572. switch (node->tav.value.kind) {
  7573. case ExactValue_String: t = t_untyped_string; break;
  7574. case ExactValue_Float: t = t_untyped_float; break;
  7575. case ExactValue_Complex: t = t_untyped_complex; break;
  7576. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  7577. case ExactValue_Integer:
  7578. t = t_untyped_integer;
  7579. if (bl->token.kind == Token_Rune) {
  7580. t = t_untyped_rune;
  7581. }
  7582. break;
  7583. default:
  7584. GB_PANIC("Unhandled value type for basic literal");
  7585. break;
  7586. }
  7587. o->mode = Addressing_Constant;
  7588. o->type = t;
  7589. o->value = node->tav.value;
  7590. case_end;
  7591. case_ast_node(bd, BasicDirective, node);
  7592. o->mode = Addressing_Constant;
  7593. if (bd->name == "file") {
  7594. o->type = t_untyped_string;
  7595. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  7596. } else if (bd->name == "line") {
  7597. o->type = t_untyped_integer;
  7598. o->value = exact_value_i64(bd->token.pos.line);
  7599. } else if (bd->name == "procedure") {
  7600. if (c->curr_proc_decl == nullptr) {
  7601. error(node, "#procedure may only be used within procedures");
  7602. o->type = t_untyped_string;
  7603. o->value = exact_value_string(str_lit(""));
  7604. } else {
  7605. o->type = t_untyped_string;
  7606. o->value = exact_value_string(c->proc_name);
  7607. }
  7608. } else if (bd->name == "caller_location") {
  7609. init_core_source_code_location(c->checker);
  7610. error(node, "#caller_location may only be used as a default argument parameter");
  7611. o->type = t_source_code_location;
  7612. o->mode = Addressing_Value;
  7613. } else {
  7614. GB_PANIC("Unknown basic directive");
  7615. }
  7616. case_end;
  7617. case_ast_node(pg, ProcGroup, node);
  7618. error(node, "Illegal use of a procedure group");
  7619. o->mode = Addressing_Invalid;
  7620. case_end;
  7621. case_ast_node(pl, ProcLit, node);
  7622. CheckerContext ctx = *c;
  7623. DeclInfo *decl = nullptr;
  7624. Type *type = alloc_type(Type_Proc);
  7625. check_open_scope(&ctx, pl->type);
  7626. {
  7627. decl = make_decl_info(ctx.scope, ctx.decl);
  7628. decl->proc_lit = node;
  7629. ctx.decl = decl;
  7630. defer (ctx.decl = ctx.decl->parent);
  7631. if (pl->tags != 0) {
  7632. error(node, "A procedure literal cannot have tags");
  7633. pl->tags = 0; // TODO(bill): Should I zero this?!
  7634. }
  7635. check_procedure_type(&ctx, type, pl->type);
  7636. if (!is_type_proc(type)) {
  7637. gbString str = expr_to_string(node);
  7638. error(node, "Invalid procedure literal '%s'", str);
  7639. gb_string_free(str);
  7640. check_close_scope(&ctx);
  7641. return kind;
  7642. }
  7643. if (pl->body == nullptr) {
  7644. error(node, "A procedure literal must have a body");
  7645. return kind;
  7646. }
  7647. pl->decl = decl;
  7648. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  7649. }
  7650. check_close_scope(&ctx);
  7651. o->mode = Addressing_Value;
  7652. o->type = type;
  7653. case_end;
  7654. case_ast_node(te, TernaryExpr, node);
  7655. Operand cond = {Addressing_Invalid};
  7656. check_expr(c, &cond, te->cond);
  7657. node->viral_state_flags |= te->cond->viral_state_flags;
  7658. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7659. error(te->cond, "Non-boolean condition in if expression");
  7660. }
  7661. Operand x = {Addressing_Invalid};
  7662. Operand y = {Addressing_Invalid};
  7663. check_expr_or_type(c, &x, te->x, type_hint);
  7664. node->viral_state_flags |= te->x->viral_state_flags;
  7665. if (te->y != nullptr) {
  7666. check_expr_or_type(c, &y, te->y, type_hint);
  7667. node->viral_state_flags |= te->y->viral_state_flags;
  7668. } else {
  7669. error(node, "A ternary expression must have an else clause");
  7670. return kind;
  7671. }
  7672. if (x.type == nullptr || x.type == t_invalid ||
  7673. y.type == nullptr || y.type == t_invalid) {
  7674. return kind;
  7675. }
  7676. if (x.mode == Addressing_Type && y.mode == Addressing_Type &&
  7677. cond.mode == Addressing_Constant && is_type_boolean(cond.type)) {
  7678. o->mode = Addressing_Type;
  7679. if (cond.value.value_bool) {
  7680. o->type = x.type;
  7681. o->expr = x.expr;
  7682. } else {
  7683. o->type = y.type;
  7684. o->expr = y.expr;
  7685. }
  7686. return Expr_Expr;
  7687. }
  7688. convert_to_typed(c, &x, y.type);
  7689. if (x.mode == Addressing_Invalid) {
  7690. return kind;
  7691. }
  7692. convert_to_typed(c, &y, x.type);
  7693. if (y.mode == Addressing_Invalid) {
  7694. x.mode = Addressing_Invalid;
  7695. return kind;
  7696. }
  7697. if (!ternary_compare_types(x.type, y.type)) {
  7698. gbString its = type_to_string(x.type);
  7699. gbString ets = type_to_string(y.type);
  7700. error(node, "Mismatched types in ternary expression, %s vs %s", its, ets);
  7701. gb_string_free(ets);
  7702. gb_string_free(its);
  7703. return kind;
  7704. }
  7705. Type *type = x.type;
  7706. if (is_type_untyped_nil(type) || is_type_untyped_undef(type)) {
  7707. type = y.type;
  7708. }
  7709. o->type = type;
  7710. o->mode = Addressing_Value;
  7711. if (cond.mode == Addressing_Constant && is_type_boolean(cond.type) &&
  7712. x.mode == Addressing_Constant &&
  7713. y.mode == Addressing_Constant) {
  7714. o->mode = Addressing_Constant;
  7715. if (cond.value.value_bool) {
  7716. o->value = x.value;
  7717. } else {
  7718. o->value = y.value;
  7719. }
  7720. }
  7721. case_end;
  7722. case_ast_node(te, TernaryIfExpr, node);
  7723. Operand cond = {Addressing_Invalid};
  7724. check_expr(c, &cond, te->cond);
  7725. node->viral_state_flags |= te->cond->viral_state_flags;
  7726. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7727. error(te->cond, "Non-boolean condition in ternary if expression");
  7728. }
  7729. Operand x = {Addressing_Invalid};
  7730. Operand y = {Addressing_Invalid};
  7731. check_expr_or_type(c, &x, te->x, type_hint);
  7732. node->viral_state_flags |= te->x->viral_state_flags;
  7733. if (te->y != nullptr) {
  7734. check_expr_or_type(c, &y, te->y, type_hint);
  7735. node->viral_state_flags |= te->y->viral_state_flags;
  7736. } else {
  7737. error(node, "A ternary expression must have an else clause");
  7738. return kind;
  7739. }
  7740. if (x.type == nullptr || x.type == t_invalid ||
  7741. y.type == nullptr || y.type == t_invalid) {
  7742. return kind;
  7743. }
  7744. convert_to_typed(c, &x, y.type);
  7745. if (x.mode == Addressing_Invalid) {
  7746. return kind;
  7747. }
  7748. convert_to_typed(c, &y, x.type);
  7749. if (y.mode == Addressing_Invalid) {
  7750. x.mode = Addressing_Invalid;
  7751. return kind;
  7752. }
  7753. if (!ternary_compare_types(x.type, y.type)) {
  7754. gbString its = type_to_string(x.type);
  7755. gbString ets = type_to_string(y.type);
  7756. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7757. gb_string_free(ets);
  7758. gb_string_free(its);
  7759. return kind;
  7760. }
  7761. Type *type = x.type;
  7762. if (is_type_untyped_nil(type) || is_type_untyped_undef(type)) {
  7763. type = y.type;
  7764. }
  7765. o->type = type;
  7766. o->mode = Addressing_Value;
  7767. // if (cond.mode == Addressing_Constant && is_type_boolean(cond.type) &&
  7768. // x.mode == Addressing_Constant &&
  7769. // y.mode == Addressing_Constant) {
  7770. // o->mode = Addressing_Constant;
  7771. // if (cond.value.value_bool) {
  7772. // o->value = x.value;
  7773. // } else {
  7774. // o->value = y.value;
  7775. // }
  7776. // }
  7777. case_end;
  7778. case_ast_node(te, TernaryWhenExpr, node);
  7779. Operand cond = {};
  7780. check_expr(c, &cond, te->cond);
  7781. node->viral_state_flags |= te->cond->viral_state_flags;
  7782. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7783. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7784. return kind;
  7785. }
  7786. if (cond.value.value_bool) {
  7787. check_expr_or_type(c, o, te->x, type_hint);
  7788. node->viral_state_flags |= te->x->viral_state_flags;
  7789. } else {
  7790. if (te->y != nullptr) {
  7791. check_expr_or_type(c, o, te->y, type_hint);
  7792. node->viral_state_flags |= te->y->viral_state_flags;
  7793. } else {
  7794. error(node, "A ternary when expression must have an else clause");
  7795. return kind;
  7796. }
  7797. }
  7798. case_end;
  7799. case_ast_node(cl, CompoundLit, node);
  7800. Type *type = type_hint;
  7801. bool is_to_be_determined_array_count = false;
  7802. bool is_constant = true;
  7803. if (cl->type != nullptr) {
  7804. type = nullptr;
  7805. // [?]Type
  7806. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  7807. Ast *count = cl->type->ArrayType.count;
  7808. if (count->kind == Ast_UnaryExpr &&
  7809. count->UnaryExpr.op.kind == Token_Question) {
  7810. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  7811. is_to_be_determined_array_count = true;
  7812. }
  7813. if (cl->elems.count > 0) {
  7814. if (cl->type->ArrayType.tag != nullptr) {
  7815. Ast *tag = cl->type->ArrayType.tag;
  7816. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7817. String name = tag->BasicDirective.name;
  7818. if (name == "soa") {
  7819. error(node, "#soa arrays are not supported for compound literals");
  7820. return kind;
  7821. }
  7822. }
  7823. }
  7824. }
  7825. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  7826. if (cl->elems.count > 0) {
  7827. Ast *tag = cl->type->DynamicArrayType.tag;
  7828. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7829. String name = tag->BasicDirective.name;
  7830. if (name == "soa") {
  7831. error(node, "#soa arrays are not supported for compound literals");
  7832. return kind;
  7833. }
  7834. }
  7835. }
  7836. if (type == nullptr) {
  7837. type = check_type(c, cl->type);
  7838. }
  7839. }
  7840. if (type == nullptr) {
  7841. error(node, "Missing type in compound literal");
  7842. return kind;
  7843. }
  7844. Type *t = base_type(type);
  7845. if (is_type_polymorphic(t)) {
  7846. gbString str = type_to_string(type);
  7847. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7848. o->expr = node;
  7849. o->type = type;
  7850. gb_string_free(str);
  7851. return kind;
  7852. }
  7853. switch (t->kind) {
  7854. case Type_Struct: {
  7855. if (cl->elems.count == 0) {
  7856. break; // NOTE(bill): No need to init
  7857. }
  7858. if (t->Struct.is_raw_union) {
  7859. if (cl->elems.count != 0) {
  7860. gbString type_str = type_to_string(type);
  7861. error(node, "Illegal compound literal type '%s'", type_str);
  7862. gb_string_free(type_str);
  7863. }
  7864. break;
  7865. }
  7866. isize field_count = t->Struct.fields.count;
  7867. isize min_field_count = t->Struct.fields.count;
  7868. for (isize i = min_field_count-1; i >= 0; i--) {
  7869. Entity *e = t->Struct.fields[i];
  7870. GB_ASSERT(e->kind == Entity_Variable);
  7871. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7872. min_field_count--;
  7873. } else {
  7874. break;
  7875. }
  7876. }
  7877. if (cl->elems[0]->kind == Ast_FieldValue) {
  7878. bool *fields_visited = gb_alloc_array(temporary_allocator(), bool, field_count);
  7879. for_array(i, cl->elems) {
  7880. Ast *elem = cl->elems[i];
  7881. if (elem->kind != Ast_FieldValue) {
  7882. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7883. continue;
  7884. }
  7885. ast_node(fv, FieldValue, elem);
  7886. if (fv->field->kind != Ast_Ident) {
  7887. gbString expr_str = expr_to_string(fv->field);
  7888. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7889. gb_string_free(expr_str);
  7890. continue;
  7891. }
  7892. String name = fv->field->Ident.token.string;
  7893. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7894. bool is_unknown = sel.entity == nullptr;
  7895. if (is_unknown) {
  7896. error(elem, "Unknown field '%.*s' in structure literal", LIT(name));
  7897. continue;
  7898. }
  7899. if (sel.index.count > 1) {
  7900. error(elem, "Cannot assign to an anonymous field '%.*s' in a structure literal (at the moment)", LIT(name));
  7901. continue;
  7902. }
  7903. Entity *field = t->Struct.fields[sel.index[0]];
  7904. add_entity_use(c, fv->field, field);
  7905. if (fields_visited[sel.index[0]]) {
  7906. error(elem, "Duplicate field '%.*s' in structure literal", LIT(name));
  7907. continue;
  7908. }
  7909. fields_visited[sel.index[0]] = true;
  7910. Operand o = {};
  7911. check_expr_or_type(c, &o, fv->value, field->type);
  7912. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7913. is_constant = false;
  7914. }
  7915. if (is_constant) {
  7916. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7917. }
  7918. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7919. }
  7920. } else {
  7921. bool seen_field_value = false;
  7922. for_array(index, cl->elems) {
  7923. Entity *field = nullptr;
  7924. Ast *elem = cl->elems[index];
  7925. if (elem->kind == Ast_FieldValue) {
  7926. seen_field_value = true;
  7927. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7928. continue;
  7929. } else if (seen_field_value) {
  7930. error(elem, "Value elements cannot be used after a 'field = value'");
  7931. continue;
  7932. }
  7933. if (index >= field_count) {
  7934. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7935. break;
  7936. }
  7937. if (field == nullptr) {
  7938. field = t->Struct.fields[index];
  7939. }
  7940. Operand o = {};
  7941. check_expr_or_type(c, &o, elem, field->type);
  7942. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7943. is_constant = false;
  7944. }
  7945. if (is_constant) {
  7946. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7947. }
  7948. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7949. }
  7950. if (cl->elems.count < field_count) {
  7951. if (min_field_count < field_count) {
  7952. if (cl->elems.count < min_field_count) {
  7953. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7954. }
  7955. } else {
  7956. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7957. }
  7958. }
  7959. }
  7960. break;
  7961. }
  7962. case Type_Slice:
  7963. case Type_Array:
  7964. case Type_DynamicArray:
  7965. case Type_SimdVector:
  7966. {
  7967. Type *elem_type = nullptr;
  7968. String context_name = {};
  7969. i64 max_type_count = -1;
  7970. if (t->kind == Type_Slice) {
  7971. elem_type = t->Slice.elem;
  7972. context_name = str_lit("slice literal");
  7973. } else if (t->kind == Type_Array) {
  7974. elem_type = t->Array.elem;
  7975. context_name = str_lit("array literal");
  7976. if (!is_to_be_determined_array_count) {
  7977. max_type_count = t->Array.count;
  7978. }
  7979. } else if (t->kind == Type_DynamicArray) {
  7980. elem_type = t->DynamicArray.elem;
  7981. context_name = str_lit("dynamic array literal");
  7982. is_constant = false;
  7983. if (!build_context.no_dynamic_literals) {
  7984. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7985. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7986. }
  7987. } else if (t->kind == Type_SimdVector) {
  7988. elem_type = t->SimdVector.elem;
  7989. context_name = str_lit("simd vector literal");
  7990. max_type_count = t->SimdVector.count;
  7991. } else {
  7992. GB_PANIC("unreachable");
  7993. }
  7994. i64 max = 0;
  7995. Type *bet = base_type(elem_type);
  7996. if (!elem_type_can_be_constant(bet)) {
  7997. is_constant = false;
  7998. }
  7999. if (bet == t_invalid) {
  8000. break;
  8001. }
  8002. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8003. if (is_type_simd_vector(t)) {
  8004. error(cl->elems[0], "'field = value' is not allowed for SIMD vector literals");
  8005. } else {
  8006. RangeCache rc = range_cache_make(heap_allocator());
  8007. defer (range_cache_destroy(&rc));
  8008. for_array(i, cl->elems) {
  8009. Ast *elem = cl->elems[i];
  8010. if (elem->kind != Ast_FieldValue) {
  8011. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8012. continue;
  8013. }
  8014. ast_node(fv, FieldValue, elem);
  8015. if (is_ast_range(fv->field)) {
  8016. Token op = fv->field->BinaryExpr.op;
  8017. Operand x = {};
  8018. Operand y = {};
  8019. bool ok = check_range(c, fv->field, &x, &y, nullptr);
  8020. if (!ok) {
  8021. continue;
  8022. }
  8023. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8024. error(x.expr, "Expected a constant integer as an array field");
  8025. continue;
  8026. }
  8027. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8028. error(y.expr, "Expected a constant integer as an array field");
  8029. continue;
  8030. }
  8031. i64 lo = exact_value_to_i64(x.value);
  8032. i64 hi = exact_value_to_i64(y.value);
  8033. i64 max_index = hi;
  8034. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8035. hi -= 1;
  8036. } else { // .. (inclusive)
  8037. max_index += 1;
  8038. }
  8039. bool new_range = range_cache_add_range(&rc, lo, hi);
  8040. if (!new_range) {
  8041. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8042. continue;
  8043. }
  8044. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8045. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8046. continue;
  8047. }
  8048. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8049. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8050. continue;
  8051. }
  8052. if (max < hi) {
  8053. max = max_index;
  8054. }
  8055. Operand operand = {};
  8056. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8057. check_assignment(c, &operand, elem_type, context_name);
  8058. is_constant = is_constant && operand.mode == Addressing_Constant;
  8059. } else {
  8060. Operand op_index = {};
  8061. check_expr(c, &op_index, fv->field);
  8062. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8063. error(elem, "Expected a constant integer as an array field");
  8064. continue;
  8065. }
  8066. // add_type_and_value(c->info, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8067. i64 index = exact_value_to_i64(op_index.value);
  8068. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8069. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8070. continue;
  8071. }
  8072. bool new_index = range_cache_add_index(&rc, index);
  8073. if (!new_index) {
  8074. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8075. continue;
  8076. }
  8077. if (max < index+1) {
  8078. max = index+1;
  8079. }
  8080. Operand operand = {};
  8081. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8082. check_assignment(c, &operand, elem_type, context_name);
  8083. is_constant = is_constant && operand.mode == Addressing_Constant;
  8084. }
  8085. }
  8086. cl->max_count = max;
  8087. }
  8088. } else {
  8089. isize index = 0;
  8090. for (; index < cl->elems.count; index++) {
  8091. Ast *e = cl->elems[index];
  8092. if (e == nullptr) {
  8093. error(node, "Invalid literal element");
  8094. continue;
  8095. }
  8096. if (e->kind == Ast_FieldValue) {
  8097. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8098. continue;
  8099. }
  8100. if (0 <= max_type_count && max_type_count <= index) {
  8101. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8102. }
  8103. Operand operand = {};
  8104. check_expr_with_type_hint(c, &operand, e, elem_type);
  8105. check_assignment(c, &operand, elem_type, context_name);
  8106. is_constant = is_constant && operand.mode == Addressing_Constant;
  8107. }
  8108. if (max < index) {
  8109. max = index;
  8110. }
  8111. }
  8112. if (t->kind == Type_Array) {
  8113. if (is_to_be_determined_array_count) {
  8114. t->Array.count = max;
  8115. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8116. if (0 < max && max < t->Array.count) {
  8117. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8118. }
  8119. }
  8120. }
  8121. if (t->kind == Type_SimdVector) {
  8122. if (!is_constant) {
  8123. error(node, "Expected all constant elements for a simd vector");
  8124. }
  8125. if (t->SimdVector.is_x86_mmx) {
  8126. error(node, "Compound literals are not allowed with intrinsics.x86_mmx");
  8127. }
  8128. }
  8129. if (t->kind == Type_DynamicArray) {
  8130. if (build_context.no_dynamic_literals && cl->elems.count) {
  8131. error(node, "Compound literals of dynamic types have been disabled");
  8132. }
  8133. }
  8134. break;
  8135. }
  8136. case Type_EnumeratedArray:
  8137. {
  8138. Type *elem_type = t->EnumeratedArray.elem;
  8139. Type *index_type = t->EnumeratedArray.index;
  8140. String context_name = str_lit("enumerated array literal");
  8141. i64 max_type_count = t->EnumeratedArray.count;
  8142. gbString index_type_str = type_to_string(index_type);
  8143. defer (gb_string_free(index_type_str));
  8144. i64 total_lo = exact_value_to_i64(t->EnumeratedArray.min_value);
  8145. i64 total_hi = exact_value_to_i64(t->EnumeratedArray.max_value);
  8146. String total_lo_string = {};
  8147. String total_hi_string = {};
  8148. GB_ASSERT(is_type_enum(index_type));
  8149. {
  8150. Type *bt = base_type(index_type);
  8151. GB_ASSERT(bt->kind == Type_Enum);
  8152. for_array(i, bt->Enum.fields) {
  8153. Entity *f = bt->Enum.fields[i];
  8154. if (f->kind != Entity_Constant) {
  8155. continue;
  8156. }
  8157. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, t->EnumeratedArray.min_value)) {
  8158. total_lo_string = f->token.string;
  8159. }
  8160. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, t->EnumeratedArray.max_value)) {
  8161. total_hi_string = f->token.string;
  8162. }
  8163. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8164. break;
  8165. }
  8166. }
  8167. }
  8168. i64 max = 0;
  8169. Type *bet = base_type(elem_type);
  8170. if (!elem_type_can_be_constant(bet)) {
  8171. is_constant = false;
  8172. }
  8173. if (bet == t_invalid) {
  8174. break;
  8175. }
  8176. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8177. RangeCache rc = range_cache_make(heap_allocator());
  8178. defer (range_cache_destroy(&rc));
  8179. for_array(i, cl->elems) {
  8180. Ast *elem = cl->elems[i];
  8181. if (elem->kind != Ast_FieldValue) {
  8182. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8183. continue;
  8184. }
  8185. ast_node(fv, FieldValue, elem);
  8186. if (is_ast_range(fv->field)) {
  8187. Token op = fv->field->BinaryExpr.op;
  8188. Operand x = {};
  8189. Operand y = {};
  8190. bool ok = check_range(c, fv->field, &x, &y, nullptr, index_type);
  8191. if (!ok) {
  8192. continue;
  8193. }
  8194. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8195. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8196. continue;
  8197. }
  8198. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8199. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8200. continue;
  8201. }
  8202. i64 lo = exact_value_to_i64(x.value);
  8203. i64 hi = exact_value_to_i64(y.value);
  8204. i64 max_index = hi;
  8205. if (op.kind == Token_RangeHalf) {
  8206. hi -= 1;
  8207. }
  8208. bool new_range = range_cache_add_range(&rc, lo, hi);
  8209. if (!new_range) {
  8210. gbString lo_str = expr_to_string(x.expr);
  8211. gbString hi_str = expr_to_string(y.expr);
  8212. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8213. gb_string_free(hi_str);
  8214. gb_string_free(lo_str);
  8215. continue;
  8216. }
  8217. // NOTE(bill): These are sanity checks for invalid enum values
  8218. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8219. gbString lo_str = expr_to_string(x.expr);
  8220. 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));
  8221. gb_string_free(lo_str);
  8222. continue;
  8223. }
  8224. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8225. gbString hi_str = expr_to_string(y.expr);
  8226. 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));
  8227. gb_string_free(hi_str);
  8228. continue;
  8229. }
  8230. if (max < hi) {
  8231. max = max_index;
  8232. }
  8233. Operand operand = {};
  8234. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8235. check_assignment(c, &operand, elem_type, context_name);
  8236. is_constant = is_constant && operand.mode == Addressing_Constant;
  8237. } else {
  8238. Operand op_index = {};
  8239. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8240. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8241. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8242. continue;
  8243. }
  8244. i64 index = exact_value_to_i64(op_index.value);
  8245. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8246. gbString idx_str = expr_to_string(op_index.expr);
  8247. 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));
  8248. gb_string_free(idx_str);
  8249. continue;
  8250. }
  8251. bool new_index = range_cache_add_index(&rc, index);
  8252. if (!new_index) {
  8253. gbString idx_str = expr_to_string(op_index.expr);
  8254. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8255. gb_string_free(idx_str);
  8256. continue;
  8257. }
  8258. if (max < index+1) {
  8259. max = index+1;
  8260. }
  8261. Operand operand = {};
  8262. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8263. check_assignment(c, &operand, elem_type, context_name);
  8264. is_constant = is_constant && operand.mode == Addressing_Constant;
  8265. }
  8266. }
  8267. cl->max_count = max;
  8268. } else {
  8269. isize index = 0;
  8270. for (; index < cl->elems.count; index++) {
  8271. Ast *e = cl->elems[index];
  8272. if (e == nullptr) {
  8273. error(node, "Invalid literal element");
  8274. continue;
  8275. }
  8276. if (e->kind == Ast_FieldValue) {
  8277. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8278. continue;
  8279. }
  8280. if (0 <= max_type_count && max_type_count <= index) {
  8281. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8282. }
  8283. Operand operand = {};
  8284. check_expr_with_type_hint(c, &operand, e, elem_type);
  8285. check_assignment(c, &operand, elem_type, context_name);
  8286. is_constant = is_constant && operand.mode == Addressing_Constant;
  8287. }
  8288. if (max < index) {
  8289. max = index;
  8290. }
  8291. }
  8292. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8293. if (0 < max && max < t->EnumeratedArray.count) {
  8294. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8295. } else {
  8296. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8297. }
  8298. }
  8299. break;
  8300. }
  8301. case Type_Basic: {
  8302. if (!is_type_any(t)) {
  8303. if (cl->elems.count != 0) {
  8304. error(node, "Illegal compound literal");
  8305. }
  8306. break;
  8307. }
  8308. if (cl->elems.count == 0) {
  8309. break; // NOTE(bill): No need to init
  8310. }
  8311. { // Checker values
  8312. Type *field_types[2] = {t_rawptr, t_typeid};
  8313. isize field_count = 2;
  8314. if (cl->elems[0]->kind == Ast_FieldValue) {
  8315. bool fields_visited[2] = {};
  8316. for_array(i, cl->elems) {
  8317. Ast *elem = cl->elems[i];
  8318. if (elem->kind != Ast_FieldValue) {
  8319. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8320. continue;
  8321. }
  8322. ast_node(fv, FieldValue, elem);
  8323. if (fv->field->kind != Ast_Ident) {
  8324. gbString expr_str = expr_to_string(fv->field);
  8325. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8326. gb_string_free(expr_str);
  8327. continue;
  8328. }
  8329. String name = fv->field->Ident.token.string;
  8330. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8331. if (sel.entity == nullptr) {
  8332. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8333. continue;
  8334. }
  8335. isize index = sel.index[0];
  8336. if (fields_visited[index]) {
  8337. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8338. continue;
  8339. }
  8340. fields_visited[index] = true;
  8341. check_expr(c, o, fv->value);
  8342. // NOTE(bill): 'any' literals can never be constant
  8343. is_constant = false;
  8344. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8345. }
  8346. } else {
  8347. for_array(index, cl->elems) {
  8348. Ast *elem = cl->elems[index];
  8349. if (elem->kind == Ast_FieldValue) {
  8350. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8351. continue;
  8352. }
  8353. check_expr(c, o, elem);
  8354. if (index >= field_count) {
  8355. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8356. break;
  8357. }
  8358. // NOTE(bill): 'any' literals can never be constant
  8359. is_constant = false;
  8360. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8361. }
  8362. if (cl->elems.count < field_count) {
  8363. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8364. }
  8365. }
  8366. }
  8367. break;
  8368. }
  8369. case Type_Map: {
  8370. if (cl->elems.count == 0) {
  8371. break;
  8372. }
  8373. is_constant = false;
  8374. { // Checker values
  8375. bool key_is_typeid = is_type_typeid(t->Map.key);
  8376. bool value_is_typeid = is_type_typeid(t->Map.value);
  8377. for_array(i, cl->elems) {
  8378. Ast *elem = cl->elems[i];
  8379. if (elem->kind != Ast_FieldValue) {
  8380. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8381. continue;
  8382. }
  8383. ast_node(fv, FieldValue, elem);
  8384. if (key_is_typeid) {
  8385. check_expr_or_type(c, o, fv->field, t->Map.key);
  8386. } else {
  8387. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8388. }
  8389. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8390. if (o->mode == Addressing_Invalid) {
  8391. continue;
  8392. }
  8393. if (value_is_typeid) {
  8394. check_expr_or_type(c, o, fv->value, t->Map.value);
  8395. } else {
  8396. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8397. }
  8398. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8399. }
  8400. }
  8401. if (build_context.no_dynamic_literals && cl->elems.count) {
  8402. error(node, "Compound literals of dynamic types have been disabled");
  8403. } else {
  8404. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  8405. add_package_dependency(c, "runtime", "__dynamic_map_set");
  8406. }
  8407. break;
  8408. }
  8409. case Type_BitSet: {
  8410. if (cl->elems.count == 0) {
  8411. break; // NOTE(bill): No need to init
  8412. }
  8413. Type *et = base_type(t->BitSet.elem);
  8414. isize field_count = 0;
  8415. if (et->kind == Type_Enum) {
  8416. field_count = et->Enum.fields.count;
  8417. }
  8418. if (cl->elems[0]->kind == Ast_FieldValue) {
  8419. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8420. is_constant = false;
  8421. } else {
  8422. for_array(index, cl->elems) {
  8423. Entity *field = nullptr;
  8424. Ast *elem = cl->elems[index];
  8425. if (elem->kind == Ast_FieldValue) {
  8426. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8427. continue;
  8428. }
  8429. check_expr_with_type_hint(c, o, elem, et);
  8430. if (is_constant) {
  8431. is_constant = o->mode == Addressing_Constant;
  8432. }
  8433. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8434. if (o->mode == Addressing_Constant) {
  8435. i64 lower = t->BitSet.lower;
  8436. i64 upper = t->BitSet.upper;
  8437. i64 v = exact_value_to_i64(o->value);
  8438. if (lower <= v && v <= upper) {
  8439. // okay
  8440. } else {
  8441. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8442. continue;
  8443. }
  8444. }
  8445. }
  8446. }
  8447. break;
  8448. }
  8449. default: {
  8450. if (cl->elems.count == 0) {
  8451. break; // NOTE(bill): No need to init
  8452. }
  8453. gbString str = type_to_string(type);
  8454. error(node, "Invalid compound literal type '%s'", str);
  8455. gb_string_free(str);
  8456. return kind;
  8457. }
  8458. }
  8459. if (is_constant) {
  8460. o->mode = Addressing_Constant;
  8461. if (is_type_bit_set(type)) {
  8462. // NOTE(bill): Encode as an integer
  8463. i64 lower = base_type(type)->BitSet.lower;
  8464. u64 bits = 0;
  8465. for_array(index, cl->elems) {
  8466. Entity *field = nullptr;
  8467. Ast *elem = cl->elems[index];
  8468. GB_ASSERT(elem->kind != Ast_FieldValue);
  8469. TypeAndValue tav = elem->tav;
  8470. ExactValue i = exact_value_to_integer(tav.value);
  8471. if (i.kind != ExactValue_Integer) {
  8472. continue;
  8473. }
  8474. i64 val = big_int_to_i64(&i.value_integer);
  8475. val -= lower;
  8476. u64 bit = u64(1ll<<val);
  8477. bits |= bit;
  8478. }
  8479. o->value = exact_value_u64(bits);
  8480. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8481. ExactValue value = exact_value_compound(node);
  8482. Type *bt = core_type(type);
  8483. if (bt->kind == Type_Basic) {
  8484. if (bt->Basic.flags & BasicFlag_Boolean) {
  8485. value = exact_value_bool(false);
  8486. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8487. value = exact_value_i64(0);
  8488. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8489. value = exact_value_i64(0);
  8490. } else if (bt->Basic.flags & BasicFlag_Float) {
  8491. value = exact_value_float(0);
  8492. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8493. value = exact_value_complex(0, 0);
  8494. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8495. value = exact_value_quaternion(0, 0, 0, 0);
  8496. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8497. value = exact_value_pointer(0);
  8498. } else if (bt->Basic.flags & BasicFlag_String) {
  8499. String empty_string = {};
  8500. value = exact_value_string(empty_string);
  8501. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8502. value = exact_value_i64(0);
  8503. }
  8504. }
  8505. o->value = value;
  8506. } else {
  8507. o->value = exact_value_compound(node);
  8508. }
  8509. } else {
  8510. o->mode = Addressing_Value;
  8511. }
  8512. o->type = type;
  8513. case_end;
  8514. case_ast_node(pe, ParenExpr, node);
  8515. kind = check_expr_base(c, o, pe->expr, type_hint);
  8516. node->viral_state_flags |= pe->expr->viral_state_flags;
  8517. o->expr = node;
  8518. case_end;
  8519. case_ast_node(te, TagExpr, node);
  8520. String name = te->name.string;
  8521. error(node, "Unknown tag expression, #%.*s", LIT(name));
  8522. if (te->expr) {
  8523. kind = check_expr_base(c, o, te->expr, type_hint);
  8524. node->viral_state_flags |= te->expr->viral_state_flags;
  8525. }
  8526. o->expr = node;
  8527. case_end;
  8528. case_ast_node(ta, TypeAssertion, node);
  8529. check_expr(c, o, ta->expr);
  8530. node->viral_state_flags |= ta->expr->viral_state_flags;
  8531. if (o->mode == Addressing_Invalid) {
  8532. o->expr = node;
  8533. return kind;
  8534. }
  8535. if (o->mode == Addressing_Constant) {
  8536. gbString expr_str = expr_to_string(o->expr);
  8537. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8538. gb_string_free(expr_str);
  8539. o->mode = Addressing_Invalid;
  8540. o->expr = node;
  8541. return kind;
  8542. }
  8543. if (is_type_untyped(o->type)) {
  8544. gbString expr_str = expr_to_string(o->expr);
  8545. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8546. gb_string_free(expr_str);
  8547. o->mode = Addressing_Invalid;
  8548. o->expr = node;
  8549. return kind;
  8550. }
  8551. bool src_is_ptr = is_type_pointer(o->type);
  8552. Type *src = type_deref(o->type);
  8553. Type *bsrc = base_type(src);
  8554. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8555. if (!is_type_union(src)) {
  8556. gbString str = type_to_string(o->type);
  8557. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8558. gb_string_free(str);
  8559. o->mode = Addressing_Invalid;
  8560. o->expr = node;
  8561. return kind;
  8562. }
  8563. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8564. bool allowed = false;
  8565. for_array(i, bsrc->Union.variants) {
  8566. Type *vt = bsrc->Union.variants[i];
  8567. if (are_types_identical(vt, type_hint)) {
  8568. allowed = true;
  8569. add_type_info_type(c, vt);
  8570. break;
  8571. }
  8572. }
  8573. if (allowed) {
  8574. add_type_info_type(c, o->type);
  8575. o->type = type_hint;
  8576. o->mode = Addressing_OptionalOk;
  8577. return kind;
  8578. }
  8579. }
  8580. if (bsrc->Union.variants.count != 1) {
  8581. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8582. o->mode = Addressing_Invalid;
  8583. o->expr = node;
  8584. return kind;
  8585. }
  8586. add_type_info_type(c, o->type);
  8587. add_type_info_type(c, bsrc->Union.variants[0]);
  8588. o->type = bsrc->Union.variants[0];
  8589. o->mode = Addressing_OptionalOk;
  8590. } else {
  8591. Type *t = check_type(c, ta->type);
  8592. Type *dst = t;
  8593. Type *bdst = base_type(dst);
  8594. if (is_type_union(src)) {
  8595. bool ok = false;
  8596. for_array(i, bsrc->Union.variants) {
  8597. Type *vt = bsrc->Union.variants[i];
  8598. if (are_types_identical(vt, dst)) {
  8599. ok = true;
  8600. break;
  8601. }
  8602. }
  8603. if (!ok) {
  8604. gbString expr_str = expr_to_string(o->expr);
  8605. gbString dst_type_str = type_to_string(t);
  8606. defer (gb_string_free(expr_str));
  8607. defer (gb_string_free(dst_type_str));
  8608. if (bsrc->Union.variants.count == 0) {
  8609. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8610. } else {
  8611. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8612. }
  8613. o->mode = Addressing_Invalid;
  8614. o->expr = node;
  8615. return kind;
  8616. }
  8617. add_type_info_type(c, o->type);
  8618. add_type_info_type(c, t);
  8619. o->type = t;
  8620. o->mode = Addressing_OptionalOk;
  8621. } else if (is_type_any(src)) {
  8622. o->type = t;
  8623. o->mode = Addressing_OptionalOk;
  8624. add_type_info_type(c, o->type);
  8625. add_type_info_type(c, t);
  8626. } else {
  8627. gbString str = type_to_string(o->type);
  8628. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8629. gb_string_free(str);
  8630. o->mode = Addressing_Invalid;
  8631. o->expr = node;
  8632. return kind;
  8633. }
  8634. }
  8635. add_package_dependency(c, "runtime", "type_assertion_check");
  8636. add_package_dependency(c, "runtime", "type_assertion_check2");
  8637. case_end;
  8638. case_ast_node(tc, TypeCast, node);
  8639. check_expr_or_type(c, o, tc->type);
  8640. if (o->mode != Addressing_Type) {
  8641. gbString str = expr_to_string(tc->type);
  8642. error(tc->type, "Expected a type, got %s", str);
  8643. gb_string_free(str);
  8644. o->mode = Addressing_Invalid;
  8645. }
  8646. if (o->mode == Addressing_Invalid) {
  8647. o->expr = node;
  8648. return kind;
  8649. }
  8650. Type *type = o->type;
  8651. check_expr_base(c, o, tc->expr, type);
  8652. node->viral_state_flags |= tc->expr->viral_state_flags;
  8653. if (o->mode != Addressing_Invalid) {
  8654. switch (tc->token.kind) {
  8655. case Token_transmute:
  8656. check_transmute(c, node, o, type);
  8657. break;
  8658. case Token_cast:
  8659. check_cast(c, o, type);
  8660. break;
  8661. default:
  8662. error(node, "Invalid AST: Invalid casting expression");
  8663. o->mode = Addressing_Invalid;
  8664. break;
  8665. }
  8666. }
  8667. return Expr_Expr;
  8668. case_end;
  8669. case_ast_node(ac, AutoCast, node);
  8670. check_expr_base(c, o, ac->expr, type_hint);
  8671. node->viral_state_flags |= ac->expr->viral_state_flags;
  8672. if (o->mode == Addressing_Invalid) {
  8673. o->expr = node;
  8674. return kind;
  8675. }
  8676. if (type_hint) {
  8677. check_cast(c, o, type_hint);
  8678. }
  8679. o->expr = node;
  8680. return Expr_Expr;
  8681. case_end;
  8682. case_ast_node(ue, UnaryExpr, node);
  8683. Ast *prev_unary_address_hint = c->unary_address_hint;
  8684. c->unary_address_hint = unparen_expr(node);
  8685. check_expr_base(c, o, ue->expr, type_hint);
  8686. c->unary_address_hint = prev_unary_address_hint;
  8687. node->viral_state_flags |= ue->expr->viral_state_flags;
  8688. if (o->mode == Addressing_Invalid) {
  8689. o->expr = node;
  8690. return kind;
  8691. }
  8692. check_unary_expr(c, o, ue->op, node);
  8693. if (o->mode == Addressing_Invalid) {
  8694. o->expr = node;
  8695. return kind;
  8696. }
  8697. case_end;
  8698. case_ast_node(be, BinaryExpr, node);
  8699. check_binary_expr(c, o, node, type_hint, true);
  8700. if (o->mode == Addressing_Invalid) {
  8701. o->expr = node;
  8702. return kind;
  8703. }
  8704. case_end;
  8705. case_ast_node(se, SelectorExpr, node);
  8706. check_selector(c, o, node, type_hint);
  8707. node->viral_state_flags |= se->expr->viral_state_flags;
  8708. case_end;
  8709. case_ast_node(se, SelectorCallExpr, node);
  8710. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8711. // COM APIs is a great example of where this kind of thing is extremely useful
  8712. // General idea:
  8713. //
  8714. // x->y(123) == x.y(x, 123)
  8715. //
  8716. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8717. // Just regenerating a new AST aids things
  8718. //
  8719. // TODO(bill): Is this a good hack or not?
  8720. //
  8721. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8722. bool allow_arrow_right_selector_expr;
  8723. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8724. c->allow_arrow_right_selector_expr = true;
  8725. Operand x = {};
  8726. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8727. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8728. if (x.mode == Addressing_Invalid || x.type == t_invalid) {
  8729. o->mode = Addressing_Invalid;
  8730. o->type = t_invalid;
  8731. o->expr = node;
  8732. return kind;
  8733. }
  8734. if (!is_type_proc(x.type)) {
  8735. gbString type_str = type_to_string(x.type);
  8736. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8737. gb_string_free(type_str);
  8738. o->mode = Addressing_Invalid;
  8739. o->type = t_invalid;
  8740. o->expr = node;
  8741. return Expr_Stmt;
  8742. }
  8743. ast_node(ce, CallExpr, se->call);
  8744. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8745. Ast *first_arg = x.expr->SelectorExpr.expr;
  8746. GB_ASSERT(first_arg != nullptr);
  8747. Type *pt = base_type(x.type);
  8748. GB_ASSERT(pt->kind == Type_Proc);
  8749. Type *first_type = nullptr;
  8750. String first_arg_name = {};
  8751. if (pt->Proc.param_count > 0) {
  8752. Entity *f = pt->Proc.params->Tuple.variables[0];
  8753. first_type = f->type;
  8754. first_arg_name = f->token.string;
  8755. }
  8756. if (first_arg_name.len == 0) {
  8757. first_arg_name = str_lit("_");
  8758. }
  8759. if (first_type == nullptr) {
  8760. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8761. o->mode = Addressing_Invalid;
  8762. o->type = t_invalid;
  8763. o->expr = node;
  8764. return Expr_Stmt;
  8765. }
  8766. Operand y = {};
  8767. y.mode = first_arg->tav.mode;
  8768. y.type = first_arg->tav.type;
  8769. y.value = first_arg->tav.value;
  8770. if (check_is_assignable_to(c, &y, first_type)) {
  8771. // Do nothing, it's valid
  8772. } else {
  8773. Operand z = y;
  8774. z.type = type_deref(y.type);
  8775. if (check_is_assignable_to(c, &z, first_type)) {
  8776. // NOTE(bill): AST GENERATION HACK!
  8777. Token op = {Token_Pointer};
  8778. first_arg = ast_deref_expr(first_arg->file, first_arg, op);
  8779. } else if (y.mode == Addressing_Variable) {
  8780. Operand w = y;
  8781. w.type = alloc_type_pointer(y.type);
  8782. if (check_is_assignable_to(c, &w, first_type)) {
  8783. // NOTE(bill): AST GENERATION HACK!
  8784. Token op = {Token_And};
  8785. first_arg = ast_unary_expr(first_arg->file, op, first_arg);
  8786. }
  8787. }
  8788. }
  8789. if (ce->args.count > 0) {
  8790. bool fail = false;
  8791. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8792. for_array(i, ce->args) {
  8793. Ast *arg = ce->args[i];
  8794. bool mix = false;
  8795. if (first_is_field_value) {
  8796. mix = arg->kind != Ast_FieldValue;
  8797. } else {
  8798. mix = arg->kind == Ast_FieldValue;
  8799. }
  8800. if (mix) {
  8801. fail = true;
  8802. break;
  8803. }
  8804. }
  8805. if (!fail && first_is_field_value) {
  8806. Token op = {Token_Eq};
  8807. AstFile *f = first_arg->file;
  8808. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8809. }
  8810. }
  8811. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8812. modified_args[0] = first_arg;
  8813. slice_copy(&modified_args, ce->args, 1);
  8814. ce->args = modified_args;
  8815. se->modified_call = true;
  8816. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8817. c->allow_arrow_right_selector_expr = true;
  8818. check_expr_base(c, o, se->call, type_hint);
  8819. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8820. o->expr = node;
  8821. return Expr_Expr;
  8822. case_end;
  8823. case_ast_node(ise, ImplicitSelectorExpr, node);
  8824. o->type = t_invalid;
  8825. o->expr = node;
  8826. o->mode = Addressing_Invalid;
  8827. Type *th = type_hint;
  8828. if (th == nullptr) {
  8829. gbString str = expr_to_string(node);
  8830. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  8831. gb_string_free(str);
  8832. return Expr_Expr;
  8833. }
  8834. o->type = th;
  8835. Type *enum_type = th;
  8836. if (!is_type_enum(th)) {
  8837. bool show_error = true;
  8838. if (is_type_union(th)) {
  8839. Type *union_type = base_type(th);
  8840. isize enum_count = 0;
  8841. Type *et = nullptr;
  8842. for_array(i, union_type->Union.variants) {
  8843. Type *vt = union_type->Union.variants[i];
  8844. if (is_type_enum(vt)) {
  8845. enum_count += 1;
  8846. et = vt;
  8847. }
  8848. }
  8849. if (enum_count == 1) {
  8850. show_error = false;
  8851. enum_type = et;
  8852. }
  8853. }
  8854. if (show_error) {
  8855. gbString typ = type_to_string(th);
  8856. gbString str = expr_to_string(node);
  8857. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  8858. gb_string_free(str);
  8859. gb_string_free(typ);
  8860. return Expr_Expr;
  8861. }
  8862. }
  8863. GB_ASSERT(ise->selector->kind == Ast_Ident);
  8864. String name = ise->selector->Ident.token.string;
  8865. enum_type = base_type(enum_type);
  8866. GB_ASSERT(enum_type->kind == Type_Enum);
  8867. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  8868. if (e == nullptr) {
  8869. gbString typ = type_to_string(th);
  8870. error(node, "Undeclared name %.*s for type '%s'", LIT(name), typ);
  8871. gb_string_free(typ);
  8872. return Expr_Expr;
  8873. }
  8874. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  8875. GB_ASSERT(e->kind == Entity_Constant);
  8876. o->value = e->Constant.value;
  8877. o->mode = Addressing_Constant;
  8878. o->type = e->type;
  8879. return Expr_Expr;
  8880. case_end;
  8881. case_ast_node(ie, IndexExpr, node);
  8882. check_expr(c, o, ie->expr);
  8883. node->viral_state_flags |= ie->expr->viral_state_flags;
  8884. if (o->mode == Addressing_Invalid) {
  8885. o->expr = node;
  8886. return kind;
  8887. }
  8888. Type *t = base_type(type_deref(o->type));
  8889. bool is_ptr = is_type_pointer(o->type);
  8890. bool is_const = o->mode == Addressing_Constant;
  8891. if (is_type_map(t)) {
  8892. Operand key = {};
  8893. if (is_type_typeid(t->Map.key)) {
  8894. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8895. } else {
  8896. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8897. }
  8898. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8899. if (key.mode == Addressing_Invalid) {
  8900. o->mode = Addressing_Invalid;
  8901. o->expr = node;
  8902. return kind;
  8903. }
  8904. o->mode = Addressing_MapIndex;
  8905. o->type = t->Map.value;
  8906. o->expr = node;
  8907. add_package_dependency(c, "runtime", "__dynamic_map_get");
  8908. add_package_dependency(c, "runtime", "__dynamic_map_set");
  8909. return Expr_Expr;
  8910. }
  8911. if (t->kind == Type_Struct) {
  8912. TypeAtomOpTable *atom_op_table = t->Struct.atom_op_table;
  8913. if (atom_op_table != nullptr) {
  8914. if (atom_op_table->op[TypeAtomOp_index_set]) {
  8915. if (c->assignment_lhs_hint == node) {
  8916. o->mode = Addressing_AtomOpAssign;
  8917. o->type = o->type;
  8918. o->expr = node;
  8919. return kind;
  8920. }
  8921. }
  8922. if (atom_op_table->op[TypeAtomOp_index_get]) {
  8923. Entity *e = atom_op_table->op[TypeAtomOp_index_get];
  8924. if (ie->index == nullptr) {
  8925. gbString str = expr_to_string(o->expr);
  8926. error(o->expr, "Missing index for '%s'", str);
  8927. gb_string_free(str);
  8928. o->mode = Addressing_Invalid;
  8929. o->expr = node;
  8930. return kind;
  8931. }
  8932. GB_ASSERT(e->identifier != nullptr);
  8933. Ast *proc_ident = clone_ast(e->identifier);
  8934. auto args = array_make<Ast *>(heap_allocator(), 2);
  8935. args[0] = ie->expr;
  8936. args[1] = ie->index;
  8937. GB_ASSERT(c->file != nullptr);
  8938. Ast *fake_call = ast_call_expr(c->file, proc_ident, args, ie->open, ie->close, {});
  8939. check_expr_base(c, o, fake_call, type_hint);
  8940. AtomOpMapEntry entry = {TypeAtomOp_index_get, fake_call};
  8941. map_set(&c->info->atom_op_map, hash_pointer(node), entry);
  8942. o->expr = node;
  8943. return kind;
  8944. }
  8945. }
  8946. }
  8947. i64 max_count = -1;
  8948. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8949. if (is_const) {
  8950. if (is_type_array(t)) {
  8951. // OKay
  8952. } else if (is_type_slice(t)) {
  8953. // Okay
  8954. } else if (is_type_enumerated_array(t)) {
  8955. // Okay
  8956. } else if (is_type_string(t)) {
  8957. // Okay
  8958. } else if (is_type_relative_slice(t)) {
  8959. // Okay
  8960. } else {
  8961. valid = false;
  8962. }
  8963. }
  8964. if (!valid) {
  8965. gbString str = expr_to_string(o->expr);
  8966. gbString type_str = type_to_string(o->type);
  8967. defer (gb_string_free(str));
  8968. defer (gb_string_free(type_str));
  8969. if (is_const) {
  8970. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8971. } else {
  8972. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8973. }
  8974. o->mode = Addressing_Invalid;
  8975. o->expr = node;
  8976. return kind;
  8977. }
  8978. if (ie->index == nullptr) {
  8979. gbString str = expr_to_string(o->expr);
  8980. error(o->expr, "Missing index for '%s'", str);
  8981. gb_string_free(str);
  8982. o->mode = Addressing_Invalid;
  8983. o->expr = node;
  8984. return kind;
  8985. }
  8986. Type *index_type_hint = nullptr;
  8987. if (is_type_enumerated_array(t)) {
  8988. Type *bt = base_type(t);
  8989. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8990. index_type_hint = bt->EnumeratedArray.index;
  8991. }
  8992. i64 index = 0;
  8993. bool ok = check_index_value(c, false, ie->index, max_count, &index, index_type_hint);
  8994. if (is_const) {
  8995. if (index < 0) {
  8996. if (max_count < 0) {
  8997. }
  8998. gbString str = expr_to_string(o->expr);
  8999. error(o->expr, "Cannot index a constant '%s'", str);
  9000. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9001. gb_string_free(str);
  9002. o->mode = Addressing_Invalid;
  9003. o->expr = node;
  9004. return kind;
  9005. } else if (ok) {
  9006. ExactValue value = type_and_value_of_expr(ie->expr).value;
  9007. o->mode = Addressing_Constant;
  9008. bool success = false;
  9009. bool finish = false;
  9010. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9011. if (!success) {
  9012. gbString str = expr_to_string(o->expr);
  9013. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9014. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9015. gb_string_free(str);
  9016. o->mode = Addressing_Invalid;
  9017. o->expr = node;
  9018. return kind;
  9019. }
  9020. }
  9021. }
  9022. case_end;
  9023. case_ast_node(se, SliceExpr, node);
  9024. check_expr(c, o, se->expr);
  9025. node->viral_state_flags |= se->expr->viral_state_flags;
  9026. if (o->mode == Addressing_Invalid) {
  9027. o->mode = Addressing_Invalid;
  9028. o->expr = node;
  9029. return kind;
  9030. }
  9031. bool valid = false;
  9032. i64 max_count = -1;
  9033. Type *t = base_type(type_deref(o->type));
  9034. switch (t->kind) {
  9035. case Type_Basic:
  9036. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9037. valid = true;
  9038. if (o->mode == Addressing_Constant) {
  9039. max_count = o->value.value_string.len;
  9040. }
  9041. o->type = type_deref(o->type);
  9042. }
  9043. break;
  9044. case Type_Array:
  9045. valid = true;
  9046. max_count = t->Array.count;
  9047. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9048. gbString str = expr_to_string(node);
  9049. error(node, "Cannot slice array '%s', value is not addressable", str);
  9050. gb_string_free(str);
  9051. o->mode = Addressing_Invalid;
  9052. o->expr = node;
  9053. return kind;
  9054. }
  9055. o->type = alloc_type_slice(t->Array.elem);
  9056. break;
  9057. case Type_Slice:
  9058. valid = true;
  9059. o->type = type_deref(o->type);
  9060. break;
  9061. case Type_DynamicArray:
  9062. valid = true;
  9063. o->type = alloc_type_slice(t->DynamicArray.elem);
  9064. break;
  9065. case Type_Struct:
  9066. if (is_type_soa_struct(t)) {
  9067. valid = true;
  9068. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9069. } else {
  9070. TypeAtomOpTable *atom_op_table = t->Struct.atom_op_table;
  9071. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9072. Entity *e = atom_op_table->op[TypeAtomOp_slice];
  9073. GB_ASSERT(e->identifier != nullptr);
  9074. Ast *proc_ident = clone_ast(e->identifier);
  9075. Ast *expr = se->expr;
  9076. if (o->mode == Addressing_Variable) {
  9077. expr = ast_unary_expr(c->file, {Token_And, STR_LIT("&")}, expr);
  9078. } else if (is_type_pointer(o->type)) {
  9079. // Okay
  9080. } else {
  9081. gbString str = expr_to_string(node);
  9082. error(node, "Cannot slice '%s', value is not addressable", str);
  9083. gb_string_free(str);
  9084. o->mode = Addressing_Invalid;
  9085. o->expr = node;
  9086. return kind;
  9087. }
  9088. auto args = array_make<Ast *>(heap_allocator(), 1);
  9089. args[0] = expr;
  9090. GB_ASSERT(c->file != nullptr);
  9091. Ast *fake_call = ast_call_expr(c->file, proc_ident, args, se->open, se->close, {});
  9092. check_expr_base(c, o, fake_call, type_hint);
  9093. AtomOpMapEntry entry = {TypeAtomOp_slice, fake_call};
  9094. map_set(&c->info->atom_op_map, hash_pointer(node), entry);
  9095. valid = true;
  9096. }
  9097. }
  9098. break;
  9099. case Type_RelativeSlice:
  9100. valid = true;
  9101. o->type = t->RelativeSlice.slice_type;
  9102. if (o->mode != Addressing_Variable) {
  9103. gbString str = expr_to_string(node);
  9104. error(node, "Cannot relative slice '%s', value is not addressable", str);
  9105. gb_string_free(str);
  9106. o->mode = Addressing_Invalid;
  9107. o->expr = node;
  9108. return kind;
  9109. }
  9110. break;
  9111. }
  9112. if (!valid) {
  9113. gbString str = expr_to_string(o->expr);
  9114. gbString type_str = type_to_string(o->type);
  9115. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9116. gb_string_free(type_str);
  9117. gb_string_free(str);
  9118. o->mode = Addressing_Invalid;
  9119. o->expr = node;
  9120. return kind;
  9121. }
  9122. o->mode = Addressing_Value;
  9123. if (se->low == nullptr && se->high != nullptr) {
  9124. // error(se->interval0, "1st index is required if a 2nd index is specified");
  9125. // It is okay to continue as it will assume the 1st index is zero
  9126. }
  9127. i64 indices[2] = {};
  9128. Ast *nodes[2] = {se->low, se->high};
  9129. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9130. i64 index = max_count;
  9131. if (nodes[i] != nullptr) {
  9132. i64 capacity = -1;
  9133. if (max_count >= 0) {
  9134. capacity = max_count;
  9135. }
  9136. i64 j = 0;
  9137. if (check_index_value(c, true, nodes[i], capacity, &j)) {
  9138. index = j;
  9139. }
  9140. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9141. } else if (i == 0) {
  9142. index = 0;
  9143. }
  9144. indices[i] = index;
  9145. }
  9146. for (isize i = 0; i < gb_count_of(indices); i++) {
  9147. i64 a = indices[i];
  9148. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9149. i64 b = indices[j];
  9150. if (a > b && b >= 0) {
  9151. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9152. }
  9153. }
  9154. }
  9155. if (is_type_string(t) && max_count >= 0) {
  9156. bool all_constant = true;
  9157. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9158. if (nodes[i] != nullptr) {
  9159. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9160. if (tav.mode != Addressing_Constant) {
  9161. all_constant = false;
  9162. break;
  9163. }
  9164. }
  9165. }
  9166. if (!all_constant) {
  9167. gbString str = expr_to_string(o->expr);
  9168. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9169. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9170. gb_string_free(str);
  9171. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9172. o->expr = node;
  9173. return kind;
  9174. }
  9175. String s = {};
  9176. if (o->value.kind == ExactValue_String) {
  9177. s = o->value.value_string;
  9178. }
  9179. o->mode = Addressing_Constant;
  9180. o->type = t;
  9181. o->value = exact_value_string(substring(s, indices[0], indices[1]));
  9182. }
  9183. case_end;
  9184. case_ast_node(ce, CallExpr, node);
  9185. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9186. case_end;
  9187. case_ast_node(de, DerefExpr, node);
  9188. check_expr_or_type(c, o, de->expr);
  9189. node->viral_state_flags |= de->expr->viral_state_flags;
  9190. if (o->mode == Addressing_Invalid) {
  9191. o->mode = Addressing_Invalid;
  9192. o->expr = node;
  9193. return kind;
  9194. } else {
  9195. Type *t = base_type(o->type);
  9196. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9197. o->mode = Addressing_Variable;
  9198. o->type = t->Pointer.elem;
  9199. } else if (t->kind == Type_RelativePointer) {
  9200. if (o->mode != Addressing_Variable) {
  9201. gbString str = expr_to_string(o->expr);
  9202. gbString typ = type_to_string(o->type);
  9203. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9204. gb_string_free(typ);
  9205. gb_string_free(str);
  9206. }
  9207. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9208. add_type_info_type(c, o->type);
  9209. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9210. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9211. o->mode = Addressing_Variable;
  9212. o->type = ptr_type->Pointer.elem;
  9213. } else {
  9214. gbString str = expr_to_string(o->expr);
  9215. gbString typ = type_to_string(o->type);
  9216. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9217. gb_string_free(typ);
  9218. gb_string_free(str);
  9219. o->mode = Addressing_Invalid;
  9220. o->expr = node;
  9221. return kind;
  9222. }
  9223. }
  9224. case_end;
  9225. case_ast_node(ia, InlineAsmExpr, node);
  9226. if (c->curr_proc_decl == nullptr) {
  9227. error(node, "Inline asm expressions are only allowed within a procedure body");
  9228. }
  9229. if (!build_context.use_llvm_api) {
  9230. error(node, "Inline asm expressions are only currently allowed with -llvm-api");
  9231. }
  9232. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9233. Type *return_type = nullptr;
  9234. for_array(i, ia->param_types) {
  9235. param_types[i] = check_type(c, ia->param_types[i]);
  9236. }
  9237. if (ia->return_type != nullptr) {
  9238. return_type = check_type(c, ia->return_type);
  9239. }
  9240. Operand x = {};
  9241. check_expr(c, &x, ia->asm_string);
  9242. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9243. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9244. }
  9245. check_expr(c, &x, ia->constraints_string);
  9246. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9247. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9248. }
  9249. Scope *scope = create_scope(c->scope);
  9250. scope->flags |= ScopeFlag_Proc;
  9251. Type *params = alloc_type_tuple();
  9252. Type *results = alloc_type_tuple();
  9253. if (param_types.count != 0) {
  9254. array_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9255. for_array(i, param_types) {
  9256. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9257. }
  9258. }
  9259. if (return_type != nullptr) {
  9260. array_init(&results->Tuple.variables, heap_allocator(), 1);
  9261. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9262. }
  9263. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9264. o->type = pt;
  9265. o->mode = Addressing_Value;
  9266. o->expr = node;
  9267. return Expr_Expr;
  9268. case_end;
  9269. case Ast_TypeidType:
  9270. case Ast_PolyType:
  9271. case Ast_ProcType:
  9272. case Ast_PointerType:
  9273. case Ast_ArrayType:
  9274. case Ast_DynamicArrayType:
  9275. case Ast_StructType:
  9276. case Ast_UnionType:
  9277. case Ast_EnumType:
  9278. case Ast_MapType:
  9279. case Ast_BitSetType:
  9280. o->mode = Addressing_Type;
  9281. o->type = check_type(c, node);
  9282. break;
  9283. }
  9284. kind = Expr_Expr;
  9285. o->expr = node;
  9286. return kind;
  9287. }
  9288. ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9289. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9290. if (o->type != nullptr && is_type_untyped(o->type)) {
  9291. add_untyped(&c->checker->info, node, false, o->mode, o->type, o->value);
  9292. }
  9293. add_type_and_value(&c->checker->info, node, o->mode, o->type, o->value);
  9294. return kind;
  9295. }
  9296. void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9297. check_expr_base(c, o, e, nullptr);
  9298. switch (o->mode) {
  9299. default:
  9300. return; // NOTE(bill): Valid
  9301. case Addressing_NoValue:
  9302. error_operand_no_value(o);
  9303. break;
  9304. }
  9305. o->mode = Addressing_Invalid;
  9306. }
  9307. void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9308. check_expr_base(c, o, e, nullptr);
  9309. switch (o->mode) {
  9310. default:
  9311. return; // NOTE(bill): Valid
  9312. case Addressing_NoValue:
  9313. error_operand_no_value(o);
  9314. break;
  9315. case Addressing_Type:
  9316. error_operand_not_expression(o);
  9317. break;
  9318. }
  9319. o->mode = Addressing_Invalid;
  9320. }
  9321. void check_not_tuple(CheckerContext *c, Operand *o) {
  9322. if (o->mode == Addressing_Value) {
  9323. // NOTE(bill): Tuples are not first class thus never named
  9324. if (o->type->kind == Type_Tuple) {
  9325. isize count = o->type->Tuple.variables.count;
  9326. error(o->expr,
  9327. "%td-valued expression found where single value expected", count);
  9328. o->mode = Addressing_Invalid;
  9329. GB_ASSERT(count != 1);
  9330. }
  9331. }
  9332. }
  9333. void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9334. check_multi_expr(c, o, e);
  9335. check_not_tuple(c, o);
  9336. }
  9337. void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9338. check_expr_base(c, o, e, type_hint);
  9339. check_not_tuple(c, o);
  9340. error_operand_no_value(o);
  9341. }
  9342. bool is_exact_value_zero(ExactValue const &v) {
  9343. switch (v.kind) {
  9344. case ExactValue_Invalid:
  9345. return true;
  9346. case ExactValue_Bool:
  9347. return !v.value_bool;
  9348. case ExactValue_String:
  9349. return v.value_string.len == 0;
  9350. case ExactValue_Integer:
  9351. return big_int_is_zero(&v.value_integer);
  9352. case ExactValue_Float:
  9353. return v.value_float == 0.0;
  9354. case ExactValue_Complex:
  9355. if (v.value_complex) {
  9356. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9357. }
  9358. return true;
  9359. case ExactValue_Quaternion:
  9360. if (v.value_quaternion) {
  9361. return v.value_quaternion->real == 0.0 &&
  9362. v.value_quaternion->imag == 0.0 &&
  9363. v.value_quaternion->jmag == 0.0 &&
  9364. v.value_quaternion->kmag == 0.0;
  9365. }
  9366. return true;
  9367. case ExactValue_Pointer:
  9368. return v.value_pointer == 0;
  9369. case ExactValue_Compound:
  9370. if (v.value_compound == nullptr) {
  9371. return true;
  9372. } else {
  9373. ast_node(cl, CompoundLit, v.value_compound);
  9374. if (cl->elems.count == 0) {
  9375. return true;
  9376. } else {
  9377. for_array(i, cl->elems) {
  9378. Ast *elem = cl->elems[i];
  9379. if (elem->tav.mode != Addressing_Constant) {
  9380. // if (elem->tav.value.kind != ExactValue_Invalid) {
  9381. return false;
  9382. // }
  9383. }
  9384. if (!is_exact_value_zero(elem->tav.value)) {
  9385. return false;
  9386. }
  9387. }
  9388. return true;
  9389. }
  9390. }
  9391. case ExactValue_Procedure:
  9392. return v.value_procedure == nullptr;
  9393. case ExactValue_Typeid:
  9394. return v.value_typeid == nullptr;
  9395. }
  9396. return true;
  9397. }
  9398. gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9399. gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9400. for_array(i, params) {
  9401. if (i > 0) {
  9402. str = gb_string_appendc(str, ", ");
  9403. }
  9404. str = write_expr_to_string(str, params[i], false);
  9405. }
  9406. return str;
  9407. }
  9408. gbString string_append_string(gbString str, String string) {
  9409. if (string.len > 0) {
  9410. return gb_string_append_length(str, &string[0], string.len);
  9411. }
  9412. return str;
  9413. }
  9414. gbString string_append_token(gbString str, Token token) {
  9415. if (token.kind == Token_String) {
  9416. str = gb_string_append_rune(str, '"');
  9417. } else if (token.kind == Token_Rune) {
  9418. str = gb_string_append_rune(str, '\'');
  9419. }
  9420. str = string_append_string(str, token.string);
  9421. if (token.kind == Token_String) {
  9422. str = gb_string_append_rune(str, '"');
  9423. } else if (token.kind == Token_Rune) {
  9424. str = gb_string_append_rune(str, '\'');
  9425. }
  9426. return str;
  9427. }
  9428. gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9429. if (node == nullptr)
  9430. return str;
  9431. if (is_ast_stmt(node)) {
  9432. GB_ASSERT("stmt passed to write_expr_to_string");
  9433. }
  9434. switch (node->kind) {
  9435. default:
  9436. str = gb_string_appendc(str, "(BadExpr)");
  9437. break;
  9438. case_ast_node(i, Ident, node);
  9439. str = string_append_token(str, i->token);
  9440. case_end;
  9441. case_ast_node(i, Implicit, node);
  9442. str = string_append_token(str, *i);
  9443. case_end;
  9444. case_ast_node(bl, BasicLit, node);
  9445. str = string_append_token(str, bl->token);
  9446. case_end;
  9447. case_ast_node(bd, BasicDirective, node);
  9448. str = gb_string_append_rune(str, '#');
  9449. str = string_append_string(str, bd->name);
  9450. case_end;
  9451. case_ast_node(ud, Undef, node);
  9452. str = gb_string_appendc(str, "---");
  9453. case_end;
  9454. case_ast_node(pg, ProcGroup, node);
  9455. str = gb_string_appendc(str, "proc{");
  9456. for_array(i, pg->args) {
  9457. if (i > 0) str = gb_string_appendc(str, ", ");
  9458. str = write_expr_to_string(str, pg->args[i], shorthand);
  9459. }
  9460. str = gb_string_append_rune(str, '}');
  9461. case_end;
  9462. case_ast_node(pl, ProcLit, node);
  9463. str = write_expr_to_string(str, pl->type, shorthand);
  9464. if (pl->body) {
  9465. str = gb_string_appendc(str, " {...}");
  9466. } else {
  9467. str = gb_string_appendc(str, " ---");
  9468. }
  9469. case_end;
  9470. case_ast_node(cl, CompoundLit, node);
  9471. str = write_expr_to_string(str, cl->type, shorthand);
  9472. str = gb_string_append_rune(str, '{');
  9473. if (shorthand) {
  9474. str = gb_string_appendc(str, "...");
  9475. } else {
  9476. for_array(i, cl->elems) {
  9477. if (i > 0) str = gb_string_appendc(str, ", ");
  9478. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9479. }
  9480. }
  9481. str = gb_string_append_rune(str, '}');
  9482. case_end;
  9483. case_ast_node(te, TagExpr, node);
  9484. str = gb_string_append_rune(str, '#');
  9485. str = string_append_token(str, te->name);
  9486. str = write_expr_to_string(str, te->expr, shorthand);
  9487. case_end;
  9488. case_ast_node(ue, UnaryExpr, node);
  9489. str = string_append_token(str, ue->op);
  9490. str = write_expr_to_string(str, ue->expr, shorthand);
  9491. case_end;
  9492. case_ast_node(de, DerefExpr, node);
  9493. str = write_expr_to_string(str, de->expr, shorthand);
  9494. str = gb_string_append_rune(str, '^');
  9495. case_end;
  9496. case_ast_node(be, BinaryExpr, node);
  9497. str = write_expr_to_string(str, be->left, shorthand);
  9498. str = gb_string_append_rune(str, ' ');
  9499. str = string_append_token(str, be->op);
  9500. str = gb_string_append_rune(str, ' ');
  9501. str = write_expr_to_string(str, be->right, shorthand);
  9502. case_end;
  9503. case_ast_node(te, TernaryExpr, node);
  9504. str = write_expr_to_string(str, te->cond, shorthand);
  9505. str = gb_string_appendc(str, " ? ");
  9506. str = write_expr_to_string(str, te->x, shorthand);
  9507. str = gb_string_appendc(str, " : ");
  9508. str = write_expr_to_string(str, te->y, shorthand);
  9509. case_end;
  9510. case_ast_node(te, TernaryIfExpr, node);
  9511. str = write_expr_to_string(str, te->x, shorthand);
  9512. str = gb_string_appendc(str, " if ");
  9513. str = write_expr_to_string(str, te->cond, shorthand);
  9514. str = gb_string_appendc(str, " else ");
  9515. str = write_expr_to_string(str, te->y, shorthand);
  9516. case_end;
  9517. case_ast_node(te, TernaryWhenExpr, node);
  9518. str = write_expr_to_string(str, te->x, shorthand);
  9519. str = gb_string_appendc(str, " when ");
  9520. str = write_expr_to_string(str, te->cond, shorthand);
  9521. str = gb_string_appendc(str, " else ");
  9522. str = write_expr_to_string(str, te->y, shorthand);
  9523. case_end;
  9524. case_ast_node(pe, ParenExpr, node);
  9525. str = gb_string_append_rune(str, '(');
  9526. str = write_expr_to_string(str, pe->expr, shorthand);
  9527. str = gb_string_append_rune(str, ')');
  9528. case_end;
  9529. case_ast_node(se, SelectorExpr, node);
  9530. str = write_expr_to_string(str, se->expr, shorthand);
  9531. str = string_append_token(str, se->token);
  9532. str = write_expr_to_string(str, se->selector, shorthand);
  9533. case_end;
  9534. case_ast_node(se, ImplicitSelectorExpr, node);
  9535. str = gb_string_append_rune(str, '.');
  9536. str = write_expr_to_string(str, se->selector, shorthand);
  9537. case_end;
  9538. case_ast_node(se, SelectorCallExpr, node);
  9539. str = write_expr_to_string(str, se->expr, shorthand);
  9540. str = gb_string_appendc(str, "(");
  9541. ast_node(ce, CallExpr, se->call);
  9542. isize start = se->modified_call ? 1 : 0;
  9543. for (isize i = start; i < ce->args.count; i++) {
  9544. Ast *arg = ce->args[i];
  9545. if (i > start) {
  9546. str = gb_string_appendc(str, ", ");
  9547. }
  9548. str = write_expr_to_string(str, arg, shorthand);
  9549. }
  9550. str = gb_string_appendc(str, ")");
  9551. case_end;
  9552. case_ast_node(ta, TypeAssertion, node);
  9553. str = write_expr_to_string(str, ta->expr, shorthand);
  9554. str = gb_string_appendc(str, ".(");
  9555. str = write_expr_to_string(str, ta->type, shorthand);
  9556. str = gb_string_append_rune(str, ')');
  9557. case_end;
  9558. case_ast_node(tc, TypeCast, node);
  9559. str = string_append_token(str, tc->token);
  9560. str = gb_string_append_rune(str, '(');
  9561. str = write_expr_to_string(str, tc->type, shorthand);
  9562. str = gb_string_append_rune(str, ')');
  9563. str = write_expr_to_string(str, tc->expr, shorthand);
  9564. case_end;
  9565. case_ast_node(ac, AutoCast, node);
  9566. str = string_append_token(str, ac->token);
  9567. str = gb_string_append_rune(str, ' ');
  9568. str = write_expr_to_string(str, ac->expr, shorthand);
  9569. case_end;
  9570. case_ast_node(ie, IndexExpr, node);
  9571. str = write_expr_to_string(str, ie->expr, shorthand);
  9572. str = gb_string_append_rune(str, '[');
  9573. str = write_expr_to_string(str, ie->index, shorthand);
  9574. str = gb_string_append_rune(str, ']');
  9575. case_end;
  9576. case_ast_node(se, SliceExpr, node);
  9577. str = write_expr_to_string(str, se->expr, shorthand);
  9578. str = gb_string_append_rune(str, '[');
  9579. str = write_expr_to_string(str, se->low, shorthand);
  9580. str = string_append_token(str, se->interval);
  9581. str = write_expr_to_string(str, se->high, shorthand);
  9582. str = gb_string_append_rune(str, ']');
  9583. case_end;
  9584. case_ast_node(e, Ellipsis, node);
  9585. str = gb_string_appendc(str, "..");
  9586. str = write_expr_to_string(str, e->expr, shorthand);
  9587. case_end;
  9588. case_ast_node(fv, FieldValue, node);
  9589. str = write_expr_to_string(str, fv->field, shorthand);
  9590. str = gb_string_appendc(str, " = ");
  9591. str = write_expr_to_string(str, fv->value, shorthand);
  9592. case_end;
  9593. case_ast_node(ht, HelperType, node);
  9594. str = gb_string_appendc(str, "#type ");
  9595. str = write_expr_to_string(str, ht->type, shorthand);
  9596. case_end;
  9597. case_ast_node(ht, DistinctType, node);
  9598. str = gb_string_appendc(str, "distinct ");
  9599. str = write_expr_to_string(str, ht->type, shorthand);
  9600. case_end;
  9601. case_ast_node(pt, PolyType, node);
  9602. str = gb_string_append_rune(str, '$');
  9603. str = write_expr_to_string(str, pt->type, shorthand);
  9604. if (pt->specialization != nullptr) {
  9605. str = gb_string_append_rune(str, '/');
  9606. str = write_expr_to_string(str, pt->specialization, shorthand);
  9607. }
  9608. case_end;
  9609. case_ast_node(pt, PointerType, node);
  9610. str = gb_string_append_rune(str, '^');
  9611. str = write_expr_to_string(str, pt->type, shorthand);
  9612. case_end;
  9613. case_ast_node(at, ArrayType, node);
  9614. str = gb_string_append_rune(str, '[');
  9615. if (at->count != nullptr &&
  9616. at->count->kind == Ast_UnaryExpr &&
  9617. at->count->UnaryExpr.op.kind == Token_Question) {
  9618. str = gb_string_appendc(str, "?");
  9619. } else {
  9620. str = write_expr_to_string(str, at->count, shorthand);
  9621. }
  9622. str = gb_string_append_rune(str, ']');
  9623. str = write_expr_to_string(str, at->elem, shorthand);
  9624. case_end;
  9625. case_ast_node(at, DynamicArrayType, node);
  9626. str = gb_string_appendc(str, "[dynamic]");
  9627. str = write_expr_to_string(str, at->elem, shorthand);
  9628. case_end;
  9629. case_ast_node(bs, BitSetType, node);
  9630. str = gb_string_appendc(str, "bit_set[");
  9631. str = write_expr_to_string(str, bs->elem, shorthand);
  9632. str = gb_string_appendc(str, "]");
  9633. case_end;
  9634. case_ast_node(mt, MapType, node);
  9635. str = gb_string_appendc(str, "map[");
  9636. str = write_expr_to_string(str, mt->key, shorthand);
  9637. str = gb_string_append_rune(str, ']');
  9638. str = write_expr_to_string(str, mt->value, shorthand);
  9639. case_end;
  9640. case_ast_node(f, Field, node);
  9641. if (f->flags&FieldFlag_using) {
  9642. str = gb_string_appendc(str, "using ");
  9643. }
  9644. if (f->flags&FieldFlag_no_alias) {
  9645. str = gb_string_appendc(str, "#no_alias ");
  9646. }
  9647. if (f->flags&FieldFlag_c_vararg) {
  9648. str = gb_string_appendc(str, "#c_vararg ");
  9649. }
  9650. if (f->flags&FieldFlag_auto_cast) {
  9651. str = gb_string_appendc(str, "auto_cast ");
  9652. }
  9653. for_array(i, f->names) {
  9654. Ast *name = f->names[i];
  9655. if (i > 0) str = gb_string_appendc(str, ", ");
  9656. str = write_expr_to_string(str, name, shorthand);
  9657. }
  9658. if (f->names.count > 0) {
  9659. if (f->type == nullptr && f->default_value != nullptr) {
  9660. str = gb_string_append_rune(str, ' ');
  9661. }
  9662. str = gb_string_appendc(str, ":");
  9663. }
  9664. if (f->type != nullptr) {
  9665. str = gb_string_append_rune(str, ' ');
  9666. str = write_expr_to_string(str, f->type, shorthand);
  9667. }
  9668. if (f->default_value != nullptr) {
  9669. if (f->type != nullptr) {
  9670. str = gb_string_append_rune(str, ' ');
  9671. }
  9672. str = gb_string_appendc(str, "= ");
  9673. str = write_expr_to_string(str, f->default_value, shorthand);
  9674. }
  9675. case_end;
  9676. case_ast_node(f, FieldList, node);
  9677. bool has_name = false;
  9678. for_array(i, f->list) {
  9679. ast_node(field, Field, f->list[i]);
  9680. if (field->names.count > 1) {
  9681. has_name = true;
  9682. break;
  9683. }
  9684. if (field->names.count == 0) {
  9685. continue;
  9686. }
  9687. if (!is_blank_ident(field->names[0])) {
  9688. has_name = true;
  9689. break;
  9690. }
  9691. }
  9692. for_array(i, f->list) {
  9693. if (i > 0) str = gb_string_appendc(str, ", ");
  9694. if (has_name) {
  9695. str = write_expr_to_string(str, f->list[i], shorthand);
  9696. } else {
  9697. ast_node(field, Field, f->list[i]);
  9698. if (field->flags&FieldFlag_using) {
  9699. str = gb_string_appendc(str, "using ");
  9700. }
  9701. if (field->flags&FieldFlag_no_alias) {
  9702. str = gb_string_appendc(str, "#no_alias ");
  9703. }
  9704. if (field->flags&FieldFlag_c_vararg) {
  9705. str = gb_string_appendc(str, "#c_vararg ");
  9706. }
  9707. str = write_expr_to_string(str, field->type, shorthand);
  9708. }
  9709. }
  9710. case_end;
  9711. case_ast_node(ce, CallExpr, node);
  9712. switch (ce->inlining) {
  9713. case ProcInlining_inline:
  9714. str = gb_string_appendc(str, "#force_inline ");
  9715. break;
  9716. case ProcInlining_no_inline:
  9717. str = gb_string_appendc(str, "#force_no_inline ");
  9718. break;
  9719. }
  9720. str = write_expr_to_string(str, ce->proc, shorthand);
  9721. str = gb_string_appendc(str, "(");
  9722. for_array(i, ce->args) {
  9723. Ast *arg = ce->args[i];
  9724. if (i > 0) {
  9725. str = gb_string_appendc(str, ", ");
  9726. }
  9727. str = write_expr_to_string(str, arg, shorthand);
  9728. }
  9729. str = gb_string_appendc(str, ")");
  9730. case_end;
  9731. case_ast_node(tt, TypeidType, node);
  9732. str = gb_string_appendc(str, "typeid");
  9733. if (tt->specialization) {
  9734. str = gb_string_appendc(str, "/");
  9735. str = write_expr_to_string(str, tt->specialization, shorthand);
  9736. }
  9737. case_end;
  9738. case_ast_node(pt, ProcType, node);
  9739. str = gb_string_appendc(str, "proc(");
  9740. str = write_expr_to_string(str, pt->params, shorthand);
  9741. str = gb_string_appendc(str, ")");
  9742. if (pt->results != nullptr) {
  9743. str = gb_string_appendc(str, " -> ");
  9744. bool parens_needed = false;
  9745. if (pt->results && pt->results->kind == Ast_FieldList) {
  9746. for_array(i, pt->results->FieldList.list) {
  9747. Ast *field = pt->results->FieldList.list[i];
  9748. ast_node(f, Field, field);
  9749. if (f->names.count != 0) {
  9750. parens_needed = true;
  9751. break;
  9752. }
  9753. }
  9754. }
  9755. if (parens_needed) {
  9756. str = gb_string_append_rune(str, '(');
  9757. }
  9758. str = write_expr_to_string(str, pt->results, shorthand);
  9759. if (parens_needed) {
  9760. str = gb_string_append_rune(str, ')');
  9761. }
  9762. }
  9763. case_end;
  9764. case_ast_node(st, StructType, node);
  9765. str = gb_string_appendc(str, "struct ");
  9766. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9767. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9768. str = gb_string_append_rune(str, '{');
  9769. if (shorthand) {
  9770. str = gb_string_appendc(str, "...");
  9771. } else {
  9772. str = write_struct_fields_to_string(str, st->fields);
  9773. }
  9774. str = gb_string_append_rune(str, '}');
  9775. case_end;
  9776. case_ast_node(st, UnionType, node);
  9777. str = gb_string_appendc(str, "union ");
  9778. str = gb_string_append_rune(str, '{');
  9779. if (shorthand) {
  9780. str = gb_string_appendc(str, "...");
  9781. } else {
  9782. str = write_struct_fields_to_string(str, st->variants);
  9783. }
  9784. str = gb_string_append_rune(str, '}');
  9785. case_end;
  9786. case_ast_node(et, EnumType, node);
  9787. str = gb_string_appendc(str, "enum ");
  9788. if (et->base_type != nullptr) {
  9789. str = write_expr_to_string(str, et->base_type, shorthand);
  9790. str = gb_string_append_rune(str, ' ');
  9791. }
  9792. str = gb_string_append_rune(str, '{');
  9793. if (shorthand) {
  9794. str = gb_string_appendc(str, "...");
  9795. } else {
  9796. for_array(i, et->fields) {
  9797. if (i > 0) {
  9798. str = gb_string_appendc(str, ", ");
  9799. }
  9800. str = write_expr_to_string(str, et->fields[i], shorthand);
  9801. }
  9802. }
  9803. str = gb_string_append_rune(str, '}');
  9804. case_end;
  9805. case_ast_node(rt, RelativeType, node);
  9806. str = write_expr_to_string(str, rt->tag, shorthand);
  9807. str = gb_string_appendc(str, "" );
  9808. str = write_expr_to_string(str, rt->type, shorthand);
  9809. case_end;
  9810. case_ast_node(ia, InlineAsmExpr, node);
  9811. str = gb_string_appendc(str, "asm(");
  9812. for_array(i, ia->param_types) {
  9813. if (i > 0) {
  9814. str = gb_string_appendc(str, ", ");
  9815. }
  9816. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9817. }
  9818. str = gb_string_appendc(str, ")");
  9819. if (ia->return_type != nullptr) {
  9820. str = gb_string_appendc(str, " -> ");
  9821. str = write_expr_to_string(str, ia->return_type, shorthand);
  9822. }
  9823. if (ia->has_side_effects) {
  9824. str = gb_string_appendc(str, " #side_effects");
  9825. }
  9826. if (ia->is_align_stack) {
  9827. str = gb_string_appendc(str, " #stack_align");
  9828. }
  9829. if (ia->dialect) {
  9830. str = gb_string_appendc(str, " #");
  9831. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9832. }
  9833. str = gb_string_appendc(str, " {");
  9834. if (shorthand) {
  9835. str = gb_string_appendc(str, "...");
  9836. } else {
  9837. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9838. str = gb_string_appendc(str, ", ");
  9839. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9840. }
  9841. str = gb_string_appendc(str, "}");
  9842. case_end;
  9843. }
  9844. return str;
  9845. }
  9846. gbString expr_to_string(Ast *expression) {
  9847. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9848. }
  9849. gbString expr_to_string_shorthand(Ast *expression) {
  9850. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9851. }