check_expr.cpp 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_ArgumentCount,
  9. CallArgumentError_TooFewArguments,
  10. CallArgumentError_TooManyArguments,
  11. CallArgumentError_InvalidFieldValue,
  12. CallArgumentError_ParameterNotFound,
  13. CallArgumentError_ParameterMissing,
  14. CallArgumentError_DuplicateParameter,
  15. CallArgumentError_NoneConstantParameter,
  16. };
  17. enum CallArgumentErrorMode {
  18. CallArgumentMode_NoErrors,
  19. CallArgumentMode_ShowErrors,
  20. };
  21. struct CallArgumentData {
  22. Entity *gen_entity;
  23. i64 score;
  24. Type * result_type;
  25. };
  26. struct PolyProcData {
  27. Entity * gen_entity;
  28. ProcInfo proc_info;
  29. };
  30. struct ValidIndexAndScore {
  31. isize index;
  32. i64 score;
  33. };
  34. int valid_index_and_score_cmp(void const *a, void const *b) {
  35. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  36. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  37. return sj < si ? -1 : sj > si;
  38. }
  39. #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)
  40. typedef CALL_ARGUMENT_CHECKER(CallArgumentCheckerType);
  41. void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  42. void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  43. void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint = nullptr);
  44. ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  45. void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  46. Type * check_type (CheckerContext *c, Ast *expression);
  47. Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  48. Type * make_optional_ok_type (Type *value);
  49. void check_type_decl (CheckerContext *c, Entity *e, Ast *type_expr, Type *def);
  50. Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  51. Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  52. Entity * find_polymorphic_struct_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> ordered_operands);
  53. void check_not_tuple (CheckerContext *c, Operand *operand);
  54. void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  55. gbString expr_to_string (Ast *expression);
  56. void check_entity_decl (CheckerContext *c, Entity *e, DeclInfo *decl, Type *named_type);
  57. void check_const_decl (CheckerContext *c, Entity *e, Ast *type_expr, Ast *init_expr, Type *named_type);
  58. void check_proc_body (CheckerContext *c, Token token, DeclInfo *decl, Type *type, Ast *body);
  59. void update_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  60. bool check_is_terminating (Ast *node);
  61. bool check_has_break (Ast *stmt, bool implicit);
  62. void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  63. void check_stmt_list (CheckerContext *c, Array<Ast *> const &stmts, u32 flags);
  64. void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  65. bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  66. bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> *operands = nullptr);
  67. void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  68. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  69. CallArgumentData check_call_arguments (CheckerContext *c, Operand *operand, Type *proc_type, Ast *call);
  70. Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  71. void error_operand_not_expression(Operand *o) {
  72. if (o->mode == Addressing_Type) {
  73. gbString err = expr_to_string(o->expr);
  74. error(o->expr, "'%s' is not an expression but a type", err);
  75. gb_string_free(err);
  76. o->mode = Addressing_Invalid;
  77. }
  78. }
  79. void error_operand_no_value(Operand *o) {
  80. if (o->mode == Addressing_NoValue) {
  81. gbString err = expr_to_string(o->expr);
  82. Ast *x = unparen_expr(o->expr);
  83. if (x->kind == Ast_CallExpr) {
  84. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  85. } else {
  86. error(o->expr, "'%s' used as a value", err);
  87. }
  88. gb_string_free(err);
  89. o->mode = Addressing_Invalid;
  90. }
  91. }
  92. void check_scope_decls(CheckerContext *c, Array<Ast *> const &nodes, isize reserve_size) {
  93. Scope *s = c->scope;
  94. check_collect_entities(c, nodes);
  95. for_array(i, s->elements.entries) {
  96. Entity *e = s->elements.entries[i].value;
  97. switch (e->kind) {
  98. case Entity_Constant:
  99. case Entity_TypeName:
  100. case Entity_Procedure:
  101. break;
  102. default:
  103. continue;
  104. }
  105. DeclInfo *d = decl_info_of_entity(e);
  106. if (d != nullptr) {
  107. check_entity_decl(c, e, d, nullptr);
  108. }
  109. }
  110. }
  111. bool check_is_assignable_to_using_subtype(Type *src, Type *dst) {
  112. bool src_is_ptr = false;
  113. Type *prev_src = src;
  114. src = type_deref(src);
  115. src_is_ptr = src != prev_src;
  116. src = base_type(src);
  117. if (!is_type_struct(src)) {
  118. return false;
  119. }
  120. for_array(i, src->Struct.fields) {
  121. Entity *f = src->Struct.fields[i];
  122. if (f->kind != Entity_Variable || (f->flags&EntityFlag_Using) == 0) {
  123. continue;
  124. }
  125. if (are_types_identical(f->type, dst)) {
  126. return true;
  127. }
  128. if (src_is_ptr && is_type_pointer(dst)) {
  129. if (are_types_identical(f->type, type_deref(dst))) {
  130. return true;
  131. }
  132. }
  133. bool ok = check_is_assignable_to_using_subtype(f->type, dst);
  134. if (ok) {
  135. return true;
  136. }
  137. }
  138. return false;
  139. }
  140. bool find_or_generate_polymorphic_procedure(CheckerContext *c, Entity *base_entity, Type *type,
  141. Array<Operand> *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  142. ///////////////////////////////////////////////////////////////////////////////
  143. // //
  144. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  145. // //
  146. ///////////////////////////////////////////////////////////////////////////////
  147. if (base_entity == nullptr) {
  148. return false;
  149. }
  150. if (!is_type_proc(base_entity->type)) {
  151. return false;
  152. }
  153. String name = base_entity->token.string;
  154. Type *src = base_type(base_entity->type);
  155. Type *dst = nullptr;
  156. if (type != nullptr) dst = base_type(type);
  157. if (param_operands == nullptr) {
  158. GB_ASSERT(dst != nullptr);
  159. }
  160. if (param_operands != nullptr) {
  161. GB_ASSERT(dst == nullptr);
  162. }
  163. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  164. return false;
  165. }
  166. if (dst != nullptr) {
  167. if (dst->Proc.is_polymorphic) {
  168. return false;
  169. }
  170. if (dst->Proc.param_count != src->Proc.param_count ||
  171. dst->Proc.result_count != src->Proc.result_count) {
  172. return false;
  173. }
  174. }
  175. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  176. if (old_decl == nullptr) {
  177. return false;
  178. }
  179. gbAllocator a = heap_allocator();
  180. Array<Operand> operands = {};
  181. if (param_operands) {
  182. operands = *param_operands;
  183. } else {
  184. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  185. for (isize i = 0; i < dst->Proc.param_count; i++) {
  186. Entity *param = dst->Proc.params->Tuple.variables[i];
  187. Operand o = {Addressing_Value};
  188. o.type = param->type;
  189. array_add(&operands, o);
  190. }
  191. }
  192. defer (if (param_operands == nullptr) {
  193. array_free(&operands);
  194. });
  195. CheckerContext nctx = *c;
  196. Scope *scope = create_scope(base_entity->scope, a);
  197. scope->flags |= ScopeFlag_Proc;
  198. nctx.scope = scope;
  199. nctx.allow_polymorphic_types = true;
  200. if (nctx.polymorphic_scope == nullptr) {
  201. nctx.polymorphic_scope = scope;
  202. }
  203. if (param_operands == nullptr) {
  204. // c->no_polymorphic_errors = false;
  205. }
  206. bool generate_type_again = nctx.no_polymorphic_errors;
  207. auto *pt = &src->Proc;
  208. // NOTE(bill): This is slightly memory leaking if the type already exists
  209. // Maybe it's better to check with the previous types first?
  210. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  211. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  212. if (!success) {
  213. return false;
  214. }
  215. auto *found_gen_procs = map_get(&nctx.info->gen_procs, hash_pointer(base_entity->identifier));
  216. if (found_gen_procs) {
  217. auto procs = *found_gen_procs;
  218. for_array(i, procs) {
  219. Entity *other = procs[i];
  220. Type *pt = base_type(other->type);
  221. if (are_types_identical(pt, final_proc_type)) {
  222. if (poly_proc_data) {
  223. poly_proc_data->gen_entity = other;
  224. }
  225. return true;
  226. }
  227. }
  228. }
  229. if (generate_type_again) {
  230. // LEAK TODO(bill): This is technically a memory leak as it has to generate the type twice
  231. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  232. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  233. nctx.no_polymorphic_errors = false;
  234. // NOTE(bill): Reset scope from the failed procedure type
  235. scope_reset(scope);
  236. success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  237. if (!success) {
  238. return false;
  239. }
  240. if (found_gen_procs) {
  241. auto procs = *found_gen_procs;
  242. for_array(i, procs) {
  243. Entity *other = procs[i];
  244. Type *pt = base_type(other->type);
  245. if (are_types_identical(pt, final_proc_type)) {
  246. if (poly_proc_data) {
  247. poly_proc_data->gen_entity = other;
  248. }
  249. return true;
  250. }
  251. }
  252. }
  253. }
  254. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  255. ast_node(pl, ProcLit, proc_lit);
  256. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  257. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  258. final_proc_type->Proc.is_poly_specialized = true;
  259. final_proc_type->Proc.is_polymorphic = true;
  260. for (isize i = 0; i < operands.count; i++) {
  261. Operand o = operands[i];
  262. if (final_proc_type == o.type ||
  263. base_entity->type == o.type) {
  264. // NOTE(bill): Cycle
  265. final_proc_type->Proc.is_poly_specialized = false;
  266. break;
  267. }
  268. }
  269. u64 tags = base_entity->Procedure.tags;
  270. Ast *ident = clone_ast(base_entity->identifier);
  271. Token token = ident->Ident.token;
  272. DeclInfo *d = make_decl_info(nctx.allocator, scope, old_decl->parent);
  273. d->gen_proc_type = final_proc_type;
  274. d->type_expr = pl->type;
  275. d->proc_lit = proc_lit;
  276. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  277. entity->identifier = ident;
  278. add_entity_and_decl_info(&nctx, ident, entity, d);
  279. // NOTE(bill): Set the scope afterwards as this is not real overloading
  280. entity->scope = scope->parent;
  281. entity->pkg = base_entity->pkg;
  282. AstFile *file = nullptr;
  283. {
  284. Scope *s = entity->scope;
  285. while (s != nullptr && s->file == nullptr) {
  286. file = s->file;
  287. s = s->parent;
  288. }
  289. }
  290. ProcInfo proc_info = {};
  291. proc_info.file = file;
  292. proc_info.token = token;
  293. proc_info.decl = d;
  294. proc_info.type = final_proc_type;
  295. proc_info.body = pl->body;
  296. proc_info.tags = tags;
  297. proc_info.generated_from_polymorphic = true;
  298. proc_info.poly_def_node = poly_def_node;
  299. if (found_gen_procs) {
  300. array_add(found_gen_procs, entity);
  301. } else {
  302. auto array = array_make<Entity *>(heap_allocator());
  303. array_add(&array, entity);
  304. map_set(&nctx.checker->info.gen_procs, hash_pointer(base_entity->identifier), array);
  305. }
  306. GB_ASSERT(entity != nullptr);
  307. if (poly_proc_data) {
  308. poly_proc_data->gen_entity = entity;
  309. poly_proc_data->proc_info = proc_info;
  310. }
  311. // NOTE(bill): Check the newly generated procedure body
  312. check_procedure_later(nctx.checker, proc_info);
  313. return true;
  314. }
  315. bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  316. if (operand->expr == nullptr) return false;
  317. Entity *base_entity = entity_of_ident(operand->expr);
  318. if (base_entity == nullptr) return false;
  319. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  320. }
  321. bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  322. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  323. }
  324. bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  325. bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  326. bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  327. i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  328. if (operand->mode == Addressing_Invalid ||
  329. type == t_invalid) {
  330. return -1;
  331. }
  332. if (operand->mode == Addressing_Builtin) {
  333. return -1;
  334. }
  335. if (operand->mode == Addressing_Type) {
  336. return -1;
  337. }
  338. Type *s = operand->type;
  339. if (are_types_identical(s, type)) {
  340. return 0;
  341. }
  342. Type *src = base_type(s);
  343. Type *dst = base_type(type);
  344. if (is_type_untyped_undef(src)) {
  345. if (type_has_undef(dst)) {
  346. return 1;
  347. }
  348. return -1;
  349. }
  350. if (is_type_untyped_nil(src)) {
  351. if (type_has_nil(dst)) {
  352. return 1;
  353. }
  354. return -1;
  355. }
  356. if (is_type_untyped(src)) {
  357. if (is_type_any(dst)) {
  358. // NOTE(bill): Anything can cast to 'Any'
  359. add_type_info_type(c, s);
  360. return 10;
  361. }
  362. if (dst->kind == Type_Basic) {
  363. if (operand->mode == Addressing_Constant) {
  364. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  365. if (is_type_typed(dst) && src->kind == Type_Basic) {
  366. switch (src->Basic.kind) {
  367. case Basic_UntypedRune:
  368. if (is_type_integer(dst) || is_type_rune(dst)) {
  369. return 1;
  370. }
  371. break;
  372. case Basic_UntypedInteger:
  373. if (is_type_integer(dst) || is_type_rune(dst)) {
  374. return 1;
  375. }
  376. break;
  377. case Basic_UntypedFloat:
  378. if (is_type_float(dst)) {
  379. return 1;
  380. }
  381. break;
  382. case Basic_UntypedComplex:
  383. if (is_type_complex(dst)) {
  384. return 1;
  385. }
  386. break;
  387. }
  388. }
  389. return 2;
  390. }
  391. return -1;
  392. }
  393. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedRune) {
  394. if (is_type_integer(dst) || is_type_rune(dst)) {
  395. if (is_type_typed(type)) {
  396. return 2;
  397. }
  398. return 1;
  399. }
  400. return -1;
  401. }
  402. if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedBool) {
  403. if (is_type_boolean(dst)) {
  404. if (is_type_typed(type)) {
  405. return 2;
  406. }
  407. return 1;
  408. }
  409. return -1;
  410. }
  411. }
  412. }
  413. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  414. if (c->in_enum_type) {
  415. return 3;
  416. }
  417. }
  418. if (is_type_bit_field_value(operand->type) && is_type_integer(type)) {
  419. Type *bfv = base_type(operand->type);
  420. i32 bits = bfv->BitFieldValue.bits;
  421. i32 size = next_pow2((bits+7)/8);
  422. i32 dst_size = cast(i32)type_size_of(type);
  423. i32 diff = gb_abs(dst_size - size);
  424. // TODO(bill): figure out a decent rule here
  425. return 1;
  426. }
  427. if (check_is_assignable_to_using_subtype(operand->type, type)) {
  428. return 4;
  429. }
  430. // ^T <- rawptr
  431. #if 0
  432. // TODO(bill): Should C-style (not C++) pointer cast be allowed?
  433. if (is_type_pointer(dst) && is_type_rawptr(src)) {
  434. return true;
  435. }
  436. #endif
  437. #if 1
  438. // TODO(bill): Should I allow this implicit conversion at all?!
  439. // rawptr <- ^T
  440. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  441. return 5;
  442. }
  443. #endif
  444. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  445. bool modify_type = !c->no_polymorphic_errors;
  446. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  447. return 2;
  448. }
  449. }
  450. if (is_type_union(dst)) {
  451. for_array(i, dst->Union.variants) {
  452. Type *vt = dst->Union.variants[i];
  453. if (are_types_identical(vt, s)) {
  454. return 1;
  455. }
  456. }
  457. }
  458. if (is_type_proc(dst)) {
  459. if (are_types_identical(src, dst)) {
  460. return 3;
  461. }
  462. PolyProcData poly_proc_data = {};
  463. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  464. add_entity_use(c, operand->expr, poly_proc_data.gen_entity);
  465. return 4;
  466. }
  467. }
  468. if (is_type_array(dst)) {
  469. Type *elem = base_array_type(dst);
  470. i64 distance = check_distance_between_types(c, operand, elem);
  471. if (distance >= 0) {
  472. return distance + 6;
  473. }
  474. }
  475. if (is_type_any(dst)) {
  476. if (!is_type_polymorphic(src)) {
  477. if (operand->mode == Addressing_Context && operand->type == t_context) {
  478. return -1;
  479. } else {
  480. // NOTE(bill): Anything can cast to 'Any'
  481. add_type_info_type(c, s);
  482. return 10;
  483. }
  484. }
  485. }
  486. Ast *expr = unparen_expr(operand->expr);
  487. if (expr != nullptr && expr->kind == Ast_AutoCast) {
  488. Operand x = *operand;
  489. x.expr = expr->AutoCast.expr;
  490. bool ok = check_cast_internal(c, &x, type);
  491. if (ok) {
  492. return 10;
  493. }
  494. }
  495. return -1;
  496. }
  497. i64 assign_score_function(i64 distance) {
  498. // TODO(bill): A decent score function
  499. return gb_max(1000000 - distance*distance, 0);
  500. }
  501. bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_) {
  502. i64 score = 0;
  503. i64 distance = check_distance_between_types(c, operand, type);
  504. bool ok = distance >= 0;
  505. if (ok) {
  506. score = assign_score_function(distance);
  507. }
  508. if (score_) *score_ = score;
  509. return ok;
  510. }
  511. bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  512. i64 score = 0;
  513. return check_is_assignable_to_with_score(c, operand, type, &score);
  514. }
  515. // NOTE(bill): 'content_name' is for debugging and error messages
  516. void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  517. check_not_tuple(c, operand);
  518. if (operand->mode == Addressing_Invalid) {
  519. return;
  520. }
  521. #if 0
  522. if (operand->mode == Addressing_Type) {
  523. Type *t = base_type(type);
  524. if (t->kind == Type_Pointer &&
  525. t->Pointer.elem == t_type_info) {
  526. add_type_info_type(c, type);
  527. return;
  528. }
  529. }
  530. #endif
  531. if (is_type_untyped(operand->type)) {
  532. Type *target_type = type;
  533. if (type == nullptr || is_type_any(type)) {
  534. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  535. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  536. operand->mode = Addressing_Invalid;
  537. return;
  538. }
  539. if (type == nullptr && is_type_untyped_undef(operand->type)) {
  540. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  541. operand->mode = Addressing_Invalid;
  542. return;
  543. }
  544. target_type = default_type(operand->type);
  545. if (type != nullptr && !is_type_any(type)) {
  546. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  547. }
  548. add_type_info_type(c, type);
  549. add_type_info_type(c, target_type);
  550. }
  551. convert_to_typed(c, operand, target_type);
  552. if (operand->mode == Addressing_Invalid) {
  553. return;
  554. }
  555. }
  556. if (type == nullptr) {
  557. return;
  558. }
  559. if (operand->mode == Addressing_ProcGroup) {
  560. Array<Entity *> procs = proc_group_entities(c, *operand);
  561. bool good = false;
  562. // NOTE(bill): These should be done
  563. for_array(i, procs) {
  564. Type *t = base_type(procs[i]->type);
  565. if (t == t_invalid) {
  566. continue;
  567. }
  568. Operand x = {};
  569. x.mode = Addressing_Value;
  570. x.type = t;
  571. if (check_is_assignable_to(c, &x, type)) {
  572. Entity *e = procs[i];
  573. add_entity_use(c, operand->expr, e);
  574. good = true;
  575. break;
  576. }
  577. }
  578. if (!good) {
  579. gbString expr_str = expr_to_string(operand->expr);
  580. gbString op_type_str = type_to_string(operand->type);
  581. gbString type_str = type_to_string(type);
  582. defer (gb_string_free(type_str));
  583. defer (gb_string_free(op_type_str));
  584. defer (gb_string_free(expr_str));
  585. // TODO(bill): is this a good enough error message?
  586. error(operand->expr,
  587. "Cannot assign overloaded procedure '%s' to '%s' in %.*s",
  588. expr_str,
  589. op_type_str,
  590. LIT(context_name));
  591. operand->mode = Addressing_Invalid;
  592. }
  593. return;
  594. }
  595. if (!check_is_assignable_to(c, operand, type)) {
  596. gbString expr_str = expr_to_string(operand->expr);
  597. gbString op_type_str = type_to_string(operand->type);
  598. gbString type_str = type_to_string(type);
  599. defer (gb_string_free(type_str));
  600. defer (gb_string_free(op_type_str));
  601. defer (gb_string_free(expr_str));
  602. switch (operand->mode) {
  603. case Addressing_Builtin:
  604. // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use
  605. error(operand->expr,
  606. "Cannot assign built-in procedure '%s' in %.*s",
  607. expr_str,
  608. LIT(context_name));
  609. break;
  610. case Addressing_Type:
  611. error(operand->expr,
  612. "Cannot assign '%s' which is a type in %.*s",
  613. op_type_str,
  614. LIT(context_name));
  615. break;
  616. default:
  617. // TODO(bill): is this a good enough error message?
  618. error(operand->expr,
  619. "Cannot assign value '%s' of type '%s' to '%s' in %.*s",
  620. expr_str,
  621. op_type_str,
  622. type_str,
  623. LIT(context_name));
  624. break;
  625. }
  626. operand->mode = Addressing_Invalid;
  627. return;
  628. }
  629. }
  630. bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  631. Operand o = {Addressing_Value};
  632. o.type = source;
  633. switch (poly->kind) {
  634. case Type_Basic:
  635. if (compound) return are_types_identical(poly, source);
  636. return check_is_assignable_to(c, &o, poly);
  637. case Type_Named: {
  638. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  639. return true;
  640. }
  641. if (compound || !is_type_generic(poly)) {
  642. return are_types_identical(poly, source);
  643. }
  644. return check_is_assignable_to(c, &o, poly);
  645. }
  646. case Type_Generic: {
  647. if (poly->Generic.specialized != nullptr) {
  648. Type *s = poly->Generic.specialized;
  649. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  650. return false;
  651. }
  652. }
  653. if (modify_type) {
  654. Type *ds = default_type(source);
  655. gb_memmove(poly, ds, gb_size_of(Type));
  656. }
  657. return true;
  658. }
  659. case Type_Pointer:
  660. if (source->kind == Type_Pointer) {
  661. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  662. }
  663. return false;
  664. case Type_Array:
  665. if (source->kind == Type_Array) {
  666. // IMPORTANT TODO(bill): Which is correct?
  667. // if (poly->Array.generic_count != nullptr && modify_type) {
  668. if (poly->Array.generic_count != nullptr) {
  669. Type *gt = poly->Array.generic_count;
  670. GB_ASSERT(gt->kind == Type_Generic);
  671. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  672. GB_ASSERT(e != nullptr);
  673. if (e->kind == Entity_TypeName) {
  674. poly->Array.generic_count = nullptr;
  675. poly->Array.count = source->Array.count;
  676. e->kind = Entity_Constant;
  677. e->Constant.value = exact_value_i64(source->Array.count);
  678. e->type = t_untyped_integer;
  679. } else if (e->kind == Entity_Constant) {
  680. poly->Array.generic_count = nullptr;
  681. if (e->Constant.value.kind != ExactValue_Integer) {
  682. return false;
  683. }
  684. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  685. if (count != source->Array.count) {
  686. return false;
  687. }
  688. poly->Array.count = source->Array.count;
  689. } else {
  690. return false;
  691. }
  692. }
  693. if (poly->Array.count == source->Array.count) {
  694. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  695. }
  696. }
  697. return false;
  698. case Type_DynamicArray:
  699. if (source->kind == Type_DynamicArray) {
  700. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  701. }
  702. return false;
  703. case Type_Slice:
  704. if (source->kind == Type_Slice) {
  705. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  706. }
  707. return false;
  708. case Type_Enum:
  709. return false;
  710. case Type_BitSet:
  711. return false;
  712. case Type_Union:
  713. if (source->kind == Type_Union) {
  714. TypeUnion *x = &poly->Union;
  715. TypeUnion *y = &source->Union;
  716. if (x->variants.count != y->variants.count) {
  717. return false;
  718. }
  719. for_array(i, x->variants) {
  720. Type *a = x->variants[i];
  721. Type *b = y->variants[i];
  722. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  723. if (!ok) return false;
  724. }
  725. return true;
  726. }
  727. return false;
  728. case Type_Struct:
  729. if (source->kind == Type_Struct) {
  730. // return check_is_assignable_to(c, &o, poly);
  731. }
  732. return false;
  733. case Type_Tuple:
  734. GB_PANIC("This should never happen");
  735. return false;
  736. case Type_Proc:
  737. if (source->kind == Type_Proc) {
  738. // return check_is_assignable_to(c, &o, poly);
  739. // TODO(bill): Polymorphic type assignment
  740. #if 1
  741. TypeProc *x = &poly->Proc;
  742. TypeProc *y = &source->Proc;
  743. if (x->calling_convention != y->calling_convention) {
  744. return false;
  745. }
  746. if (x->c_vararg != y->c_vararg) {
  747. return false;
  748. }
  749. if (x->variadic != y->variadic) {
  750. return false;
  751. }
  752. if (x->param_count != y->param_count) {
  753. return false;
  754. }
  755. if (x->result_count != y->result_count) {
  756. return false;
  757. }
  758. for (isize i = 0; i < x->param_count; i++) {
  759. Entity *a = x->params->Tuple.variables[i];
  760. Entity *b = y->params->Tuple.variables[i];
  761. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  762. if (!ok) return false;
  763. }
  764. for (isize i = 0; i < x->result_count; i++) {
  765. Entity *a = x->results->Tuple.variables[i];
  766. Entity *b = y->results->Tuple.variables[i];
  767. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  768. if (!ok) return false;
  769. }
  770. // TODO(bill): Polymorphic type assignment
  771. return true;
  772. #endif
  773. }
  774. return false;
  775. case Type_Map:
  776. if (source->kind == Type_Map) {
  777. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  778. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  779. return key || value;
  780. }
  781. return false;
  782. }
  783. return false;
  784. }
  785. bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  786. if (curr->state != EntityState_InProgress) {
  787. return false;
  788. }
  789. for_array(i, *c->type_path) {
  790. Entity *prev = (*c->type_path)[i];
  791. if (prev == curr) {
  792. if (report) {
  793. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  794. for (isize j = i; j < c->type_path->count; j++) {
  795. Entity *curr = (*c->type_path)[j];
  796. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  797. }
  798. error(curr->token, "\t%.*s", LIT(curr->token.string));
  799. }
  800. return true;
  801. }
  802. }
  803. return false;
  804. }
  805. Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  806. GB_ASSERT(n->kind == Ast_Ident);
  807. o->mode = Addressing_Invalid;
  808. o->expr = n;
  809. String name = n->Ident.token.string;
  810. Entity *e = scope_lookup(c->scope, name);
  811. if (e == nullptr) {
  812. if (is_blank_ident(name)) {
  813. error(n, "'_' cannot be used as a value type");
  814. } else {
  815. error(n, "Undeclared name: %.*s", LIT(name));
  816. }
  817. o->type = t_invalid;
  818. o->mode = Addressing_Invalid;
  819. if (named_type != nullptr) {
  820. set_base_type(named_type, t_invalid);
  821. }
  822. return nullptr;
  823. }
  824. if (e->parent_proc_decl != nullptr &&
  825. e->parent_proc_decl != c->curr_proc_decl) {
  826. if (e->kind == Entity_Variable) {
  827. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  828. return nullptr;
  829. } else if (e->kind == Entity_Label) {
  830. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  831. return nullptr;
  832. }
  833. }
  834. HashKey key = hash_string(e->token.string);
  835. if (e->kind == Entity_ProcGroup) {
  836. auto *pge = &e->ProcGroup;
  837. DeclInfo *d = decl_info_of_entity(e);
  838. check_entity_decl(c, e, d, nullptr);
  839. Array<Entity *> procs = pge->entities;
  840. bool skip = false;
  841. if (type_hint != nullptr) {
  842. // NOTE(bill): These should be done
  843. for_array(i, procs) {
  844. Type *t = base_type(procs[i]->type);
  845. if (t == t_invalid) {
  846. continue;
  847. }
  848. Operand x = {};
  849. x.mode = Addressing_Value;
  850. x.type = t;
  851. if (check_is_assignable_to(c, &x, type_hint)) {
  852. e = procs[i];
  853. add_entity_use(c, n, e);
  854. skip = true;
  855. break;
  856. }
  857. }
  858. }
  859. if (!skip) {
  860. o->mode = Addressing_ProcGroup;
  861. o->type = t_invalid;
  862. o->proc_group = e;
  863. return nullptr;
  864. }
  865. }
  866. add_entity_use(c, n, e);
  867. if (e->state == EntityState_Unresolved) {
  868. check_entity_decl(c, e, nullptr, named_type);
  869. }
  870. if (e->type == nullptr) {
  871. // TODO(bill): Which is correct? return or compiler_error?
  872. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  873. return nullptr;
  874. }
  875. e->flags |= EntityFlag_Used;
  876. Type *type = e->type;
  877. switch (e->kind) {
  878. case Entity_Constant:
  879. if (type == t_invalid) {
  880. o->type = t_invalid;
  881. return e;
  882. }
  883. o->value = e->Constant.value;
  884. if (o->value.kind == ExactValue_Invalid) {
  885. return e;
  886. }
  887. o->mode = Addressing_Constant;
  888. break;
  889. case Entity_Variable:
  890. e->flags |= EntityFlag_Used;
  891. if (type == t_invalid) {
  892. o->type = t_invalid;
  893. return e;
  894. }
  895. o->mode = Addressing_Variable;
  896. if (e->flags & EntityFlag_Value) {
  897. o->mode = Addressing_Value;
  898. }
  899. if (e->Variable.is_immutable) {
  900. o->mode = Addressing_Immutable;
  901. }
  902. break;
  903. case Entity_Procedure:
  904. o->mode = Addressing_Value;
  905. break;
  906. case Entity_Builtin:
  907. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  908. o->mode = Addressing_Builtin;
  909. break;
  910. case Entity_TypeName:
  911. o->mode = Addressing_Type;
  912. if (check_cycle(c, e, true)) {
  913. type = t_invalid;
  914. }
  915. break;
  916. case Entity_ImportName:
  917. if (!allow_import_name) {
  918. error(n, "Use of import '%.*s' not in selector", LIT(name));
  919. }
  920. return e;
  921. case Entity_LibraryName:
  922. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  923. return e;
  924. case Entity_Label:
  925. o->mode = Addressing_NoValue;
  926. break;
  927. case Entity_Nil:
  928. o->mode = Addressing_Value;
  929. break;
  930. default:
  931. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  932. break;
  933. }
  934. o->type = type;
  935. return e;
  936. }
  937. bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  938. if (o->type == nullptr) {
  939. gbString str = expr_to_string(o->expr);
  940. error(o->expr, "Expression has no value '%s'", str);
  941. gb_string_free(str);
  942. return false;
  943. }
  944. // TODO(bill): Handle errors correctly
  945. Type *type = base_type(core_array_type(o->type));
  946. gbString str = nullptr;
  947. switch (op.kind) {
  948. case Token_Add:
  949. case Token_Sub:
  950. if (!is_type_numeric(type)) {
  951. str = expr_to_string(o->expr);
  952. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  953. gb_string_free(str);
  954. }
  955. break;
  956. case Token_Xor:
  957. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  958. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  959. }
  960. break;
  961. case Token_Not:
  962. if (!is_type_boolean(type)) {
  963. str = expr_to_string(o->expr);
  964. error(op, "Operator '%.*s' is only allowed on boolean expression", LIT(op.string));
  965. gb_string_free(str);
  966. }
  967. break;
  968. default:
  969. error(op, "Unknown operator '%.*s'", LIT(op.string));
  970. return false;
  971. }
  972. return true;
  973. }
  974. bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  975. // TODO(bill): Handle errors correctly
  976. Type *type = base_type(core_array_type(o->type));
  977. switch (op.kind) {
  978. case Token_Sub:
  979. case Token_SubEq:
  980. if (!is_type_numeric(type)) {
  981. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  982. return false;
  983. }
  984. break;
  985. case Token_Mul:
  986. case Token_Quo:
  987. case Token_MulEq:
  988. case Token_QuoEq:
  989. case Token_AddEq:
  990. if (!is_type_numeric(type)) {
  991. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  992. return false;
  993. }
  994. break;
  995. case Token_Add:
  996. if (is_type_string(type)) {
  997. if (o->mode == Addressing_Constant) {
  998. return true;
  999. }
  1000. error(op, "String concatenation is only allowed with constant strings");
  1001. return false;
  1002. } else if (!is_type_numeric(type)) {
  1003. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1004. return false;
  1005. }
  1006. break;
  1007. case Token_And:
  1008. case Token_Or:
  1009. case Token_AndEq:
  1010. case Token_OrEq:
  1011. case Token_Xor:
  1012. case Token_XorEq:
  1013. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1014. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1015. return false;
  1016. }
  1017. break;
  1018. case Token_Mod:
  1019. case Token_ModMod:
  1020. case Token_ModEq:
  1021. case Token_ModModEq:
  1022. if (!is_type_integer(type)) {
  1023. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1024. return false;
  1025. }
  1026. break;
  1027. case Token_AndNot:
  1028. case Token_AndNotEq:
  1029. if (!is_type_integer(type) && !is_type_bit_set(type)) {
  1030. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1031. return false;
  1032. }
  1033. break;
  1034. case Token_CmpAnd:
  1035. case Token_CmpOr:
  1036. case Token_CmpAndEq:
  1037. case Token_CmpOrEq:
  1038. if (!is_type_boolean(type)) {
  1039. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1040. return false;
  1041. }
  1042. break;
  1043. default:
  1044. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1045. return false;
  1046. }
  1047. return true;
  1048. }
  1049. bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1050. if (in_value.kind == ExactValue_Invalid) {
  1051. // NOTE(bill): There's already been an error
  1052. return true;
  1053. }
  1054. type = core_type(type);
  1055. if (type == t_invalid) {
  1056. return false;
  1057. } else if (is_type_boolean(type)) {
  1058. return in_value.kind == ExactValue_Bool;
  1059. } else if (is_type_string(type)) {
  1060. return in_value.kind == ExactValue_String;
  1061. } else if (is_type_integer(type) || is_type_rune(type)) {
  1062. ExactValue v = exact_value_to_integer(in_value);
  1063. if (v.kind != ExactValue_Integer) {
  1064. return false;
  1065. }
  1066. if (out_value) *out_value = v;
  1067. if (is_type_untyped(type)) {
  1068. return true;
  1069. }
  1070. BigInt i = v.value_integer;
  1071. i64 bit_size = type_size_of(type);
  1072. BigInt umax = {};
  1073. BigInt imin = {};
  1074. BigInt imax = {};
  1075. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1076. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1077. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1078. switch (type->Basic.kind) {
  1079. case Basic_rune:
  1080. case Basic_i8:
  1081. case Basic_i16:
  1082. case Basic_i32:
  1083. case Basic_i64:
  1084. case Basic_int:
  1085. {
  1086. // return imin <= i && i <= imax;
  1087. int a = big_int_cmp(&imin, &i);
  1088. int b = big_int_cmp(&i, &imax);
  1089. return (a <= 0) && (b <= 0);
  1090. }
  1091. case Basic_u8:
  1092. case Basic_u16:
  1093. case Basic_u32:
  1094. case Basic_u64:
  1095. case Basic_uint:
  1096. case Basic_uintptr:
  1097. {
  1098. // return 0ull <= i && i <= umax;
  1099. int b = big_int_cmp(&i, &umax);
  1100. return !i.neg && (b <= 0);
  1101. }
  1102. case Basic_UntypedInteger:
  1103. return true;
  1104. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1105. }
  1106. } else if (is_type_float(type)) {
  1107. ExactValue v = exact_value_to_float(in_value);
  1108. if (v.kind != ExactValue_Float) {
  1109. return false;
  1110. }
  1111. if (out_value) *out_value = v;
  1112. switch (type->Basic.kind) {
  1113. // case Basic_f16:
  1114. case Basic_f32:
  1115. case Basic_f64:
  1116. return true;
  1117. case Basic_UntypedFloat:
  1118. return true;
  1119. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1120. }
  1121. } else if (is_type_complex(type)) {
  1122. ExactValue v = exact_value_to_complex(in_value);
  1123. if (v.kind != ExactValue_Complex) {
  1124. return false;
  1125. }
  1126. switch (type->Basic.kind) {
  1127. case Basic_complex64:
  1128. case Basic_complex128: {
  1129. ExactValue real = exact_value_real(v);
  1130. ExactValue imag = exact_value_imag(v);
  1131. if (real.kind != ExactValue_Invalid &&
  1132. imag.kind != ExactValue_Invalid) {
  1133. if (out_value) *out_value = exact_binary_operator_value(Token_Add, real, exact_value_make_imag(imag));
  1134. return true;
  1135. }
  1136. break;
  1137. }
  1138. case Basic_UntypedComplex:
  1139. return true;
  1140. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1141. }
  1142. return false;
  1143. } else if (is_type_pointer(type)) {
  1144. if (in_value.kind == ExactValue_Pointer) {
  1145. return true;
  1146. }
  1147. if (in_value.kind == ExactValue_Integer) {
  1148. return false;
  1149. // return true;
  1150. }
  1151. if (out_value) *out_value = in_value;
  1152. } else if (is_type_bit_set(type)) {
  1153. if (in_value.kind == ExactValue_Integer) {
  1154. return true;
  1155. }
  1156. }
  1157. return false;
  1158. }
  1159. void check_is_expressible(CheckerContext *c, Operand *o, Type *type) {
  1160. GB_ASSERT(is_type_constant_type(type));
  1161. GB_ASSERT(o->mode == Addressing_Constant);
  1162. if (!check_representable_as_constant(c, o->value, type, &o->value)) {
  1163. gbString a = expr_to_string(o->expr);
  1164. gbString b = type_to_string(type);
  1165. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1166. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1167. error(o->expr, "'%s' truncated to '%s'", a, b);
  1168. } else {
  1169. gbAllocator ha = heap_allocator();
  1170. String str = big_int_to_string(ha, &o->value.value_integer);
  1171. defer (gb_free(ha, str.text));
  1172. error(o->expr, "'%s = %.*s' overflows '%s'", a, LIT(str), b);
  1173. }
  1174. } else {
  1175. error(o->expr, "Cannot convert '%s' to '%s'", a, b);
  1176. }
  1177. gb_string_free(b);
  1178. gb_string_free(a);
  1179. o->mode = Addressing_Invalid;
  1180. }
  1181. }
  1182. bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1183. if (o->mode == Addressing_OptionalOk) {
  1184. Ast *expr = unselector_expr(o->expr);
  1185. if (expr->kind != Ast_TypeAssertion) {
  1186. return true;
  1187. }
  1188. ast_node(ta, TypeAssertion, expr);
  1189. TypeAndValue tv = ta->expr->tav;
  1190. if (is_type_pointer(tv.type)) {
  1191. return false;
  1192. }
  1193. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1194. return false;
  1195. }
  1196. if (is_type_any(tv.type)) {
  1197. return false;
  1198. }
  1199. return true;
  1200. }
  1201. if (o->mode != Addressing_Variable) {
  1202. return true;
  1203. }
  1204. if (is_type_bit_field_value(o->type)) {
  1205. return true;
  1206. }
  1207. return false;
  1208. }
  1209. void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  1210. switch (op.kind) {
  1211. case Token_And: { // Pointer address
  1212. if (check_is_not_addressable(c, o)) {
  1213. if (ast_node_expect(node, Ast_UnaryExpr)) {
  1214. ast_node(ue, UnaryExpr, node);
  1215. gbString str = expr_to_string(ue->expr);
  1216. error(op, "Cannot take the pointer address of '%s'", str);
  1217. gb_string_free(str);
  1218. }
  1219. o->mode = Addressing_Invalid;
  1220. return;
  1221. }
  1222. o->mode = Addressing_Value;
  1223. o->type = alloc_type_pointer(o->type);
  1224. return;
  1225. }
  1226. }
  1227. if (!check_unary_op(c, o, op)) {
  1228. o->mode = Addressing_Invalid;
  1229. return;
  1230. }
  1231. if (o->mode == Addressing_Constant) {
  1232. Type *type = base_type(o->type);
  1233. if (!is_type_constant_type(o->type)) {
  1234. gbString xt = type_to_string(o->type);
  1235. gbString err_str = expr_to_string(node);
  1236. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  1237. gb_string_free(err_str);
  1238. gb_string_free(xt);
  1239. o->mode = Addressing_Invalid;
  1240. return;
  1241. }
  1242. if (op.kind == Token_Xor && is_type_untyped(type)) {
  1243. gbString err_str = expr_to_string(node);
  1244. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  1245. gb_string_free(err_str);
  1246. o->mode = Addressing_Invalid;
  1247. return;
  1248. }
  1249. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  1250. gbString err_str = expr_to_string(node);
  1251. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  1252. gb_string_free(err_str);
  1253. o->mode = Addressing_Invalid;
  1254. return;
  1255. }
  1256. i32 precision = 0;
  1257. if (is_type_typed(type)) {
  1258. precision = cast(i32)(8 * type_size_of(type));
  1259. }
  1260. bool is_unsigned = is_type_unsigned(type);
  1261. if (is_type_rune(type)) {
  1262. GB_ASSERT(!is_unsigned);
  1263. }
  1264. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  1265. if (is_type_typed(type)) {
  1266. if (node != nullptr) {
  1267. o->expr = node;
  1268. }
  1269. check_is_expressible(c, o, type);
  1270. }
  1271. return;
  1272. }
  1273. o->mode = Addressing_Value;
  1274. }
  1275. void check_comparison(CheckerContext *c, Operand *x, Operand *y, TokenKind op) {
  1276. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  1277. bool comp = are_types_identical(x->type, y->type);
  1278. switch (op) {
  1279. case Token_CmpEq: /* comp = comp; */ break;
  1280. case Token_NotEq: comp = !comp; break;
  1281. }
  1282. x->mode = Addressing_Constant;
  1283. x->type = t_untyped_bool;
  1284. x->value = exact_value_bool(comp);
  1285. return;
  1286. }
  1287. gbString err_str = nullptr;
  1288. defer (if (err_str != nullptr) {
  1289. gb_string_free(err_str);
  1290. });
  1291. if (check_is_assignable_to(c, x, y->type) ||
  1292. check_is_assignable_to(c, y, x->type)) {
  1293. Type *err_type = x->type;
  1294. bool defined = false;
  1295. switch (op) {
  1296. case Token_CmpEq:
  1297. case Token_NotEq:
  1298. defined = is_type_comparable(x->type) ||
  1299. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  1300. (is_operand_nil(*y) && type_has_nil(x->type));
  1301. break;
  1302. case Token_Lt:
  1303. case Token_Gt:
  1304. case Token_LtEq:
  1305. case Token_GtEq:
  1306. defined = is_type_ordered(x->type);
  1307. break;
  1308. }
  1309. if (!defined) {
  1310. if (x->type == err_type && is_operand_nil(*x)) {
  1311. err_type = y->type;
  1312. }
  1313. gbString type_string = type_to_string(err_type);
  1314. defer (gb_string_free(type_string));
  1315. err_str = gb_string_make(c->allocator,
  1316. gb_bprintf("operator '%.*s' not defined for type '%s'", LIT(token_strings[op]), type_string));
  1317. }
  1318. } else {
  1319. gbString xt, yt;
  1320. if (x->mode == Addressing_ProcGroup) {
  1321. xt = gb_string_make(heap_allocator(), "procedure group");
  1322. } else {
  1323. xt = type_to_string(x->type);
  1324. }
  1325. if (y->mode == Addressing_ProcGroup) {
  1326. yt = gb_string_make(heap_allocator(), "procedure group");
  1327. } else {
  1328. yt = type_to_string(y->type);
  1329. }
  1330. err_str = gb_string_make(c->allocator,
  1331. gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  1332. gb_string_free(yt);
  1333. gb_string_free(xt);
  1334. }
  1335. if (err_str != nullptr) {
  1336. error(x->expr, "Cannot compare expression, %s", err_str);
  1337. x->type = t_untyped_bool;
  1338. } else {
  1339. if (x->mode == Addressing_Constant &&
  1340. y->mode == Addressing_Constant) {
  1341. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  1342. } else {
  1343. x->mode = Addressing_Value;
  1344. update_expr_type(c, x->expr, default_type(x->type), true);
  1345. update_expr_type(c, y->expr, default_type(y->type), true);
  1346. i64 size = 0;
  1347. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  1348. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  1349. if (is_type_string(x->type) || is_type_string(y->type)) {
  1350. switch (op) {
  1351. case Token_CmpEq: add_package_dependency(c, "runtime", "__string_eq"); break;
  1352. case Token_NotEq: add_package_dependency(c, "runtime", "__string_ne"); break;
  1353. case Token_Lt: add_package_dependency(c, "runtime", "__string_lt"); break;
  1354. case Token_Gt: add_package_dependency(c, "runtime", "__string_gt"); break;
  1355. case Token_LtEq: add_package_dependency(c, "runtime", "__string_le"); break;
  1356. case Token_GtEq: add_package_dependency(c, "runtime", "__string_gt"); break;
  1357. }
  1358. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  1359. switch (op) {
  1360. case Token_CmpEq:
  1361. switch (8*size) {
  1362. case 64: add_package_dependency(c, "runtime", "__complex64_eq"); break;
  1363. case 128: add_package_dependency(c, "runtime", "__complex128_eq"); break;
  1364. }
  1365. break;
  1366. case Token_NotEq:
  1367. switch (8*size) {
  1368. case 64: add_package_dependency(c, "runtime", "__complex64_ne"); break;
  1369. case 128: add_package_dependency(c, "runtime", "__complex128_ne"); break;
  1370. }
  1371. break;
  1372. }
  1373. }
  1374. }
  1375. x->type = t_untyped_bool;
  1376. }
  1377. }
  1378. void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node) {
  1379. GB_ASSERT(node->kind == Ast_BinaryExpr);
  1380. ast_node(be, BinaryExpr, node);
  1381. ExactValue x_val = {};
  1382. if (x->mode == Addressing_Constant) {
  1383. x_val = exact_value_to_integer(x->value);
  1384. }
  1385. bool x_is_untyped = is_type_untyped(x->type);
  1386. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  1387. gbString err_str = expr_to_string(x->expr);
  1388. error(node, "Shifted operand '%s' must be an integer", err_str);
  1389. gb_string_free(err_str);
  1390. x->mode = Addressing_Invalid;
  1391. return;
  1392. }
  1393. if (is_type_unsigned(y->type)) {
  1394. } else if (is_type_untyped(y->type)) {
  1395. convert_to_typed(c, y, t_untyped_integer);
  1396. if (y->mode == Addressing_Invalid) {
  1397. x->mode = Addressing_Invalid;
  1398. return;
  1399. }
  1400. } else {
  1401. gbString err_str = expr_to_string(y->expr);
  1402. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  1403. gb_string_free(err_str);
  1404. x->mode = Addressing_Invalid;
  1405. return;
  1406. }
  1407. if (x->mode == Addressing_Constant) {
  1408. if (y->mode == Addressing_Constant) {
  1409. ExactValue y_val = exact_value_to_integer(y->value);
  1410. if (y_val.kind != ExactValue_Integer) {
  1411. gbString err_str = expr_to_string(y->expr);
  1412. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  1413. gb_string_free(err_str);
  1414. x->mode = Addressing_Invalid;
  1415. return;
  1416. }
  1417. BigInt max_shift = {};
  1418. big_int_from_u64(&max_shift, 128);
  1419. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  1420. gbString err_str = expr_to_string(y->expr);
  1421. error(node, "Shift amount too large: '%s'", err_str);
  1422. gb_string_free(err_str);
  1423. x->mode = Addressing_Invalid;
  1424. return;
  1425. }
  1426. if (!is_type_integer(x->type)) {
  1427. // NOTE(bill): It could be an untyped float but still representable
  1428. // as an integer
  1429. x->type = t_untyped_integer;
  1430. }
  1431. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  1432. if (is_type_typed(x->type)) {
  1433. check_is_expressible(c, x, base_type(x->type));
  1434. }
  1435. return;
  1436. }
  1437. TokenPos pos = ast_token(x->expr).pos;
  1438. if (x_is_untyped) {
  1439. ExprInfo *info = check_get_expr_info(&c->checker->info, x->expr);
  1440. if (info != nullptr) {
  1441. info->is_lhs = true;
  1442. }
  1443. x->mode = Addressing_Value;
  1444. // x->value = x_val;
  1445. return;
  1446. }
  1447. }
  1448. if (y->mode == Addressing_Constant && y->value.value_integer.neg) {
  1449. gbString err_str = expr_to_string(y->expr);
  1450. error(node, "Shift amount cannot be negative: '%s'", err_str);
  1451. gb_string_free(err_str);
  1452. }
  1453. if (!is_type_integer(x->type)) {
  1454. gbString err_str = expr_to_string(y->expr);
  1455. error(node, "Shift operand '%s' must be an integer", err_str);
  1456. gb_string_free(err_str);
  1457. x->mode = Addressing_Invalid;
  1458. return;
  1459. }
  1460. x->mode = Addressing_Value;
  1461. }
  1462. // Operand check_ptr_addition(CheckerContext *c, TokenKind op, Operand *ptr, Operand *offset, Ast *node) {
  1463. // GB_ASSERT(node->kind == Ast_BinaryExpr);
  1464. // ast_node(be, BinaryExpr, node);
  1465. // GB_ASSERT(is_type_pointer(ptr->type));
  1466. // GB_ASSERT(is_type_integer(offset->type));
  1467. // GB_ASSERT(op == Token_Add || op == Token_Sub);
  1468. // Operand operand = {};
  1469. // operand.mode = Addressing_Value;
  1470. // operand.type = ptr->type;
  1471. // operand.expr = node;
  1472. // if (base_type(ptr->type) == t_rawptr) {
  1473. // gbString str = type_to_string(ptr->type);
  1474. // error(node, "Invalid pointer type for pointer arithmetic: '%s'", str);
  1475. // gb_string_free(str);
  1476. // operand.mode = Addressing_Invalid;
  1477. // return operand;
  1478. // }
  1479. // #if defined(NO_POINTER_ARITHMETIC)
  1480. // operand.mode = Addressing_Invalid;
  1481. // error(operand.expr, "Pointer arithmetic is not supported");
  1482. // return operand;
  1483. // #else
  1484. // Type *base_ptr = base_type(ptr->type); GB_ASSERT(base_ptr->kind == Type_Pointer);
  1485. // Type *elem = base_ptr->Pointer.elem;
  1486. // i64 elem_size = type_size_of(elem);
  1487. // if (elem_size <= 0) {
  1488. // gbString str = type_to_string(elem);
  1489. // error(node, "Size of pointer's element type '%s' is zero and cannot be used for pointer arithmetic", str);
  1490. // gb_string_free(str);
  1491. // operand.mode = Addressing_Invalid;
  1492. // return operand;
  1493. // }
  1494. // if (ptr->mode == Addressing_Constant && offset->mode == Addressing_Constant) {
  1495. // i64 ptr_val = ptr->value.value_pointer;
  1496. // i64 offset_val = exact_value_to_integer(offset->value).value_integer;
  1497. // i64 new_ptr_val = ptr_val;
  1498. // if (op == Token_Add) {
  1499. // new_ptr_val += elem_size*offset_val;
  1500. // } else {
  1501. // new_ptr_val -= elem_size*offset_val;
  1502. // }
  1503. // operand.mode = Addressing_Constant;
  1504. // operand.value = exact_value_pointer(new_ptr_val);
  1505. // }
  1506. // return operand;
  1507. // #endif
  1508. // }
  1509. bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  1510. if (check_is_assignable_to(c, operand, y)) {
  1511. return true;
  1512. }
  1513. Type *x = operand->type;
  1514. Type *src = core_type(x);
  1515. Type *dst = core_type(y);
  1516. if (are_types_identical(src, dst)) {
  1517. return true;
  1518. }
  1519. if (dst->kind == Type_Array && src->kind == Type_Array) {
  1520. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  1521. return dst->Array.count == src->Array.count;
  1522. }
  1523. }
  1524. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  1525. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  1526. }
  1527. // Cast between booleans and integers
  1528. if (is_type_boolean(src) || is_type_integer(src)) {
  1529. if (is_type_boolean(dst) || is_type_integer(dst)) {
  1530. return true;
  1531. }
  1532. }
  1533. // Cast between numbers
  1534. if (is_type_integer(src) || is_type_float(src)) {
  1535. if (is_type_integer(dst) || is_type_float(dst)) {
  1536. return true;
  1537. }
  1538. }
  1539. if (is_type_integer(src) && is_type_rune(dst)) {
  1540. return true;
  1541. }
  1542. if (is_type_rune(src) && is_type_integer(dst)) {
  1543. return true;
  1544. }
  1545. if (is_type_complex(src) && is_type_complex(dst)) {
  1546. return true;
  1547. }
  1548. if (is_type_bit_field_value(src) && is_type_integer(dst)) {
  1549. return true;
  1550. }
  1551. if (is_type_bit_field_value(src) && is_type_boolean(dst)) {
  1552. return src->BitFieldValue.bits == 1;
  1553. }
  1554. // Cast between pointers
  1555. if (is_type_pointer(src) && is_type_pointer(dst)) {
  1556. #if 0
  1557. Type *s = base_type(type_deref(src));
  1558. if (is_type_union(s)) {
  1559. // NOTE(bill): Should the error be here?!
  1560. // NOTE(bill): This error should suppress the next casting error as it's at the same position
  1561. gbString xs = type_to_string(x);
  1562. gbString ys = type_to_string(y);
  1563. error(operand->expr, "Cannot cast from a union pointer '%s' to '%s', try using 'union_cast' or cast to a 'rawptr'", xs, ys);
  1564. gb_string_free(ys);
  1565. gb_string_free(xs);
  1566. return false;
  1567. }
  1568. #endif
  1569. return true;
  1570. }
  1571. // (u)int <-> pointer
  1572. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  1573. return true;
  1574. }
  1575. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  1576. return true;
  1577. }
  1578. // []byte/[]u8 <-> string
  1579. if (is_type_u8_slice(src) && is_type_string(dst)) {
  1580. return true;
  1581. }
  1582. if (is_type_string(src) && is_type_u8_slice(dst)) {
  1583. // if (is_type_typed(src)) {
  1584. return true;
  1585. // }
  1586. }
  1587. // cstring -> string
  1588. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  1589. if (operand->mode != Addressing_Constant) {
  1590. add_package_dependency(c, "runtime", "__cstring_to_string");
  1591. }
  1592. return true;
  1593. }
  1594. // cstring -> ^u8
  1595. if (src == t_cstring && is_type_u8_ptr(dst)) {
  1596. return true;
  1597. }
  1598. // ^u8 -> cstring
  1599. if (is_type_u8_ptr(src) && dst == t_cstring) {
  1600. return true;
  1601. }
  1602. // proc <-> proc
  1603. if (is_type_proc(src) && is_type_proc(dst)) {
  1604. return true;
  1605. }
  1606. // proc -> rawptr
  1607. if (is_type_proc(src) && is_type_rawptr(dst)) {
  1608. return true;
  1609. }
  1610. // rawptr -> proc
  1611. if (is_type_rawptr(src) && is_type_proc(dst)) {
  1612. return true;
  1613. }
  1614. return false;
  1615. }
  1616. bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  1617. bool is_const_expr = x->mode == Addressing_Constant;
  1618. bool can_convert = false;
  1619. Type *bt = base_type(type);
  1620. if (is_const_expr && is_type_constant_type(bt)) {
  1621. if (core_type(bt)->kind == Type_Basic) {
  1622. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  1623. return true;
  1624. } else if (is_type_pointer(type) && check_is_castable_to(c, x, type)) {
  1625. return true;
  1626. }
  1627. }
  1628. } else if (check_is_castable_to(c, x, type)) {
  1629. if (x->mode != Addressing_Constant) {
  1630. x->mode = Addressing_Value;
  1631. } else if (is_type_slice(type) && is_type_string(x->type)) {
  1632. x->mode = Addressing_Value;
  1633. }
  1634. return true;
  1635. }
  1636. return false;
  1637. }
  1638. void check_cast(CheckerContext *c, Operand *x, Type *type) {
  1639. if (!is_operand_value(*x)) {
  1640. error(x->expr, "Only values can be casted");
  1641. x->mode = Addressing_Invalid;
  1642. return;
  1643. }
  1644. bool is_const_expr = x->mode == Addressing_Constant;
  1645. bool can_convert = check_cast_internal(c, x, type);
  1646. if (!can_convert) {
  1647. gbString expr_str = expr_to_string(x->expr);
  1648. gbString to_type = type_to_string(type);
  1649. gbString from_type = type_to_string(x->type);
  1650. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  1651. gb_string_free(from_type);
  1652. gb_string_free(to_type);
  1653. gb_string_free(expr_str);
  1654. x->mode = Addressing_Invalid;
  1655. return;
  1656. }
  1657. if (is_type_untyped(x->type)) {
  1658. Type *final_type = type;
  1659. if (is_const_expr && !is_type_constant_type(type)) {
  1660. final_type = default_type(x->type);
  1661. }
  1662. update_expr_type(c, x->expr, final_type, true);
  1663. }
  1664. x->type = type;
  1665. }
  1666. bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  1667. if (!is_operand_value(*o)) {
  1668. error(o->expr, "'transmute' can only be applied to values");
  1669. o->mode = Addressing_Invalid;
  1670. return false;
  1671. }
  1672. if (o->mode == Addressing_Constant) {
  1673. gbString expr_str = expr_to_string(o->expr);
  1674. error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  1675. gb_string_free(expr_str);
  1676. o->mode = Addressing_Invalid;
  1677. o->expr = node;
  1678. return false;
  1679. }
  1680. if (is_type_untyped(o->type)) {
  1681. gbString expr_str = expr_to_string(o->expr);
  1682. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  1683. gb_string_free(expr_str);
  1684. o->mode = Addressing_Invalid;
  1685. o->expr = node;
  1686. return false;
  1687. }
  1688. i64 srcz = type_size_of(o->type);
  1689. i64 dstz = type_size_of(t);
  1690. if (srcz != dstz) {
  1691. gbString expr_str = expr_to_string(o->expr);
  1692. gbString type_str = type_to_string(t);
  1693. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  1694. gb_string_free(type_str);
  1695. gb_string_free(expr_str);
  1696. o->mode = Addressing_Invalid;
  1697. o->expr = node;
  1698. return false;
  1699. }
  1700. o->mode = Addressing_Value;
  1701. o->type = t;
  1702. return true;
  1703. }
  1704. bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  1705. if (is_type_array(x->type) && !is_type_array(y->type)) {
  1706. if (check_is_assignable_to(c, y, x->type)) {
  1707. if (check_binary_op(c, x, op)) {
  1708. return true;
  1709. }
  1710. }
  1711. }
  1712. return false;
  1713. }
  1714. void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, bool use_lhs_as_type_hint=false) {
  1715. GB_ASSERT(node->kind == Ast_BinaryExpr);
  1716. Operand y_ = {}, *y = &y_;
  1717. ast_node(be, BinaryExpr, node);
  1718. Token op = be->op;
  1719. switch (op.kind) {
  1720. case Token_CmpEq:
  1721. case Token_NotEq: {
  1722. // NOTE(bill): Allow comparisons between types
  1723. check_expr_or_type(c, x, be->left);
  1724. check_expr_or_type(c, y, be->right);
  1725. bool xt = x->mode == Addressing_Type;
  1726. bool yt = y->mode == Addressing_Type;
  1727. // If only one is a type, this is an error
  1728. if (xt ^ yt) {
  1729. GB_ASSERT(xt != yt);
  1730. if (xt) error_operand_not_expression(x);
  1731. if (yt) error_operand_not_expression(y);
  1732. }
  1733. break;
  1734. }
  1735. case Token_in:
  1736. check_expr(c, x, be->left);
  1737. check_expr(c, y, be->right);
  1738. if (x->mode == Addressing_Invalid) {
  1739. return;
  1740. }
  1741. if (y->mode == Addressing_Invalid) {
  1742. x->mode = Addressing_Invalid;
  1743. x->expr = y->expr;
  1744. return;
  1745. }
  1746. if (is_type_map(y->type)) {
  1747. Type *yt = base_type(y->type);
  1748. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  1749. add_package_dependency(c, "runtime", "__dynamic_map_get");
  1750. } else if (is_type_bit_set(y->type)) {
  1751. Type *yt = base_type(y->type);
  1752. check_assignment(c, x, yt->BitSet.base_type, str_lit("bit_set 'in'"));
  1753. } else {
  1754. gbString t = type_to_string(y->type);
  1755. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  1756. gb_string_free(t);
  1757. x->expr = node;
  1758. x->mode = Addressing_Invalid;
  1759. return;
  1760. }
  1761. if (x->mode != Addressing_Invalid) {
  1762. x->mode = Addressing_Value;
  1763. x->type = t_untyped_bool;
  1764. }
  1765. x->expr = node;
  1766. return;
  1767. default:
  1768. check_expr(c, x, be->left);
  1769. if (use_lhs_as_type_hint) {
  1770. check_expr_with_type_hint(c, y, be->right, x->type);
  1771. } else {
  1772. check_expr(c, y, be->right);
  1773. }
  1774. break;
  1775. }
  1776. if (x->mode == Addressing_Invalid) {
  1777. return;
  1778. }
  1779. if (y->mode == Addressing_Invalid) {
  1780. x->mode = Addressing_Invalid;
  1781. x->expr = y->expr;
  1782. return;
  1783. }
  1784. if (x->mode == Addressing_Builtin) {
  1785. x->mode = Addressing_Invalid;
  1786. error(x->expr, "built-in expression in binary expression");
  1787. return;
  1788. }
  1789. if (y->mode == Addressing_Builtin) {
  1790. x->mode = Addressing_Invalid;
  1791. error(y->expr, "built-in expression in binary expression");
  1792. return;
  1793. }
  1794. if (token_is_shift(op.kind)) {
  1795. check_shift(c, x, y, node);
  1796. return;
  1797. }
  1798. // if (op.kind == Token_Add || op.kind == Token_Sub) {
  1799. // if (is_type_pointer(x->type) && is_type_integer(y->type)) {
  1800. // *x = check_ptr_addition(c, op.kind, x, y, node);
  1801. // return;
  1802. // } else if (is_type_integer(x->type) && is_type_pointer(y->type)) {
  1803. // if (op.kind == Token_Sub) {
  1804. // gbString lhs = expr_to_string(x->expr);
  1805. // gbString rhs = expr_to_string(y->expr);
  1806. // error(node, "Invalid pointer arithmetic, did you mean '%s %.*s %s'?", rhs, LIT(op.string), lhs);
  1807. // gb_string_free(rhs);
  1808. // gb_string_free(lhs);
  1809. // x->mode = Addressing_Invalid;
  1810. // return;
  1811. // }
  1812. // *x = check_ptr_addition(c, op.kind, y, x, node);
  1813. // return;
  1814. // }
  1815. // }
  1816. convert_to_typed(c, x, y->type);
  1817. if (x->mode == Addressing_Invalid) {
  1818. return;
  1819. }
  1820. convert_to_typed(c, y, x->type);
  1821. if (y->mode == Addressing_Invalid) {
  1822. x->mode = Addressing_Invalid;
  1823. return;
  1824. }
  1825. if (token_is_comparison(op.kind)) {
  1826. check_comparison(c, x, y, op.kind);
  1827. return;
  1828. }
  1829. if (check_binary_array_expr(c, op, x, y)) {
  1830. x->mode = Addressing_Value;
  1831. x->type = x->type;
  1832. return;
  1833. }
  1834. if (check_binary_array_expr(c, op, y, x)) {
  1835. x->mode = Addressing_Value;
  1836. x->type = y->type;
  1837. return;
  1838. }
  1839. if (!are_types_identical(x->type, y->type)) {
  1840. if (x->type != t_invalid &&
  1841. y->type != t_invalid) {
  1842. gbString xt = type_to_string(x->type);
  1843. gbString yt = type_to_string(y->type);
  1844. gbString expr_str = expr_to_string(x->expr);
  1845. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  1846. gb_string_free(expr_str);
  1847. gb_string_free(yt);
  1848. gb_string_free(xt);
  1849. }
  1850. x->mode = Addressing_Invalid;
  1851. return;
  1852. }
  1853. if (!check_binary_op(c, x, op)) {
  1854. x->mode = Addressing_Invalid;
  1855. return;
  1856. }
  1857. switch (op.kind) {
  1858. case Token_Quo:
  1859. case Token_Mod:
  1860. case Token_ModMod:
  1861. case Token_QuoEq:
  1862. case Token_ModEq:
  1863. case Token_ModModEq:
  1864. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  1865. y->mode == Addressing_Constant) {
  1866. bool fail = false;
  1867. switch (y->value.kind) {
  1868. case ExactValue_Integer:
  1869. if (big_int_is_zero(&y->value.value_integer)) {
  1870. fail = true;
  1871. }
  1872. break;
  1873. case ExactValue_Float:
  1874. if (y->value.value_float == 0.0) {
  1875. fail = true;
  1876. }
  1877. break;
  1878. }
  1879. if (fail) {
  1880. error(y->expr, "Division by zero not allowed");
  1881. x->mode = Addressing_Invalid;
  1882. return;
  1883. }
  1884. }
  1885. }
  1886. if (x->mode == Addressing_Constant &&
  1887. y->mode == Addressing_Constant) {
  1888. ExactValue a = x->value;
  1889. ExactValue b = y->value;
  1890. // Type *type = base_type(x->type);
  1891. Type *type = x->type;
  1892. if (is_type_pointer(type)) {
  1893. GB_ASSERT(op.kind == Token_Sub);
  1894. i64 bytes = a.value_pointer - b.value_pointer;
  1895. i64 diff = bytes/type_size_of(type);
  1896. x->value = exact_value_pointer(diff);
  1897. return;
  1898. }
  1899. if (!is_type_constant_type(type)) {
  1900. gbString xt = type_to_string(x->type);
  1901. gbString err_str = expr_to_string(node);
  1902. error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
  1903. gb_string_free(err_str);
  1904. gb_string_free(xt);
  1905. x->mode = Addressing_Invalid;
  1906. return;
  1907. }
  1908. if (op.kind == Token_Quo && is_type_integer(type)) {
  1909. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  1910. }
  1911. x->value = exact_binary_operator_value(op.kind, a, b);
  1912. if (is_type_typed(type)) {
  1913. if (node != nullptr) {
  1914. x->expr = node;
  1915. }
  1916. check_is_expressible(c, x, type);
  1917. }
  1918. return;
  1919. } else if (is_type_string(x->type)) {
  1920. error(node, "String concatenation is only allowed with constant strings");
  1921. x->mode = Addressing_Invalid;
  1922. return;
  1923. }
  1924. x->mode = Addressing_Value;
  1925. }
  1926. void update_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  1927. ExprInfo *found = check_get_expr_info(&c->checker->info, e);
  1928. if (found == nullptr) {
  1929. return;
  1930. }
  1931. ExprInfo old = *found;
  1932. switch (e->kind) {
  1933. case_ast_node(ue, UnaryExpr, e);
  1934. if (old.value.kind != ExactValue_Invalid) {
  1935. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  1936. // They don't need to be updated as they will be updated later and
  1937. // checked at the end of general checking stage.
  1938. break;
  1939. }
  1940. update_expr_type(c, ue->expr, type, final);
  1941. case_end;
  1942. case_ast_node(be, BinaryExpr, e);
  1943. if (old.value.kind != ExactValue_Invalid) {
  1944. // See above note in UnaryExpr case
  1945. break;
  1946. }
  1947. if (token_is_comparison(be->op.kind)) {
  1948. // NOTE(bill): Do nothing as the types are fine
  1949. } else if (token_is_shift(be->op.kind)) {
  1950. update_expr_type(c, be->left, type, final);
  1951. } else {
  1952. update_expr_type(c, be->left, type, final);
  1953. update_expr_type(c, be->right, type, final);
  1954. }
  1955. case_end;
  1956. case_ast_node(pe, ParenExpr, e);
  1957. update_expr_type(c, pe->expr, type, final);
  1958. case_end;
  1959. }
  1960. if (!final && is_type_untyped(type)) {
  1961. old.type = base_type(type);
  1962. check_set_expr_info(&c->checker->info, e, old);
  1963. return;
  1964. }
  1965. // We need to remove it and then give it a new one
  1966. check_remove_expr_info(&c->checker->info, e);
  1967. if (old.is_lhs && !is_type_integer(type)) {
  1968. gbString expr_str = expr_to_string(e);
  1969. gbString type_str = type_to_string(type);
  1970. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  1971. gb_string_free(type_str);
  1972. gb_string_free(expr_str);
  1973. return;
  1974. }
  1975. add_type_and_value(&c->checker->info, e, old.mode, type, old.value);
  1976. }
  1977. void update_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  1978. ExprInfo *found = check_get_expr_info(&c->checker->info, e);
  1979. if (found) {
  1980. found->value = value;
  1981. }
  1982. }
  1983. void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  1984. gbString expr_str = expr_to_string(operand->expr);
  1985. gbString type_str = type_to_string(target_type);
  1986. char *extra_text = "";
  1987. if (operand->mode == Addressing_Constant) {
  1988. if (big_int_is_zero(&operand->value.value_integer)) {
  1989. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  1990. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  1991. extra_text = " - Did you want 'nil'?";
  1992. }
  1993. }
  1994. }
  1995. error(operand->expr, "Cannot convert '%s' to '%s'%s", expr_str, type_str, extra_text);
  1996. gb_string_free(type_str);
  1997. gb_string_free(expr_str);
  1998. operand->mode = Addressing_Invalid;
  1999. }
  2000. ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  2001. Type *t = core_type(type);
  2002. if (is_type_boolean(t)) {
  2003. // v = exact_value_to_boolean(v);
  2004. } else if (is_type_float(t)) {
  2005. v = exact_value_to_float(v);
  2006. } else if (is_type_integer(t)) {
  2007. v = exact_value_to_integer(v);
  2008. } else if (is_type_pointer(t)) {
  2009. v = exact_value_to_integer(v);
  2010. } else if (is_type_complex(t)) {
  2011. v = exact_value_to_complex(v);
  2012. }
  2013. return v;
  2014. }
  2015. void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  2016. GB_ASSERT_NOT_NULL(target_type);
  2017. if (operand->mode == Addressing_Invalid ||
  2018. operand->mode == Addressing_Type ||
  2019. is_type_typed(operand->type) ||
  2020. target_type == t_invalid) {
  2021. return;
  2022. }
  2023. if (is_type_untyped(target_type)) {
  2024. GB_ASSERT(operand->type->kind == Type_Basic);
  2025. GB_ASSERT(target_type->kind == Type_Basic);
  2026. BasicKind x_kind = operand->type->Basic.kind;
  2027. BasicKind y_kind = target_type->Basic.kind;
  2028. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  2029. if (x_kind < y_kind) {
  2030. operand->type = target_type;
  2031. update_expr_type(c, operand->expr, target_type, false);
  2032. }
  2033. } else if (x_kind != y_kind) {
  2034. operand->mode = Addressing_Invalid;
  2035. convert_untyped_error(c, operand, target_type);
  2036. return;
  2037. }
  2038. return;
  2039. }
  2040. Type *t = base_type(target_type);
  2041. if (c->in_enum_type) {
  2042. t = core_type(target_type);
  2043. }
  2044. switch (t->kind) {
  2045. case Type_Basic:
  2046. if (operand->mode == Addressing_Constant) {
  2047. check_is_expressible(c, operand, t);
  2048. if (operand->mode == Addressing_Invalid) {
  2049. return;
  2050. }
  2051. update_expr_value(c, operand->expr, operand->value);
  2052. } else {
  2053. switch (operand->type->Basic.kind) {
  2054. case Basic_UntypedBool:
  2055. if (!is_type_boolean(target_type)) {
  2056. operand->mode = Addressing_Invalid;
  2057. convert_untyped_error(c, operand, target_type);
  2058. return;
  2059. }
  2060. break;
  2061. case Basic_UntypedInteger:
  2062. case Basic_UntypedFloat:
  2063. case Basic_UntypedComplex:
  2064. case Basic_UntypedRune:
  2065. if (!is_type_numeric(target_type)) {
  2066. operand->mode = Addressing_Invalid;
  2067. convert_untyped_error(c, operand, target_type);
  2068. return;
  2069. }
  2070. break;
  2071. case Basic_UntypedNil:
  2072. if (is_type_any(target_type)) {
  2073. target_type = t_untyped_nil;
  2074. } else if (is_type_cstring(target_type)) {
  2075. target_type = t_untyped_nil;
  2076. } else if (!type_has_nil(target_type)) {
  2077. operand->mode = Addressing_Invalid;
  2078. convert_untyped_error(c, operand, target_type);
  2079. return;
  2080. }
  2081. break;
  2082. }
  2083. }
  2084. break;
  2085. case Type_Array: {
  2086. Type *elem = base_array_type(t);
  2087. if (check_is_assignable_to(c, operand, elem)) {
  2088. operand->mode = Addressing_Value;
  2089. } else {
  2090. operand->mode = Addressing_Invalid;
  2091. convert_untyped_error(c, operand, target_type);
  2092. return;
  2093. }
  2094. break;
  2095. }
  2096. case Type_Union:
  2097. if (!is_operand_nil(*operand) && !is_operand_undef(*operand)) {
  2098. isize count = t->Union.variants.count;
  2099. ValidIndexAndScore *valids = gb_alloc_array(c->allocator, ValidIndexAndScore, count);
  2100. defer (gb_free(c->allocator, valids));
  2101. isize valid_count = 0;
  2102. isize first_success_index = -1;
  2103. for_array(i, t->Union.variants) {
  2104. Type *vt = t->Union.variants[i];
  2105. i64 score = 0;
  2106. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  2107. valids[valid_count].index = i;
  2108. valids[valid_count].score = score;
  2109. valid_count += 1;
  2110. if (first_success_index < 0) {
  2111. first_success_index = i;
  2112. }
  2113. }
  2114. }
  2115. if (valid_count > 1) {
  2116. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  2117. i64 best_score = valids[0].score;
  2118. Type *best_type = t->Union.variants[valids[0].index];
  2119. for (isize i = 1; i < valid_count; i++) {
  2120. auto v = valids[i];
  2121. Type *vt = t->Union.variants[v.index];
  2122. if (best_score > v.score) {
  2123. valid_count = i;
  2124. break;
  2125. }
  2126. best_score = v.score;
  2127. }
  2128. first_success_index = valids[0].index;
  2129. }
  2130. gbString type_str = type_to_string(target_type);
  2131. defer (gb_string_free(type_str));
  2132. if (valid_count == 1) {
  2133. operand->mode = Addressing_Value;
  2134. operand->type = t->Union.variants[first_success_index];
  2135. target_type = t->Union.variants[first_success_index];
  2136. break;
  2137. } else if (valid_count > 1) {
  2138. GB_ASSERT(first_success_index >= 0);
  2139. operand->mode = Addressing_Invalid;
  2140. convert_untyped_error(c, operand, target_type);
  2141. gb_printf_err("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  2142. i32 j = 0;
  2143. for (i32 i = 0; i < valid_count; i++) {
  2144. ValidIndexAndScore valid = valids[i];
  2145. if (j > 0 && valid_count > 2) gb_printf_err(", ");
  2146. if (j == valid_count-1) {
  2147. if (valid_count == 2) gb_printf_err(" ");
  2148. gb_printf_err("or ");
  2149. }
  2150. gbString str = type_to_string(t->Union.variants[valid.index]);
  2151. gb_printf_err("'%s'", str);
  2152. gb_string_free(str);
  2153. j++;
  2154. }
  2155. gb_printf_err("\n\n");
  2156. return;
  2157. } else if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  2158. target_type = t_untyped_undef;
  2159. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  2160. operand->mode = Addressing_Invalid;
  2161. convert_untyped_error(c, operand, target_type);
  2162. if (count > 0) {
  2163. gb_printf_err("'%s' is a union which only excepts the following types:\n", type_str);
  2164. gb_printf_err("\t");
  2165. for (i32 i = 0; i < count; i++) {
  2166. Type *v = t->Union.variants[i];
  2167. if (i > 0 && count > 2) gb_printf_err(", ");
  2168. if (i == count-1) {
  2169. if (count == 2) gb_printf_err(" ");
  2170. gb_printf_err("or ");
  2171. }
  2172. gbString str = type_to_string(v);
  2173. gb_printf_err("'%s'", str);
  2174. gb_string_free(str);
  2175. }
  2176. gb_printf_err("\n\n");
  2177. }
  2178. return;
  2179. }
  2180. }
  2181. /* fallthrough */
  2182. default:
  2183. if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  2184. target_type = t_untyped_undef;
  2185. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  2186. target_type = t_untyped_nil;
  2187. } else {
  2188. operand->mode = Addressing_Invalid;
  2189. convert_untyped_error(c, operand, target_type);
  2190. return;
  2191. }
  2192. break;
  2193. }
  2194. operand->type = target_type;
  2195. update_expr_type(c, operand->expr, target_type, true);
  2196. }
  2197. bool check_index_value(CheckerContext *c, bool open_range, Ast *index_value, i64 max_count, i64 *value) {
  2198. Operand operand = {Addressing_Invalid};
  2199. check_expr(c, &operand, index_value);
  2200. if (operand.mode == Addressing_Invalid) {
  2201. if (value) *value = 0;
  2202. return false;
  2203. }
  2204. convert_to_typed(c, &operand, t_int);
  2205. if (operand.mode == Addressing_Invalid) {
  2206. if (value) *value = 0;
  2207. return false;
  2208. }
  2209. if (!is_type_integer(operand.type)) {
  2210. gbString expr_str = expr_to_string(operand.expr);
  2211. error(operand.expr, "Index '%s' must be an integer", expr_str);
  2212. gb_string_free(expr_str);
  2213. if (value) *value = 0;
  2214. return false;
  2215. }
  2216. if (operand.mode == Addressing_Constant &&
  2217. (c->stmt_state_flags & StmtStateFlag_no_bounds_check) == 0) {
  2218. BigInt i = exact_value_to_integer(operand.value).value_integer;
  2219. if (i.neg) {
  2220. gbString expr_str = expr_to_string(operand.expr);
  2221. error(operand.expr, "Index '%s' cannot be a negative value", expr_str);
  2222. gb_string_free(expr_str);
  2223. if (value) *value = 0;
  2224. return false;
  2225. }
  2226. if (max_count >= 0) { // NOTE(bill): Do array bound checking
  2227. i64 v = -1;
  2228. if (i.len <= 1) {
  2229. v = big_int_to_i64(&i);
  2230. }
  2231. if (value) *value = v;
  2232. bool out_of_bounds = false;
  2233. if (open_range) {
  2234. out_of_bounds = v > max_count;
  2235. } else {
  2236. out_of_bounds = v >= max_count;
  2237. }
  2238. if (v < 0) {
  2239. out_of_bounds = true;
  2240. }
  2241. if (out_of_bounds) {
  2242. gbString expr_str = expr_to_string(operand.expr);
  2243. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld", expr_str, max_count);
  2244. gb_string_free(expr_str);
  2245. return false;
  2246. }
  2247. return true;
  2248. }
  2249. }
  2250. // NOTE(bill): It's alright :D
  2251. if (value) *value = -1;
  2252. return true;
  2253. }
  2254. Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  2255. ast_node(se, SelectorExpr, node);
  2256. bool check_op_expr = true;
  2257. Entity *expr_entity = nullptr;
  2258. Entity *entity = nullptr;
  2259. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  2260. operand->expr = node;
  2261. Ast *op_expr = se->expr;
  2262. Ast *selector = unparen_expr(se->selector);
  2263. if (selector == nullptr) {
  2264. operand->mode = Addressing_Invalid;
  2265. operand->expr = node;
  2266. return nullptr;
  2267. }
  2268. if (selector->kind != Ast_Ident) {
  2269. // if (selector->kind != Ast_Ident) {
  2270. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  2271. operand->mode = Addressing_Invalid;
  2272. operand->expr = node;
  2273. return nullptr;
  2274. }
  2275. if (op_expr->kind == Ast_Ident) {
  2276. String op_name = op_expr->Ident.token.string;
  2277. Entity *e = scope_lookup(c->scope, op_name);
  2278. add_entity_use(c, op_expr, e);
  2279. expr_entity = e;
  2280. Entity *original_e = e;
  2281. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  2282. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  2283. // It pretty much needs to be in this order and this way
  2284. // If you can clean this up, please do but be really careful
  2285. String import_name = op_name;
  2286. Scope *import_scope = e->ImportName.scope;
  2287. String entity_name = selector->Ident.token.string;
  2288. check_op_expr = false;
  2289. entity = scope_lookup_current(import_scope, entity_name);
  2290. bool is_declared = entity != nullptr;
  2291. if (is_declared) {
  2292. if (entity->kind == Entity_Builtin) {
  2293. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  2294. // This means that we should just ignore the found result through it
  2295. is_declared = false;
  2296. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  2297. is_declared = false;
  2298. }
  2299. }
  2300. if (!is_declared) {
  2301. error(op_expr, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  2302. operand->mode = Addressing_Invalid;
  2303. operand->expr = node;
  2304. return nullptr;
  2305. }
  2306. check_entity_decl(c, entity, nullptr, nullptr);
  2307. GB_ASSERT(entity->type != nullptr);
  2308. if (!is_entity_exported(entity)) {
  2309. gbString sel_str = expr_to_string(selector);
  2310. error(op_expr, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  2311. gb_string_free(sel_str);
  2312. operand->mode = Addressing_Invalid;
  2313. operand->expr = node;
  2314. return nullptr;
  2315. }
  2316. if (entity->kind == Entity_ProcGroup) {
  2317. Array<Entity *> procs = entity->ProcGroup.entities;
  2318. bool skip = false;
  2319. for_array(i, procs) {
  2320. Entity *p = procs[i];
  2321. Type *t = base_type(p->type);
  2322. if (t == t_invalid) {
  2323. continue;
  2324. }
  2325. Operand x = {};
  2326. x.mode = Addressing_Value;
  2327. x.type = t;
  2328. if (type_hint != nullptr) {
  2329. if (check_is_assignable_to(c, &x, type_hint)) {
  2330. entity = p;
  2331. skip = true;
  2332. break;
  2333. }
  2334. }
  2335. }
  2336. if (!skip) {
  2337. GB_ASSERT(entity != nullptr);
  2338. operand->mode = Addressing_ProcGroup;
  2339. operand->type = t_invalid;
  2340. operand->expr = node;
  2341. operand->proc_group = entity;
  2342. return entity;
  2343. }
  2344. }
  2345. }
  2346. }
  2347. if (check_op_expr) {
  2348. check_expr_base(c, operand, op_expr, nullptr);
  2349. if (operand->mode == Addressing_Invalid) {
  2350. operand->mode = Addressing_Invalid;
  2351. operand->expr = node;
  2352. return nullptr;
  2353. }
  2354. }
  2355. if (entity == nullptr && selector->kind == Ast_Ident) {
  2356. String field_name = selector->Ident.token.string;
  2357. if (is_type_dynamic_array(type_deref(operand->type))) {
  2358. init_mem_allocator(c->checker);
  2359. }
  2360. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  2361. entity = sel.entity;
  2362. // NOTE(bill): Add type info needed for fields like 'names'
  2363. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  2364. add_type_info_type(c, operand->type);
  2365. }
  2366. if (is_type_enum(operand->type)) {
  2367. add_type_info_type(c, operand->type);
  2368. }
  2369. }
  2370. if (entity == nullptr) {
  2371. gbString op_str = expr_to_string(op_expr);
  2372. gbString type_str = type_to_string(operand->type);
  2373. gbString sel_str = expr_to_string(selector);
  2374. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  2375. gb_string_free(sel_str);
  2376. gb_string_free(type_str);
  2377. gb_string_free(op_str);
  2378. operand->mode = Addressing_Invalid;
  2379. operand->expr = node;
  2380. return nullptr;
  2381. }
  2382. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  2383. gbString op_str = expr_to_string(op_expr);
  2384. gbString type_str = type_to_string(operand->type);
  2385. gbString sel_str = expr_to_string(selector);
  2386. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  2387. gb_string_free(sel_str);
  2388. gb_string_free(type_str);
  2389. gb_string_free(op_str);
  2390. operand->mode = Addressing_Invalid;
  2391. operand->expr = node;
  2392. return nullptr;
  2393. }
  2394. add_entity_use(c, selector, entity);
  2395. switch (entity->kind) {
  2396. case Entity_Constant:
  2397. operand->mode = Addressing_Constant;
  2398. operand->value = entity->Constant.value;
  2399. break;
  2400. case Entity_Variable:
  2401. // TODO(bill): Is this the rule I need?
  2402. if (operand->mode == Addressing_Immutable) {
  2403. // Okay
  2404. } else if (operand->mode == Addressing_Context) {
  2405. operand->mode = Addressing_Value; // TODO(bill): Should this be Value or Immutable?
  2406. } else if (operand->mode == Addressing_MapIndex) {
  2407. operand->mode = Addressing_Value;
  2408. } else if (sel.indirect || operand->mode != Addressing_Value) {
  2409. operand->mode = Addressing_Variable;
  2410. } else {
  2411. operand->mode = Addressing_Value;
  2412. }
  2413. break;
  2414. case Entity_TypeName:
  2415. operand->mode = Addressing_Type;
  2416. break;
  2417. case Entity_Procedure:
  2418. operand->mode = Addressing_Value;
  2419. break;
  2420. case Entity_Builtin:
  2421. operand->mode = Addressing_Builtin;
  2422. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  2423. break;
  2424. case Entity_ProcGroup:
  2425. operand->mode = Addressing_ProcGroup;
  2426. operand->proc_group = entity;
  2427. break;
  2428. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  2429. case Entity_Nil:
  2430. operand->mode = Addressing_Value;
  2431. break;
  2432. }
  2433. operand->type = entity->type;
  2434. operand->expr = node;
  2435. return entity;
  2436. }
  2437. bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id) {
  2438. ast_node(ce, CallExpr, call);
  2439. BuiltinProc *bp = &builtin_procs[id];
  2440. {
  2441. char *err = nullptr;
  2442. if (ce->args.count < bp->arg_count) {
  2443. err = "Too few";
  2444. } else if (ce->args.count > bp->arg_count && !bp->variadic) {
  2445. err = "Too many";
  2446. }
  2447. if (err != nullptr) {
  2448. gbString expr = expr_to_string(ce->proc);
  2449. error(ce->close, "%s arguments for '%s', expected %td, got %td",
  2450. err, expr,
  2451. bp->arg_count, ce->args.count);
  2452. gb_string_free(expr);
  2453. return false;
  2454. }
  2455. }
  2456. switch (id) {
  2457. case BuiltinProc_size_of:
  2458. case BuiltinProc_align_of:
  2459. case BuiltinProc_offset_of:
  2460. case BuiltinProc_type_info_of:
  2461. case BuiltinProc_typeid_of:
  2462. case BuiltinProc_len:
  2463. // NOTE(bill): The first arg may be a Type, this will be checked case by case
  2464. break;
  2465. default:
  2466. if (ce->args.count > 0) {
  2467. check_multi_expr(c, operand, ce->args[0]);
  2468. }
  2469. break;
  2470. }
  2471. if (ce->args.count > 0) {
  2472. if (ce->args[0]->kind == Ast_FieldValue) {
  2473. error(call, "'field = value' calling is not allowed on built-in procedures");
  2474. return false;
  2475. }
  2476. }
  2477. switch (id) {
  2478. default:
  2479. GB_PANIC("Implement built-in procedure: %.*s", LIT(builtin_procs[id].name));
  2480. break;
  2481. case BuiltinProc_DIRECTIVE: {
  2482. ast_node(bd, BasicDirective, ce->proc);
  2483. String name = bd->name;
  2484. if (name == "location") {
  2485. if (ce->args.count > 1) {
  2486. error(ce->args[0], "'#location' expects either 0 or 1 arguments, got %td", ce->args.count);
  2487. }
  2488. if (ce->args.count > 0) {
  2489. Ast *arg = ce->args[0];
  2490. Entity *e = nullptr;
  2491. Operand o = {};
  2492. if (arg->kind == Ast_Ident) {
  2493. e = check_ident(c, &o, arg, nullptr, nullptr, true);
  2494. } else if (arg->kind == Ast_SelectorExpr) {
  2495. e = check_selector(c, &o, arg, nullptr);
  2496. }
  2497. if (e == nullptr) {
  2498. error(ce->args[0], "'#location' expected a valid entity name");
  2499. }
  2500. }
  2501. operand->type = t_source_code_location;
  2502. operand->mode = Addressing_Value;
  2503. } else if (name == "assert") {
  2504. if (ce->args.count != 1) {
  2505. error(call, "'#assert' expects 1 argument, got %td", ce->args.count);
  2506. return false;
  2507. }
  2508. if (!is_type_boolean(operand->type) && operand->mode != Addressing_Constant) {
  2509. gbString str = expr_to_string(ce->args[0]);
  2510. error(call, "'%s' is not a constant boolean", str);
  2511. gb_string_free(str);
  2512. return false;
  2513. }
  2514. if (!operand->value.value_bool) {
  2515. gbString arg = expr_to_string(ce->args[0]);
  2516. error(call, "Compile time assertion: %s", arg);
  2517. gb_string_free(arg);
  2518. }
  2519. operand->type = t_untyped_bool;
  2520. operand->mode = Addressing_Constant;
  2521. } else {
  2522. GB_PANIC("Unhandled #%.*s", LIT(name));
  2523. }
  2524. break;
  2525. }
  2526. case BuiltinProc_len:
  2527. check_expr_or_type(c, operand, ce->args[0]);
  2528. if (operand->mode == Addressing_Invalid) {
  2529. return false;
  2530. }
  2531. /* fallthrough */
  2532. case BuiltinProc_cap:
  2533. {
  2534. // len :: proc(Type) -> int
  2535. // cap :: proc(Type) -> int
  2536. Type *op_type = type_deref(operand->type);
  2537. Type *type = t_int;
  2538. AddressingMode mode = Addressing_Invalid;
  2539. ExactValue value = {};
  2540. if (is_type_string(op_type) && id == BuiltinProc_len) {
  2541. if (operand->mode == Addressing_Constant) {
  2542. mode = Addressing_Constant;
  2543. String str = operand->value.value_string;
  2544. value = exact_value_i64(str.len);
  2545. type = t_untyped_integer;
  2546. } else {
  2547. mode = Addressing_Value;
  2548. if (is_type_cstring(op_type)) {
  2549. add_package_dependency(c, "runtime", "__cstring_len");
  2550. }
  2551. }
  2552. } else if (is_type_array(op_type)) {
  2553. Type *at = core_type(op_type);
  2554. mode = Addressing_Constant;
  2555. value = exact_value_i64(at->Array.count);
  2556. type = t_untyped_integer;
  2557. } else if (is_type_slice(op_type) && id == BuiltinProc_len) {
  2558. mode = Addressing_Value;
  2559. } else if (is_type_dynamic_array(op_type)) {
  2560. mode = Addressing_Value;
  2561. } else if (is_type_map(op_type)) {
  2562. mode = Addressing_Value;
  2563. } else if (operand->mode == Addressing_Type && is_type_enum(op_type) && id == BuiltinProc_len) {
  2564. Type *bt = base_type(op_type);
  2565. mode = Addressing_Constant;
  2566. value = exact_value_i64(bt->Enum.fields.count);
  2567. type = t_untyped_integer;
  2568. }
  2569. if (mode == Addressing_Invalid) {
  2570. String name = builtin_procs[id].name;
  2571. gbString t = type_to_string(operand->type);
  2572. error(call, "'%.*s' is not supported for '%s'", LIT(name), t);
  2573. return false;
  2574. }
  2575. operand->mode = mode;
  2576. operand->value = value;
  2577. operand->type = type;
  2578. break;
  2579. }
  2580. case BuiltinProc_size_of: {
  2581. // size_of :: proc(Type or expr) -> untyped int
  2582. Operand o = {};
  2583. check_expr_or_type(c, &o, ce->args[0]);
  2584. if (o.mode == Addressing_Invalid) {
  2585. return false;
  2586. }
  2587. Type *t = o.type;
  2588. if (t == nullptr || t == t_invalid) {
  2589. error(ce->args[0], "Invalid argument for 'size_of'");
  2590. return false;
  2591. }
  2592. t = default_type(t);
  2593. operand->mode = Addressing_Constant;
  2594. operand->value = exact_value_i64(type_size_of(t));
  2595. operand->type = t_untyped_integer;
  2596. break;
  2597. }
  2598. case BuiltinProc_align_of: {
  2599. // align_of :: proc(Type or expr) -> untyped int
  2600. Operand o = {};
  2601. check_expr_or_type(c, &o, ce->args[0]);
  2602. if (o.mode == Addressing_Invalid) {
  2603. return false;
  2604. }
  2605. Type *t = o.type;
  2606. if (t == nullptr || t == t_invalid) {
  2607. error(ce->args[0], "Invalid argument for 'align_of'");
  2608. return false;
  2609. }
  2610. t = default_type(t);
  2611. operand->mode = Addressing_Constant;
  2612. operand->value = exact_value_i64(type_align_of(t));
  2613. operand->type = t_untyped_integer;
  2614. break;
  2615. }
  2616. case BuiltinProc_offset_of: {
  2617. // offset_of :: proc(Type, field) -> uintptr
  2618. Operand op = {};
  2619. Type *bt = check_type(c, ce->args[0]);
  2620. Type *type = base_type(bt);
  2621. if (type == nullptr || type == t_invalid) {
  2622. error(ce->args[0], "Expected a type for 'offset_of'");
  2623. return false;
  2624. }
  2625. Ast *field_arg = unparen_expr(ce->args[1]);
  2626. if (field_arg == nullptr ||
  2627. field_arg->kind != Ast_Ident) {
  2628. error(field_arg, "Expected an identifier for field argument");
  2629. return false;
  2630. }
  2631. if (is_type_array(type)) {
  2632. error(field_arg, "Invalid type for 'offset_of'");
  2633. return false;
  2634. }
  2635. ast_node(arg, Ident, field_arg);
  2636. Selection sel = lookup_field(type, arg->token.string, operand->mode == Addressing_Type);
  2637. if (sel.entity == nullptr) {
  2638. gbString type_str = type_to_string(bt);
  2639. error(ce->args[0],
  2640. "'%s' has no field named '%.*s'", type_str, LIT(arg->token.string));
  2641. gb_string_free(type_str);
  2642. return false;
  2643. }
  2644. if (sel.indirect) {
  2645. gbString type_str = type_to_string(bt);
  2646. error(ce->args[0],
  2647. "Field '%.*s' is embedded via a pointer in '%s'", LIT(arg->token.string), type_str);
  2648. gb_string_free(type_str);
  2649. return false;
  2650. }
  2651. operand->mode = Addressing_Constant;
  2652. operand->value = exact_value_i64(type_offset_of_from_selection(type, sel));
  2653. operand->type = t_uintptr;
  2654. break;
  2655. }
  2656. case BuiltinProc_type_of: {
  2657. // type_of :: proc(val: Type) -> type(Type)
  2658. Ast *expr = ce->args[0];
  2659. Operand o = {};
  2660. check_expr_or_type(c, &o, expr);
  2661. // check_assignment(c, operand, nullptr, str_lit("argument of 'type_of'"));
  2662. if (o.mode == Addressing_Invalid || o.mode == Addressing_Builtin) {
  2663. return false;
  2664. }
  2665. if (o.type == nullptr || o.type == t_invalid) {
  2666. error(o.expr, "Invalid argument to 'type_of'");
  2667. return false;
  2668. }
  2669. if (o.type == nullptr || o.type == t_invalid) {
  2670. error(o.expr, "Invalid argument to 'type_of'");
  2671. return false;
  2672. }
  2673. // NOTE(bill): Prevent type cycles for procedure declarations
  2674. if (c->curr_proc_sig == o.type) {
  2675. gbString s = expr_to_string(o.expr);
  2676. error(o.expr, "Invalid cyclic type usage from 'type_of', got '%s'", s);
  2677. gb_string_free(s);
  2678. return false;
  2679. }
  2680. if (is_type_polymorphic(o.type)) {
  2681. error(o.expr, "'type_of' of polymorphic type cannot be determined");
  2682. return false;
  2683. }
  2684. operand->mode = Addressing_Type;
  2685. operand->type = o.type;
  2686. break;
  2687. }
  2688. case BuiltinProc_type_info_of: {
  2689. // type_info_of :: proc(Type) -> ^Type_Info
  2690. if (c->scope->flags&ScopeFlag_Global) {
  2691. compiler_error("'type_info_of' Cannot be declared within the runtime package due to how the internals of the compiler works");
  2692. }
  2693. // NOTE(bill): The type information may not be setup yet
  2694. init_core_type_info(c->checker);
  2695. Ast *expr = ce->args[0];
  2696. Operand o = {};
  2697. check_expr_or_type(c, &o, expr);
  2698. if (o.mode == Addressing_Invalid) {
  2699. return false;
  2700. }
  2701. Type *t = o.type;
  2702. if (t == nullptr || t == t_invalid || is_type_polymorphic(operand->type)) {
  2703. error(ce->args[0], "Invalid argument for 'type_info_of'");
  2704. return false;
  2705. }
  2706. t = default_type(t);
  2707. add_type_info_type(c, t);
  2708. if (is_operand_value(o) && is_type_typeid(t)) {
  2709. add_package_dependency(c, "runtime", "__type_info_of");
  2710. } else if (o.mode != Addressing_Type) {
  2711. error(expr, "Expected a type or typeid for 'type_info_of'");
  2712. return false;
  2713. }
  2714. operand->mode = Addressing_Value;
  2715. operand->type = t_type_info_ptr;
  2716. break;
  2717. }
  2718. case BuiltinProc_typeid_of: {
  2719. // typeid_of :: proc(Type) -> typeid
  2720. if (c->scope->flags&ScopeFlag_Global) {
  2721. compiler_error("'typeid_of' Cannot be declared within the runtime package due to how the internals of the compiler works");
  2722. }
  2723. // NOTE(bill): The type information may not be setup yet
  2724. init_core_type_info(c->checker);
  2725. Ast *expr = ce->args[0];
  2726. Operand o = {};
  2727. check_expr_or_type(c, &o, expr);
  2728. if (o.mode == Addressing_Invalid) {
  2729. return false;
  2730. }
  2731. Type *t = o.type;
  2732. if (t == nullptr || t == t_invalid || is_type_polymorphic(operand->type)) {
  2733. error(ce->args[0], "Invalid argument for 'typeid_of'");
  2734. return false;
  2735. }
  2736. t = default_type(t);
  2737. add_type_info_type(c, t);
  2738. t = base_type(t);
  2739. if (is_operand_value(o) && are_types_identical(t, t_type_info_ptr)) {
  2740. add_package_dependency(c, "runtime", "__typeid_of");
  2741. } else if (o.mode != Addressing_Type) {
  2742. error(expr, "Expected a type or type info for 'typeid_of'");
  2743. return false;
  2744. }
  2745. operand->mode = Addressing_Value;
  2746. operand->type = t_typeid;
  2747. break;
  2748. }
  2749. case BuiltinProc_swizzle: {
  2750. // swizzle :: proc(v: [N]T, ...int) -> [M]T
  2751. Type *type = base_type(operand->type);
  2752. if (!is_type_array(type)) {
  2753. gbString type_str = type_to_string(operand->type);
  2754. error(call,
  2755. "You can only 'swizzle' an array, got '%s'",
  2756. type_str);
  2757. gb_string_free(type_str);
  2758. return false;
  2759. }
  2760. i64 max_count = type->Array.count;
  2761. Type *elem_type = type->Array.elem;
  2762. i64 arg_count = 0;
  2763. for_array(i, ce->args) {
  2764. if (i == 0) {
  2765. continue;
  2766. }
  2767. Ast *arg = ce->args[i];
  2768. Operand op = {};
  2769. check_expr(c, &op, arg);
  2770. if (op.mode == Addressing_Invalid) {
  2771. return false;
  2772. }
  2773. Type *arg_type = base_type(op.type);
  2774. if (!is_type_integer(arg_type) || op.mode != Addressing_Constant) {
  2775. error(op.expr, "Indices to 'swizzle' must be constant integers");
  2776. return false;
  2777. }
  2778. if (op.value.value_integer.neg) {
  2779. error(op.expr, "Negative 'swizzle' index");
  2780. return false;
  2781. }
  2782. BigInt mc = {};
  2783. big_int_from_i64(&mc, max_count);
  2784. if (big_int_cmp(&mc, &op.value.value_integer) <= 0) {
  2785. error(op.expr, "'swizzle' index exceeds length");
  2786. return false;
  2787. }
  2788. arg_count++;
  2789. }
  2790. if (arg_count > max_count) {
  2791. error(call, "Too many 'swizzle' indices, %td > %td", arg_count, max_count);
  2792. return false;
  2793. }
  2794. if (arg_count < max_count) {
  2795. operand->type = alloc_type_array(elem_type, arg_count);
  2796. }
  2797. operand->mode = Addressing_Value;
  2798. break;
  2799. }
  2800. case BuiltinProc_complex: {
  2801. // complex :: proc(real, imag: float_type) -> complex_type
  2802. Operand x = *operand;
  2803. Operand y = {};
  2804. // NOTE(bill): Invalid will be the default till fixed
  2805. operand->type = t_invalid;
  2806. operand->mode = Addressing_Invalid;
  2807. check_expr(c, &y, ce->args[1]);
  2808. if (y.mode == Addressing_Invalid) {
  2809. return false;
  2810. }
  2811. convert_to_typed(c, &x, y.type); if (x.mode == Addressing_Invalid) return false;
  2812. convert_to_typed(c, &y, x.type); if (y.mode == Addressing_Invalid) return false;
  2813. if (x.mode == Addressing_Constant &&
  2814. y.mode == Addressing_Constant) {
  2815. if (is_type_numeric(x.type) && exact_value_imag(x.value).value_float == 0) {
  2816. x.type = t_untyped_float;
  2817. }
  2818. if (is_type_numeric(y.type) && exact_value_imag(y.value).value_float == 0) {
  2819. y.type = t_untyped_float;
  2820. }
  2821. }
  2822. if (!are_types_identical(x.type, y.type)) {
  2823. gbString tx = type_to_string(x.type);
  2824. gbString ty = type_to_string(y.type);
  2825. error(call, "Mismatched types to 'complex', '%s' vs '%s'", tx, ty);
  2826. gb_string_free(ty);
  2827. gb_string_free(tx);
  2828. return false;
  2829. }
  2830. if (!is_type_float(x.type)) {
  2831. gbString s = type_to_string(x.type);
  2832. error(call, "Arguments have type '%s', expected a floating point", s);
  2833. gb_string_free(s);
  2834. return false;
  2835. }
  2836. if (x.mode == Addressing_Constant && y.mode == Addressing_Constant) {
  2837. operand->value = exact_binary_operator_value(Token_Add, x.value, y.value);
  2838. operand->mode = Addressing_Constant;
  2839. } else {
  2840. operand->mode = Addressing_Value;
  2841. }
  2842. BasicKind kind = core_type(x.type)->Basic.kind;
  2843. switch (kind) {
  2844. // case Basic_f16: operand->type = t_complex32; break;
  2845. case Basic_f32: operand->type = t_complex64; break;
  2846. case Basic_f64: operand->type = t_complex128; break;
  2847. case Basic_UntypedFloat: operand->type = t_untyped_complex; break;
  2848. default: GB_PANIC("Invalid type"); break;
  2849. }
  2850. break;
  2851. }
  2852. case BuiltinProc_real:
  2853. case BuiltinProc_imag: {
  2854. // real :: proc(x: type) -> float_type
  2855. // proc imag(x: type) -> float_type
  2856. Operand *x = operand;
  2857. if (is_type_untyped(x->type)) {
  2858. if (x->mode == Addressing_Constant) {
  2859. if (is_type_numeric(x->type)) {
  2860. x->type = t_untyped_complex;
  2861. }
  2862. } else {
  2863. convert_to_typed(c, x, t_complex128);
  2864. if (x->mode == Addressing_Invalid) {
  2865. return false;
  2866. }
  2867. }
  2868. }
  2869. if (!is_type_complex(x->type)) {
  2870. gbString s = type_to_string(x->type);
  2871. error(call, "Argument has type '%s', expected a complex type", s);
  2872. gb_string_free(s);
  2873. return false;
  2874. }
  2875. if (x->mode == Addressing_Constant) {
  2876. switch (id) {
  2877. case BuiltinProc_real: x->value = exact_value_real(x->value); break;
  2878. case BuiltinProc_imag: x->value = exact_value_imag(x->value); break;
  2879. }
  2880. } else {
  2881. x->mode = Addressing_Value;
  2882. }
  2883. BasicKind kind = core_type(x->type)->Basic.kind;
  2884. switch (kind) {
  2885. case Basic_complex64: x->type = t_f32; break;
  2886. case Basic_complex128: x->type = t_f64; break;
  2887. case Basic_UntypedComplex: x->type = t_untyped_float; break;
  2888. default: GB_PANIC("Invalid type"); break;
  2889. }
  2890. break;
  2891. }
  2892. case BuiltinProc_conj: {
  2893. // conj :: proc(x: type) -> type
  2894. Operand *x = operand;
  2895. if (is_type_complex(x->type)) {
  2896. if (x->mode == Addressing_Constant) {
  2897. ExactValue v = exact_value_to_complex(x->value);
  2898. f64 r = v.value_complex.real;
  2899. f64 i = v.value_complex.imag;
  2900. x->value = exact_value_complex(r, i);
  2901. x->mode = Addressing_Constant;
  2902. } else {
  2903. x->mode = Addressing_Value;
  2904. }
  2905. } else {
  2906. gbString s = type_to_string(x->type);
  2907. error(call, "Expected a complex or quaternion, got '%s'", s);
  2908. gb_string_free(s);
  2909. return false;
  2910. }
  2911. break;
  2912. }
  2913. case BuiltinProc_expand_to_tuple: {
  2914. Type *type = base_type(operand->type);
  2915. if (!is_type_struct(type) && !is_type_array(type)) {
  2916. gbString type_str = type_to_string(operand->type);
  2917. error(call, "Expected a struct or array type, got '%s'", type_str);
  2918. gb_string_free(type_str);
  2919. return false;
  2920. }
  2921. gbAllocator a = c->allocator;
  2922. Type *tuple = alloc_type_tuple();
  2923. if (is_type_struct(type)) {
  2924. isize variable_count = type->Struct.fields.count;
  2925. array_init(&tuple->Tuple.variables, a, variable_count);
  2926. // TODO(bill): Should I copy each of the entities or is this good enough?
  2927. gb_memmove_array(tuple->Tuple.variables.data, type->Struct.fields.data, variable_count);
  2928. } else if (is_type_array(type)) {
  2929. isize variable_count = type->Array.count;
  2930. array_init(&tuple->Tuple.variables, a, variable_count);
  2931. for (isize i = 0; i < variable_count; i++) {
  2932. tuple->Tuple.variables[i] = alloc_entity_array_elem(nullptr, blank_token, type->Array.elem, cast(i32)i);
  2933. }
  2934. }
  2935. operand->type = tuple;
  2936. operand->mode = Addressing_Value;
  2937. break;
  2938. }
  2939. case BuiltinProc_min: {
  2940. // min :: proc(a, b: ordered) -> ordered
  2941. Type *type = base_type(operand->type);
  2942. if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {
  2943. gbString type_str = type_to_string(operand->type);
  2944. error(call, "Expected a ordered numeric type to 'min', got '%s'", type_str);
  2945. gb_string_free(type_str);
  2946. return false;
  2947. }
  2948. Ast *other_arg = ce->args[1];
  2949. Operand a = *operand;
  2950. Operand b = {};
  2951. check_expr(c, &b, other_arg);
  2952. if (b.mode == Addressing_Invalid) {
  2953. return false;
  2954. }
  2955. if (!is_type_ordered(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) {
  2956. gbString type_str = type_to_string(b.type);
  2957. error(call,
  2958. "Expected a ordered numeric type to 'min', got '%s'",
  2959. type_str);
  2960. gb_string_free(type_str);
  2961. return false;
  2962. }
  2963. if (a.mode == Addressing_Constant &&
  2964. b.mode == Addressing_Constant) {
  2965. ExactValue x = a.value;
  2966. ExactValue y = b.value;
  2967. operand->mode = Addressing_Constant;
  2968. if (compare_exact_values(Token_Lt, x, y)) {
  2969. operand->value = x;
  2970. operand->type = a.type;
  2971. } else {
  2972. operand->value = y;
  2973. operand->type = b.type;
  2974. }
  2975. } else {
  2976. operand->mode = Addressing_Value;
  2977. operand->type = type;
  2978. convert_to_typed(c, &a, b.type);
  2979. if (a.mode == Addressing_Invalid) {
  2980. return false;
  2981. }
  2982. convert_to_typed(c, &b, a.type);
  2983. if (b.mode == Addressing_Invalid) {
  2984. return false;
  2985. }
  2986. if (!are_types_identical(a.type, b.type)) {
  2987. gbString type_a = type_to_string(a.type);
  2988. gbString type_b = type_to_string(b.type);
  2989. error(call,
  2990. "Mismatched types to 'min', '%s' vs '%s'",
  2991. type_a, type_b);
  2992. gb_string_free(type_b);
  2993. gb_string_free(type_a);
  2994. return false;
  2995. }
  2996. {
  2997. Type *bt = base_type(a.type);
  2998. if (bt == t_f32) add_package_dependency(c, "runtime", "__min_f32");
  2999. if (bt == t_f64) add_package_dependency(c, "runtime", "__min_f64");
  3000. }
  3001. }
  3002. break;
  3003. }
  3004. case BuiltinProc_max: {
  3005. // min :: proc(a, b: ordered) -> ordered
  3006. Type *type = base_type(operand->type);
  3007. if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {
  3008. gbString type_str = type_to_string(operand->type);
  3009. error(call,
  3010. "Expected a ordered numeric or string type to 'max', got '%s'",
  3011. type_str);
  3012. gb_string_free(type_str);
  3013. return false;
  3014. }
  3015. Ast *other_arg = ce->args[1];
  3016. Operand a = *operand;
  3017. Operand b = {};
  3018. check_expr(c, &b, other_arg);
  3019. if (b.mode == Addressing_Invalid) {
  3020. return false;
  3021. }
  3022. if (!is_type_ordered(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) {
  3023. gbString type_str = type_to_string(b.type);
  3024. error(call,
  3025. "Expected a ordered numeric or string type to 'max', got '%s'",
  3026. type_str);
  3027. gb_string_free(type_str);
  3028. return false;
  3029. }
  3030. if (a.mode == Addressing_Constant &&
  3031. b.mode == Addressing_Constant) {
  3032. ExactValue x = a.value;
  3033. ExactValue y = b.value;
  3034. operand->mode = Addressing_Constant;
  3035. if (compare_exact_values(Token_Gt, x, y)) {
  3036. operand->value = x;
  3037. operand->type = a.type;
  3038. } else {
  3039. operand->value = y;
  3040. operand->type = b.type;
  3041. }
  3042. } else {
  3043. operand->mode = Addressing_Value;
  3044. operand->type = type;
  3045. convert_to_typed(c, &a, b.type);
  3046. if (a.mode == Addressing_Invalid) {
  3047. return false;
  3048. }
  3049. convert_to_typed(c, &b, a.type);
  3050. if (b.mode == Addressing_Invalid) {
  3051. return false;
  3052. }
  3053. if (!are_types_identical(a.type, b.type)) {
  3054. gbString type_a = type_to_string(a.type);
  3055. gbString type_b = type_to_string(b.type);
  3056. error(call,
  3057. "Mismatched types to 'max', '%s' vs '%s'",
  3058. type_a, type_b);
  3059. gb_string_free(type_b);
  3060. gb_string_free(type_a);
  3061. return false;
  3062. }
  3063. {
  3064. Type *bt = base_type(a.type);
  3065. if (bt == t_f32) add_package_dependency(c, "runtime", "__max_f32");
  3066. if (bt == t_f64) add_package_dependency(c, "runtime", "__max_f64");
  3067. }
  3068. }
  3069. break;
  3070. }
  3071. case BuiltinProc_abs: {
  3072. // abs :: proc(n: numeric) -> numeric
  3073. if (!is_type_numeric(operand->type)) {
  3074. gbString type_str = type_to_string(operand->type);
  3075. error(call, "Expected a numeric type to 'abs', got '%s'", type_str);
  3076. gb_string_free(type_str);
  3077. return false;
  3078. }
  3079. if (operand->mode == Addressing_Constant) {
  3080. switch (operand->value.kind) {
  3081. case ExactValue_Integer:
  3082. operand->value.value_integer.neg = false;
  3083. break;
  3084. case ExactValue_Float:
  3085. operand->value.value_float = gb_abs(operand->value.value_float);
  3086. break;
  3087. case ExactValue_Complex: {
  3088. f64 r = operand->value.value_complex.real;
  3089. f64 i = operand->value.value_complex.imag;
  3090. operand->value = exact_value_float(gb_sqrt(r*r + i*i));
  3091. break;
  3092. }
  3093. default:
  3094. GB_PANIC("Invalid numeric constant");
  3095. break;
  3096. }
  3097. } else {
  3098. operand->mode = Addressing_Value;
  3099. {
  3100. Type *bt = base_type(operand->type);
  3101. if (bt == t_f32) add_package_dependency(c, "runtime", "__abs_f32");
  3102. if (bt == t_f64) add_package_dependency(c, "runtime", "__abs_f64");
  3103. if (bt == t_complex64) add_package_dependency(c, "runtime", "__abs_complex64");
  3104. if (bt == t_complex128) add_package_dependency(c, "runtime", "__abs_complex128");
  3105. }
  3106. }
  3107. if (is_type_complex(operand->type)) {
  3108. operand->type = base_complex_elem_type(operand->type);
  3109. }
  3110. GB_ASSERT(!is_type_complex(operand->type));
  3111. break;
  3112. }
  3113. case BuiltinProc_clamp: {
  3114. // clamp :: proc(a, min, max: ordered) -> ordered
  3115. Type *type = base_type(operand->type);
  3116. if (!is_type_ordered(type) || !(is_type_numeric(type) || is_type_string(type))) {
  3117. gbString type_str = type_to_string(operand->type);
  3118. error(call, "Expected a ordered numeric or string type to 'clamp', got '%s'", type_str);
  3119. gb_string_free(type_str);
  3120. return false;
  3121. }
  3122. Ast *min_arg = ce->args[1];
  3123. Ast *max_arg = ce->args[2];
  3124. Operand x = *operand;
  3125. Operand y = {};
  3126. Operand z = {};
  3127. check_expr(c, &y, min_arg);
  3128. if (y.mode == Addressing_Invalid) {
  3129. return false;
  3130. }
  3131. if (!is_type_ordered(y.type) || !(is_type_numeric(y.type) || is_type_string(y.type))) {
  3132. gbString type_str = type_to_string(y.type);
  3133. error(call, "Expected a ordered numeric or string type to 'clamp', got '%s'", type_str);
  3134. gb_string_free(type_str);
  3135. return false;
  3136. }
  3137. check_expr(c, &z, max_arg);
  3138. if (z.mode == Addressing_Invalid) {
  3139. return false;
  3140. }
  3141. if (!is_type_ordered(z.type) || !(is_type_numeric(z.type) || is_type_string(z.type))) {
  3142. gbString type_str = type_to_string(z.type);
  3143. error(call, "Expected a ordered numeric or string type to 'clamp', got '%s'", type_str);
  3144. gb_string_free(type_str);
  3145. return false;
  3146. }
  3147. if (x.mode == Addressing_Constant &&
  3148. y.mode == Addressing_Constant &&
  3149. z.mode == Addressing_Constant) {
  3150. ExactValue a = x.value;
  3151. ExactValue b = y.value;
  3152. ExactValue c = z.value;
  3153. operand->mode = Addressing_Constant;
  3154. if (compare_exact_values(Token_Lt, a, b)) {
  3155. operand->value = b;
  3156. operand->type = y.type;
  3157. } else if (compare_exact_values(Token_Gt, a, c)) {
  3158. operand->value = c;
  3159. operand->type = z.type;
  3160. } else {
  3161. operand->value = a;
  3162. operand->type = x.type;
  3163. }
  3164. } else {
  3165. operand->mode = Addressing_Value;
  3166. operand->type = type;
  3167. convert_to_typed(c, &x, y.type);
  3168. if (x.mode == Addressing_Invalid) { return false; }
  3169. convert_to_typed(c, &y, x.type);
  3170. if (y.mode == Addressing_Invalid) { return false; }
  3171. convert_to_typed(c, &x, z.type);
  3172. if (x.mode == Addressing_Invalid) { return false; }
  3173. convert_to_typed(c, &z, x.type);
  3174. if (z.mode == Addressing_Invalid) { return false; }
  3175. convert_to_typed(c, &y, z.type);
  3176. if (y.mode == Addressing_Invalid) { return false; }
  3177. convert_to_typed(c, &z, y.type);
  3178. if (z.mode == Addressing_Invalid) { return false; }
  3179. if (!are_types_identical(x.type, y.type) || !are_types_identical(x.type, z.type)) {
  3180. gbString type_x = type_to_string(x.type);
  3181. gbString type_y = type_to_string(y.type);
  3182. gbString type_z = type_to_string(z.type);
  3183. error(call,
  3184. "Mismatched types to 'clamp', '%s', '%s', '%s'",
  3185. type_x, type_y, type_z);
  3186. gb_string_free(type_z);
  3187. gb_string_free(type_y);
  3188. gb_string_free(type_x);
  3189. return false;
  3190. }
  3191. {
  3192. Type *bt = base_type(x.type);
  3193. if (bt == t_f32) {
  3194. add_package_dependency(c, "runtime", "__min_f32");
  3195. add_package_dependency(c, "runtime", "__max_f32");
  3196. }
  3197. if (bt == t_f64) {
  3198. add_package_dependency(c, "runtime", "__min_f64");
  3199. add_package_dependency(c, "runtime", "__max_f64");
  3200. }
  3201. }
  3202. }
  3203. break;
  3204. }
  3205. }
  3206. return true;
  3207. }
  3208. isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) {
  3209. if (lhs != nullptr) {
  3210. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  3211. Entity *e = lhs[tuple_index + j];
  3212. DeclInfo *decl = decl_info_of_entity(e);
  3213. if (decl != nullptr) {
  3214. c->decl = decl; // will be reset by the 'defer' any way
  3215. for_array(k, decl->deps.entries) {
  3216. Entity *dep = decl->deps.entries[k].ptr;
  3217. add_declaration_dependency(c, dep); // TODO(bill): Should this be here?
  3218. }
  3219. }
  3220. }
  3221. }
  3222. return tuple_count;
  3223. }
  3224. bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Array<Ast *> const &rhs) {
  3225. bool optional_ok = false;
  3226. isize tuple_index = 0;
  3227. for_array(i, rhs) {
  3228. CheckerContext c_ = *ctx;
  3229. CheckerContext *c = &c_;
  3230. Operand o = {};
  3231. Type *type_hint = nullptr;
  3232. if (tuple_index < lhs.count) {
  3233. type_hint = lhs[tuple_index].type;
  3234. }
  3235. check_expr_base(c, &o, rhs[i], type_hint);
  3236. if (o.mode == Addressing_NoValue) {
  3237. error_operand_no_value(&o);
  3238. o.mode = Addressing_Invalid;
  3239. }
  3240. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  3241. if (lhs.count == 2 && rhs.count == 1 &&
  3242. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk)) {
  3243. Type *tuple = make_optional_ok_type(o.type);
  3244. add_type_and_value(&c->checker->info, o.expr, o.mode, tuple, o.value);
  3245. Operand val = o;
  3246. Operand ok = o;
  3247. val.mode = Addressing_Value;
  3248. ok.mode = Addressing_Value;
  3249. ok.type = t_untyped_bool;
  3250. array_add(operands, val);
  3251. array_add(operands, ok);
  3252. optional_ok = true;
  3253. tuple_index += 2;
  3254. } else {
  3255. array_add(operands, o);
  3256. tuple_index += 1;
  3257. }
  3258. } else {
  3259. TypeTuple *tuple = &o.type->Tuple;
  3260. for_array(j, tuple->variables) {
  3261. o.type = tuple->variables[j]->type;
  3262. array_add(operands, o);
  3263. }
  3264. isize count = tuple->variables.count;
  3265. tuple_index += 2;
  3266. }
  3267. }
  3268. return optional_ok;
  3269. }
  3270. bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Array<Ast *> const &rhs, bool allow_ok) {
  3271. bool optional_ok = false;
  3272. isize tuple_index = 0;
  3273. for_array(i, rhs) {
  3274. CheckerContext c_ = *ctx;
  3275. CheckerContext *c = &c_;
  3276. Operand o = {};
  3277. Type *type_hint = nullptr;
  3278. if (lhs != nullptr && tuple_index < lhs_count) {
  3279. // NOTE(bill): override DeclInfo for dependency
  3280. Entity *e = lhs[tuple_index];
  3281. DeclInfo *decl = decl_info_of_entity(e);
  3282. if (decl) c->decl = decl;
  3283. type_hint = e->type;
  3284. }
  3285. check_expr_base(c, &o, rhs[i], type_hint);
  3286. if (o.mode == Addressing_NoValue) {
  3287. error_operand_no_value(&o);
  3288. o.mode = Addressing_Invalid;
  3289. }
  3290. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  3291. if (allow_ok && lhs_count == 2 && rhs.count == 1 &&
  3292. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk)) {
  3293. Type *tuple = make_optional_ok_type(o.type);
  3294. add_type_and_value(&c->checker->info, o.expr, o.mode, tuple, o.value);
  3295. Operand val = o;
  3296. Operand ok = o;
  3297. val.mode = Addressing_Value;
  3298. ok.mode = Addressing_Value;
  3299. ok.type = t_bool;
  3300. array_add(operands, val);
  3301. array_add(operands, ok);
  3302. optional_ok = true;
  3303. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  3304. } else {
  3305. array_add(operands, o);
  3306. tuple_index += 1;
  3307. }
  3308. } else {
  3309. TypeTuple *tuple = &o.type->Tuple;
  3310. for_array(j, tuple->variables) {
  3311. o.type = tuple->variables[j]->type;
  3312. array_add(operands, o);
  3313. }
  3314. isize count = tuple->variables.count;
  3315. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  3316. }
  3317. }
  3318. return optional_ok;
  3319. }
  3320. CALL_ARGUMENT_CHECKER(check_call_arguments_internal) {
  3321. ast_node(ce, CallExpr, call);
  3322. GB_ASSERT(is_type_proc(proc_type));
  3323. proc_type = base_type(proc_type);
  3324. TypeProc *pt = &proc_type->Proc;
  3325. isize param_count = 0;
  3326. isize param_count_excluding_defaults = 0;
  3327. bool variadic = pt->variadic;
  3328. bool vari_expand = (ce->ellipsis.pos.line != 0);
  3329. i64 score = 0;
  3330. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  3331. TypeTuple *param_tuple = nullptr;
  3332. if (pt->params != nullptr) {
  3333. param_tuple = &pt->params->Tuple;
  3334. param_count = param_tuple->variables.count;
  3335. if (variadic) {
  3336. for (isize i = param_count-1; i >= 0; i--) {
  3337. Entity *e = param_tuple->variables[i];
  3338. if (e->kind == Entity_TypeName) {
  3339. break;
  3340. }
  3341. if (e->kind == Entity_Variable) {
  3342. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  3343. param_count--;
  3344. continue;
  3345. }
  3346. }
  3347. break;
  3348. }
  3349. param_count--;
  3350. }
  3351. }
  3352. param_count_excluding_defaults = param_count;
  3353. if (param_tuple != nullptr) {
  3354. for (isize i = param_count-1; i >= 0; i--) {
  3355. Entity *e = param_tuple->variables[i];
  3356. if (e->kind == Entity_TypeName) {
  3357. break;
  3358. }
  3359. if (e->kind == Entity_Variable) {
  3360. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  3361. param_count_excluding_defaults--;
  3362. continue;
  3363. }
  3364. }
  3365. break;
  3366. }
  3367. }
  3368. CallArgumentError err = CallArgumentError_None;
  3369. Type *final_proc_type = proc_type;
  3370. Entity *gen_entity = nullptr;
  3371. if (vari_expand && !variadic) {
  3372. if (show_error) {
  3373. error(ce->ellipsis,
  3374. "Cannot use '...' in call to a non-variadic procedure: '%.*s'",
  3375. LIT(ce->proc->Ident.token.string));
  3376. }
  3377. err = CallArgumentError_NonVariadicExpand;
  3378. } else if (vari_expand && pt->c_vararg) {
  3379. if (show_error) {
  3380. error(ce->ellipsis,
  3381. "Cannot use '...' in call to a '#c_vararg' variadic procedure: '%.*s'",
  3382. LIT(ce->proc->Ident.token.string));
  3383. }
  3384. err = CallArgumentError_NonVariadicExpand;
  3385. } else if (operands.count == 0 && param_count_excluding_defaults == 0) {
  3386. err = CallArgumentError_None;
  3387. } else {
  3388. i32 error_code = 0;
  3389. if (operands.count < param_count_excluding_defaults) {
  3390. error_code = -1;
  3391. } else if (!variadic && operands.count > param_count) {
  3392. error_code = +1;
  3393. }
  3394. if (error_code != 0) {
  3395. err = CallArgumentError_TooManyArguments;
  3396. char *err_fmt = "Too many arguments for '%s', expected %td arguments";
  3397. if (error_code < 0) {
  3398. err = CallArgumentError_TooFewArguments;
  3399. err_fmt = "Too few arguments for '%s', expected %td arguments";
  3400. }
  3401. if (show_error) {
  3402. gbString proc_str = expr_to_string(ce->proc);
  3403. error(call, err_fmt, proc_str, param_count_excluding_defaults);
  3404. gb_string_free(proc_str);
  3405. }
  3406. } else {
  3407. // NOTE(bill): Generate the procedure type for this generic instance
  3408. PolyProcData poly_proc_data = {};
  3409. if (pt->is_polymorphic && !pt->is_poly_specialized) {
  3410. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &operands, call, &poly_proc_data)) {
  3411. gen_entity = poly_proc_data.gen_entity;
  3412. GB_ASSERT(is_type_proc(gen_entity->type));
  3413. final_proc_type = gen_entity->type;
  3414. } else {
  3415. err = CallArgumentError_WrongTypes;
  3416. }
  3417. }
  3418. GB_ASSERT(is_type_proc(final_proc_type));
  3419. TypeProc *pt = &final_proc_type->Proc;
  3420. GB_ASSERT(pt->params != nullptr);
  3421. auto sig_params = pt->params->Tuple.variables;
  3422. isize operand_index = 0;
  3423. isize max_operand_count = gb_min(param_count, operands.count);
  3424. for (; operand_index < max_operand_count; operand_index++) {
  3425. Entity *e = sig_params[operand_index];
  3426. Type *t = e->type;
  3427. Operand o = operands[operand_index];
  3428. if (e->kind == Entity_TypeName) {
  3429. // GB_ASSERT(!variadic);
  3430. if (o.mode == Addressing_Invalid) {
  3431. continue;
  3432. } else if (o.mode != Addressing_Type) {
  3433. if (show_error) {
  3434. error(o.expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  3435. }
  3436. err = CallArgumentError_WrongTypes;
  3437. }
  3438. if (are_types_identical(e->type, o.type)) {
  3439. score += assign_score_function(1);
  3440. } else {
  3441. score += assign_score_function(10);
  3442. }
  3443. continue;
  3444. }
  3445. i64 s = 0;
  3446. if (!check_is_assignable_to_with_score(c, &o, t, &s)) {
  3447. bool ok = false;
  3448. if (e->flags & EntityFlag_AutoCast) {
  3449. ok = check_is_castable_to(c, &o, t);
  3450. }
  3451. if (ok) {
  3452. s = assign_score_function(10);
  3453. } else {
  3454. if (show_error) {
  3455. check_assignment(c, &o, t, str_lit("argument"));
  3456. }
  3457. err = CallArgumentError_WrongTypes;
  3458. }
  3459. }
  3460. score += s;
  3461. }
  3462. if (variadic) {
  3463. bool variadic_expand = false;
  3464. Type *slice = sig_params[param_count]->type;
  3465. GB_ASSERT(is_type_slice(slice));
  3466. Type *elem = base_type(slice)->Slice.elem;
  3467. Type *t = elem;
  3468. for (; operand_index < operands.count; operand_index++) {
  3469. Operand o = operands[operand_index];
  3470. if (vari_expand) {
  3471. variadic_expand = true;
  3472. t = slice;
  3473. if (operand_index != param_count) {
  3474. if (show_error) {
  3475. error(o.expr, "'...' in a variadic procedure can only have one variadic argument at the end");
  3476. }
  3477. if (data) {
  3478. data->score = score;
  3479. data->result_type = final_proc_type->Proc.results;
  3480. data->gen_entity = gen_entity;
  3481. }
  3482. return CallArgumentError_MultipleVariadicExpand;
  3483. }
  3484. }
  3485. i64 s = 0;
  3486. if (!check_is_assignable_to_with_score(c, &o, t, &s)) {
  3487. if (show_error) {
  3488. check_assignment(c, &o, t, str_lit("argument"));
  3489. }
  3490. err = CallArgumentError_WrongTypes;
  3491. }
  3492. score += s;
  3493. if (is_type_any(elem)) {
  3494. add_type_info_type(c, o.type);
  3495. }
  3496. }
  3497. }
  3498. }
  3499. }
  3500. if (data) {
  3501. data->score = score;
  3502. data->result_type = final_proc_type->Proc.results;
  3503. data->gen_entity = gen_entity;
  3504. }
  3505. return err;
  3506. }
  3507. bool is_call_expr_field_value(AstCallExpr *ce) {
  3508. GB_ASSERT(ce != nullptr);
  3509. if (ce->args.count == 0) {
  3510. return false;
  3511. }
  3512. return ce->args[0]->kind == Ast_FieldValue;
  3513. }
  3514. isize lookup_procedure_parameter(TypeProc *pt, String parameter_name) {
  3515. isize param_count = pt->param_count;
  3516. for (isize i = 0; i < param_count; i++) {
  3517. Entity *e = pt->params->Tuple.variables[i];
  3518. String name = e->token.string;
  3519. if (is_blank_ident(name)) {
  3520. continue;
  3521. }
  3522. if (name == parameter_name) {
  3523. return i;
  3524. }
  3525. }
  3526. return -1;
  3527. }
  3528. isize lookup_procedure_result(TypeProc *pt, String result_name) {
  3529. isize result_count = pt->result_count;
  3530. for (isize i = 0; i < result_count; i++) {
  3531. Entity *e = pt->results->Tuple.variables[i];
  3532. String name = e->token.string;
  3533. if (is_blank_ident(name)) {
  3534. continue;
  3535. }
  3536. if (name == result_name) {
  3537. return i;
  3538. }
  3539. }
  3540. return -1;
  3541. }
  3542. CALL_ARGUMENT_CHECKER(check_named_call_arguments) {
  3543. ast_node(ce, CallExpr, call);
  3544. GB_ASSERT(is_type_proc(proc_type));
  3545. proc_type = base_type(proc_type);
  3546. TypeProc *pt = &proc_type->Proc;
  3547. i64 score = 0;
  3548. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  3549. CallArgumentError err = CallArgumentError_None;
  3550. isize param_count = pt->param_count;
  3551. bool *visited = gb_alloc_array(c->allocator, bool, param_count);
  3552. defer (gb_free(c->allocator, visited));
  3553. auto ordered_operands = array_make<Operand>(c->allocator, param_count);
  3554. defer (array_free(&ordered_operands));
  3555. for_array(i, ce->args) {
  3556. Ast *arg = ce->args[i];
  3557. ast_node(fv, FieldValue, arg);
  3558. if (fv->field->kind != Ast_Ident) {
  3559. if (show_error) {
  3560. gbString expr_str = expr_to_string(fv->field);
  3561. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  3562. gb_string_free(expr_str);
  3563. }
  3564. err = CallArgumentError_InvalidFieldValue;
  3565. continue;
  3566. }
  3567. String name = fv->field->Ident.token.string;
  3568. isize index = lookup_procedure_parameter(pt, name);
  3569. if (index < 0) {
  3570. if (show_error) {
  3571. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  3572. }
  3573. err = CallArgumentError_ParameterNotFound;
  3574. continue;
  3575. }
  3576. if (visited[index]) {
  3577. if (show_error) {
  3578. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  3579. }
  3580. err = CallArgumentError_DuplicateParameter;
  3581. continue;
  3582. }
  3583. visited[index] = true;
  3584. ordered_operands[index] = operands[i];
  3585. }
  3586. // NOTE(bill): Check for default values and missing parameters
  3587. isize param_count_to_check = param_count;
  3588. if (pt->variadic) {
  3589. param_count_to_check--;
  3590. }
  3591. for (isize i = 0; i < param_count_to_check; i++) {
  3592. if (!visited[i]) {
  3593. Entity *e = pt->params->Tuple.variables[i];
  3594. if (is_blank_ident(e->token)) {
  3595. continue;
  3596. }
  3597. if (e->kind == Entity_Variable) {
  3598. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  3599. score += assign_score_function(1);
  3600. continue;
  3601. }
  3602. }
  3603. if (show_error) {
  3604. if (e->kind == Entity_TypeName) {
  3605. error(call, "Type parameter '%.*s' is missing in procedure call",
  3606. LIT(e->token.string));
  3607. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  3608. // Ignore
  3609. } else {
  3610. gbString str = type_to_string(e->type);
  3611. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  3612. LIT(e->token.string), str);
  3613. gb_string_free(str);
  3614. }
  3615. }
  3616. err = CallArgumentError_ParameterMissing;
  3617. }
  3618. }
  3619. Entity *gen_entity = nullptr;
  3620. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  3621. PolyProcData poly_proc_data = {};
  3622. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  3623. gen_entity = poly_proc_data.gen_entity;
  3624. Type *gept = base_type(gen_entity->type);
  3625. GB_ASSERT(is_type_proc(gept));
  3626. proc_type = gept;
  3627. pt = &gept->Proc;
  3628. }
  3629. }
  3630. for (isize i = 0; i < param_count; i++) {
  3631. Operand *o = &ordered_operands[i];
  3632. if (o->mode == Addressing_Invalid) {
  3633. continue;
  3634. }
  3635. Entity *e = pt->params->Tuple.variables[i];
  3636. if (e->kind == Entity_TypeName) {
  3637. GB_ASSERT(pt->is_polymorphic);
  3638. if (o->mode != Addressing_Type) {
  3639. if (show_error) {
  3640. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  3641. }
  3642. err = CallArgumentError_WrongTypes;
  3643. }
  3644. if (are_types_identical(e->type, o->type)) {
  3645. score += assign_score_function(1);
  3646. } else {
  3647. score += assign_score_function(10);
  3648. }
  3649. } else {
  3650. i64 s = 0;
  3651. if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  3652. bool ok = false;
  3653. if (e->flags & EntityFlag_AutoCast) {
  3654. ok = check_is_castable_to(c, o, e->type);
  3655. }
  3656. if (ok) {
  3657. s = assign_score_function(10);
  3658. } else {
  3659. if (show_error) {
  3660. check_assignment(c, o, e->type, str_lit("procedure argument"));
  3661. }
  3662. err = CallArgumentError_WrongTypes;
  3663. }
  3664. }
  3665. score += s;
  3666. }
  3667. }
  3668. if (data) {
  3669. data->score = score;
  3670. data->result_type = pt->results;
  3671. data->gen_entity = gen_entity;
  3672. }
  3673. return err;
  3674. }
  3675. CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Type *proc_type, Ast *call) {
  3676. ast_node(ce, CallExpr, call);
  3677. CallArgumentCheckerType *call_checker = check_call_arguments_internal;
  3678. Array<Operand> operands = {};
  3679. defer (array_free(&operands));
  3680. Type *result_type = t_invalid;
  3681. if (is_call_expr_field_value(ce)) {
  3682. call_checker = check_named_call_arguments;
  3683. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  3684. for_array(i, ce->args) {
  3685. Ast *arg = ce->args[i];
  3686. ast_node(fv, FieldValue, arg);
  3687. check_expr_or_type(c, &operands[i], fv->value);
  3688. }
  3689. bool vari_expand = (ce->ellipsis.pos.line != 0);
  3690. if (vari_expand) {
  3691. // error(ce->ellipsis, "Invalid use of '...' with 'field = value' call'");
  3692. }
  3693. } else {
  3694. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  3695. check_unpack_arguments(c, nullptr, -1, &operands, ce->args, false);
  3696. }
  3697. if (operand->mode == Addressing_ProcGroup) {
  3698. check_entity_decl(c, operand->proc_group, nullptr, nullptr);
  3699. Array<Entity *> procs = proc_group_entities(c, *operand);
  3700. if (procs.count == 1) {
  3701. Ast *ident = operand->expr;
  3702. while (ident->kind == Ast_SelectorExpr) {
  3703. Ast *s = ident->SelectorExpr.selector;
  3704. ident = s;
  3705. }
  3706. Entity *e = procs[0];
  3707. CallArgumentData data = {};
  3708. CallArgumentError err = call_checker(c, call, e->type, e, operands, CallArgumentMode_ShowErrors, &data);
  3709. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  3710. add_entity_use(c, ident, entity_to_use);
  3711. return data;
  3712. }
  3713. ValidIndexAndScore *valids = gb_alloc_array(heap_allocator(), ValidIndexAndScore, procs.count);
  3714. isize valid_count = 0;
  3715. defer (gb_free(heap_allocator(), valids));
  3716. gbString expr_name = expr_to_string(operand->expr);
  3717. defer (gb_string_free(expr_name));
  3718. for_array(i, procs) {
  3719. Entity *p = procs[i];
  3720. check_entity_decl(c, p, nullptr, nullptr);
  3721. Type *pt = base_type(p->type);
  3722. if (pt != nullptr && is_type_proc(pt)) {
  3723. CallArgumentError err = CallArgumentError_None;
  3724. CallArgumentData data = {};
  3725. CheckerContext ctx = *c;
  3726. ctx.no_polymorphic_errors = true;
  3727. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  3728. err = call_checker(&ctx, call, pt, p, operands, CallArgumentMode_NoErrors, &data);
  3729. if (err == CallArgumentError_None) {
  3730. valids[valid_count].index = i;
  3731. valids[valid_count].score = data.score;
  3732. valid_count++;
  3733. }
  3734. }
  3735. }
  3736. if (valid_count > 1) {
  3737. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3738. i64 best_score = valids[0].score;
  3739. Entity *best_entity = procs[valids[0].index];
  3740. for (isize i = 1; i < valid_count; i++) {
  3741. if (best_score > valids[i].score) {
  3742. valid_count = i;
  3743. break;
  3744. }
  3745. if (best_entity == procs[valids[i].index]) {
  3746. valid_count = i;
  3747. break;
  3748. }
  3749. best_score = valids[i].score;
  3750. }
  3751. }
  3752. if (valid_count == 0) {
  3753. bool all_invalid_type = true;
  3754. for_array(i, operands) {
  3755. Operand o = operands[i];
  3756. if (o.type != t_invalid) {
  3757. all_invalid_type = false;
  3758. break;
  3759. }
  3760. }
  3761. if (!all_invalid_type) {
  3762. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  3763. gb_printf_err("\tGiven argument types: (");
  3764. for_array(i, operands) {
  3765. Operand o = operands[i];
  3766. if (i > 0) gb_printf_err(", ");
  3767. gbString type = type_to_string(o.type);
  3768. defer (gb_string_free(type));
  3769. gb_printf_err("%s", type);
  3770. }
  3771. gb_printf_err(")\n");
  3772. if (procs.count > 0) {
  3773. gb_printf_err("Did you mean to use one of the following:\n");
  3774. }
  3775. for_array(i, procs) {
  3776. Entity *proc = procs[i];
  3777. TokenPos pos = proc->token.pos;
  3778. Type *t = base_type(proc->type);
  3779. if (t == t_invalid) continue;
  3780. GB_ASSERT(t->kind == Type_Proc);
  3781. gbString pt;
  3782. defer (gb_string_free(pt));
  3783. if (t->Proc.node != nullptr) {
  3784. pt = expr_to_string(t->Proc.node);
  3785. } else {
  3786. pt = type_to_string(t);
  3787. }
  3788. String prefix = {};
  3789. String prefix_sep = {};
  3790. if (proc->pkg) {
  3791. prefix = proc->pkg->name;
  3792. prefix_sep = str_lit(".");
  3793. }
  3794. String name = proc->token.string;
  3795. char const *sep = "::";
  3796. if (proc->kind == Entity_Variable) {
  3797. sep = ":=";
  3798. }
  3799. // gb_printf_err("\t%.*s %s %s at %.*s(%td:%td) with score %lld\n", LIT(name), sep, pt, LIT(pos.file), pos.line, pos.column, cast(long long)valids[i].score);
  3800. gb_printf_err("\t%.*s%.*s%.*s %s %s at %.*s(%td:%td)\n", LIT(prefix), LIT(prefix_sep), LIT(name), sep, pt, LIT(pos.file), pos.line, pos.column);
  3801. }
  3802. if (procs.count > 0) {
  3803. gb_printf_err("\n");
  3804. }
  3805. }
  3806. result_type = t_invalid;
  3807. } else if (valid_count > 1) {
  3808. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  3809. gb_printf_err("\tGiven argument types: (");
  3810. for_array(i, operands) {
  3811. Operand o = operands[i];
  3812. if (i > 0) gb_printf_err(", ");
  3813. gbString type = type_to_string(o.type);
  3814. defer (gb_string_free(type));
  3815. gb_printf_err("%s", type);
  3816. }
  3817. gb_printf_err(")\n");
  3818. for (isize i = 0; i < valid_count; i++) {
  3819. Entity *proc = procs[valids[i].index];
  3820. TokenPos pos = proc->token.pos;
  3821. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  3822. gbString pt;
  3823. defer (gb_string_free(pt));
  3824. if (t->Proc.node != nullptr) {
  3825. pt = expr_to_string(t->Proc.node);
  3826. } else {
  3827. pt = type_to_string(t);
  3828. }
  3829. String name = proc->token.string;
  3830. char const *sep = "::";
  3831. if (proc->kind == Entity_Variable) {
  3832. sep = ":=";
  3833. }
  3834. gb_printf_err("\t%.*s %s %s at %.*s(%td:%td)\n", LIT(name), sep, pt, LIT(pos.file), pos.line, pos.column);
  3835. }
  3836. result_type = t_invalid;
  3837. } else {
  3838. Ast *ident = operand->expr;
  3839. while (ident->kind == Ast_SelectorExpr) {
  3840. Ast *s = ident->SelectorExpr.selector;
  3841. ident = s;
  3842. }
  3843. Entity *e = procs[valids[0].index];
  3844. proc_type = e->type;
  3845. CallArgumentData data = {};
  3846. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  3847. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  3848. add_entity_use(c, ident, entity_to_use);
  3849. return data;
  3850. }
  3851. } else {
  3852. Ast *ident = operand->expr;
  3853. while (ident->kind == Ast_SelectorExpr) {
  3854. Ast *s = ident->SelectorExpr.selector;
  3855. ident = s;
  3856. }
  3857. Entity *e = entity_of_ident(ident);
  3858. CallArgumentData data = {};
  3859. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  3860. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  3861. add_entity_use(c, ident, entity_to_use);
  3862. return data;
  3863. }
  3864. CallArgumentData data = {};
  3865. data.result_type = t_invalid;
  3866. return data;
  3867. }
  3868. isize lookup_polymorphic_struct_parameter(TypeStruct *st, String parameter_name) {
  3869. if (!st->is_polymorphic) return -1;
  3870. TypeTuple *params = &st->polymorphic_params->Tuple;
  3871. for_array(i, params->variables) {
  3872. Entity *e = params->variables[i];
  3873. String name = e->token.string;
  3874. if (is_blank_ident(name)) {
  3875. continue;
  3876. }
  3877. if (name == parameter_name) {
  3878. return i;
  3879. }
  3880. }
  3881. return -1;
  3882. }
  3883. CallArgumentError check_polymorphic_struct_type(CheckerContext *c, Operand *operand, Ast *call) {
  3884. ast_node(ce, CallExpr, call);
  3885. Type *original_type = operand->type;
  3886. Type *struct_type = base_type(operand->type);
  3887. GB_ASSERT(struct_type->kind == Type_Struct);
  3888. TypeStruct *st = &struct_type->Struct;
  3889. GB_ASSERT(st->is_polymorphic);
  3890. bool show_error = true;
  3891. Array<Operand> operands = {};
  3892. defer (array_free(&operands));
  3893. bool named_fields = false;
  3894. if (is_call_expr_field_value(ce)) {
  3895. named_fields = true;
  3896. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  3897. for_array(i, ce->args) {
  3898. Ast *arg = ce->args[i];
  3899. ast_node(fv, FieldValue, arg);
  3900. check_expr_or_type(c, &operands[i], fv->value);
  3901. }
  3902. bool vari_expand = (ce->ellipsis.pos.line != 0);
  3903. if (vari_expand) {
  3904. error(ce->ellipsis, "Invalid use of '...' in a polymorphic type call'");
  3905. }
  3906. } else {
  3907. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  3908. check_unpack_arguments(c, nullptr, -1, &operands, ce->args, false);
  3909. }
  3910. CallArgumentError err = CallArgumentError_None;
  3911. TypeTuple *tuple = &st->polymorphic_params->Tuple;
  3912. isize param_count = tuple->variables.count;
  3913. Array<Operand> ordered_operands = operands;
  3914. if (named_fields) {
  3915. bool *visited = gb_alloc_array(c->allocator, bool, param_count);
  3916. // LEAK(bill)
  3917. ordered_operands = array_make<Operand>(c->allocator, param_count);
  3918. for_array(i, ce->args) {
  3919. Ast *arg = ce->args[i];
  3920. ast_node(fv, FieldValue, arg);
  3921. if (fv->field->kind != Ast_Ident) {
  3922. if (show_error) {
  3923. gbString expr_str = expr_to_string(fv->field);
  3924. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  3925. gb_string_free(expr_str);
  3926. }
  3927. err = CallArgumentError_InvalidFieldValue;
  3928. continue;
  3929. }
  3930. String name = fv->field->Ident.token.string;
  3931. isize index = lookup_polymorphic_struct_parameter(st, name);
  3932. if (index < 0) {
  3933. if (show_error) {
  3934. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  3935. }
  3936. err = CallArgumentError_ParameterNotFound;
  3937. continue;
  3938. }
  3939. if (visited[index]) {
  3940. if (show_error) {
  3941. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  3942. }
  3943. err = CallArgumentError_DuplicateParameter;
  3944. continue;
  3945. }
  3946. visited[index] = true;
  3947. ordered_operands[index] = operands[i];
  3948. }
  3949. for (isize i = 0; i < param_count; i++) {
  3950. if (!visited[i]) {
  3951. Entity *e = tuple->variables[i];
  3952. if (is_blank_ident(e->token)) {
  3953. continue;
  3954. }
  3955. if (show_error) {
  3956. if (e->kind == Entity_TypeName) {
  3957. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  3958. LIT(e->token.string));
  3959. } else {
  3960. gbString str = type_to_string(e->type);
  3961. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  3962. LIT(e->token.string), str);
  3963. gb_string_free(str);
  3964. }
  3965. }
  3966. err = CallArgumentError_ParameterMissing;
  3967. }
  3968. }
  3969. }
  3970. if (err != 0) {
  3971. operand->mode = Addressing_Invalid;
  3972. return err;
  3973. }
  3974. i64 score = 0;
  3975. for (isize i = 0; i < param_count; i++) {
  3976. Operand *o = &ordered_operands[i];
  3977. if (o->mode == Addressing_Invalid) {
  3978. continue;
  3979. }
  3980. Entity *e = tuple->variables[i];
  3981. if (e->kind == Entity_TypeName) {
  3982. if (o->mode != Addressing_Type) {
  3983. if (show_error) {
  3984. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  3985. }
  3986. err = CallArgumentError_WrongTypes;
  3987. }
  3988. if (are_types_identical(e->type, o->type)) {
  3989. score += assign_score_function(1);
  3990. } else {
  3991. score += assign_score_function(10);
  3992. }
  3993. } else {
  3994. i64 s = 0;
  3995. if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  3996. if (show_error) {
  3997. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  3998. }
  3999. err = CallArgumentError_WrongTypes;
  4000. }
  4001. o->type = e->type;
  4002. if (o->mode != Addressing_Constant) {
  4003. if (show_error) {
  4004. error(o->expr, "Expected a constant value for this polymorphic type argument");
  4005. }
  4006. err = CallArgumentError_NoneConstantParameter;
  4007. }
  4008. score += s;
  4009. }
  4010. }
  4011. if (param_count < ordered_operands.count) {
  4012. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  4013. err = CallArgumentError_TooManyArguments;
  4014. } else if (param_count > ordered_operands.count) {
  4015. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  4016. err = CallArgumentError_TooFewArguments;
  4017. }
  4018. if (err != 0) {
  4019. return err;
  4020. }
  4021. {
  4022. // TODO(bill): Check for previous types
  4023. gbAllocator a = c->allocator;
  4024. Entity *found_entity = find_polymorphic_struct_entity(c, original_type, param_count, ordered_operands);
  4025. if (found_entity) {
  4026. operand->mode = Addressing_Type;
  4027. operand->type = found_entity->type;
  4028. return err;
  4029. }
  4030. String generated_name = make_string_c(expr_to_string(call));
  4031. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  4032. Ast *node = clone_ast(st->node);
  4033. Type *struct_type = alloc_type_struct();
  4034. struct_type->Struct.node = node;
  4035. struct_type->Struct.polymorphic_parent = original_type;
  4036. set_base_type(named_type, struct_type);
  4037. check_open_scope(c, node);
  4038. check_struct_type(c, struct_type, node, &ordered_operands, named_type, original_type);
  4039. check_close_scope(c);
  4040. operand->mode = Addressing_Type;
  4041. operand->type = named_type;
  4042. }
  4043. return err;
  4044. }
  4045. ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call) {
  4046. ast_node(ce, CallExpr, call);
  4047. if (ce->proc != nullptr &&
  4048. ce->proc->kind == Ast_BasicDirective) {
  4049. ast_node(bd, BasicDirective, ce->proc);
  4050. String name = bd->name;
  4051. if (name == "location" || name == "assert") {
  4052. operand->mode = Addressing_Builtin;
  4053. operand->builtin_id = BuiltinProc_DIRECTIVE;
  4054. operand->expr = ce->proc;
  4055. operand->type = t_invalid;
  4056. add_type_and_value(&c->checker->info, ce->proc, operand->mode, operand->type, operand->value);
  4057. } else {
  4058. GB_PANIC("Unhandled #%.*s", LIT(name));
  4059. }
  4060. } else {
  4061. check_expr_or_type(c, operand, ce->proc);
  4062. }
  4063. if (ce->args.count > 0) {
  4064. bool fail = false;
  4065. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  4066. for_array(i, ce->args) {
  4067. Ast *arg = ce->args[i];
  4068. bool mix = false;
  4069. if (first_is_field_value) {
  4070. mix = arg->kind != Ast_FieldValue;
  4071. } else {
  4072. mix = arg->kind == Ast_FieldValue;
  4073. }
  4074. if (mix) {
  4075. error(arg, "Mixture of 'field = value' and value elements in a procedure all is not allowed");
  4076. fail = true;
  4077. }
  4078. }
  4079. if (fail) {
  4080. operand->mode = Addressing_Invalid;
  4081. operand->expr = call;
  4082. return Expr_Stmt;
  4083. }
  4084. }
  4085. if (operand->mode == Addressing_Invalid) {
  4086. for_array(i, ce->args) {
  4087. Ast *arg = ce->args[i];
  4088. if (arg->kind == Ast_FieldValue) {
  4089. arg = arg->FieldValue.value;
  4090. }
  4091. check_expr_base(c, operand, arg, nullptr);
  4092. }
  4093. operand->mode = Addressing_Invalid;
  4094. operand->expr = call;
  4095. return Expr_Stmt;
  4096. }
  4097. if (operand->mode == Addressing_Type) {
  4098. Type *t = operand->type;
  4099. if (is_type_polymorphic_struct(t)) {
  4100. auto err = check_polymorphic_struct_type(c, operand, call);
  4101. if (err == 0) {
  4102. Ast *ident = operand->expr;
  4103. while (ident->kind == Ast_SelectorExpr) {
  4104. Ast *s = ident->SelectorExpr.selector;
  4105. ident = s;
  4106. }
  4107. Type *ot = operand->type; GB_ASSERT(ot->kind == Type_Named);
  4108. Entity *e = ot->Named.type_name;
  4109. add_entity_use(c, ident, e);
  4110. add_type_and_value(&c->checker->info, call, Addressing_Type, ot, empty_exact_value);
  4111. } else {
  4112. operand->mode = Addressing_Invalid;
  4113. operand->type = t_invalid;
  4114. }
  4115. } else {
  4116. gbString str = type_to_string(t);
  4117. defer (gb_string_free(str));
  4118. operand->mode = Addressing_Invalid;
  4119. isize arg_count = ce->args.count;
  4120. switch (arg_count) {
  4121. case 0: error(call, "Missing argument in conversion to '%s'", str); break;
  4122. default: error(call, "Too many arguments in conversion to '%s'", str); break;
  4123. case 1: {
  4124. Ast *arg = ce->args[0];
  4125. if (arg->kind == Ast_FieldValue) {
  4126. error(call, "'field = value' cannot be used in a type conversion");
  4127. arg = arg->FieldValue.value;
  4128. // NOTE(bill): Carry on the cast regardless
  4129. }
  4130. check_expr(c, operand, arg);
  4131. if (operand->mode != Addressing_Invalid) {
  4132. check_cast(c, operand, t);
  4133. }
  4134. break;
  4135. }
  4136. }
  4137. }
  4138. return Expr_Expr;
  4139. }
  4140. if (operand->mode == Addressing_Builtin) {
  4141. i32 id = operand->builtin_id;
  4142. if (!check_builtin_procedure(c, operand, call, id)) {
  4143. operand->mode = Addressing_Invalid;
  4144. }
  4145. operand->expr = call;
  4146. return builtin_procs[id].kind;
  4147. }
  4148. Type *proc_type = base_type(operand->type);
  4149. if (operand->mode != Addressing_ProcGroup) {
  4150. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  4151. bool valid_mode = is_operand_value(*operand);
  4152. if (!valid_type || !valid_mode) {
  4153. Ast *e = operand->expr;
  4154. gbString str = expr_to_string(e);
  4155. gbString type_str = type_to_string(operand->type);
  4156. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  4157. gb_string_free(type_str);
  4158. gb_string_free(str);
  4159. operand->mode = Addressing_Invalid;
  4160. operand->expr = call;
  4161. return Expr_Stmt;
  4162. }
  4163. }
  4164. // NOTE(bill): Should this be here or on the `add_entity_use`?
  4165. // if (ce->proc != nullptr) {
  4166. // Entity *e = entity_of_node(&c->info, ce->proc);
  4167. // if (e != nullptr && e->kind == Entity_Procedure) {
  4168. // String msg = e->Procedure.deprecated_message;
  4169. // if (msg.len > 0) {
  4170. // warning(call, "%.*s is deprecated: %.*s", LIT(e->token.string), LIT(msg));
  4171. // }
  4172. // }
  4173. // }
  4174. CallArgumentData data = check_call_arguments(c, operand, proc_type, call);
  4175. Type *result_type = data.result_type;
  4176. gb_zero_item(operand);
  4177. operand->expr = call;
  4178. if (result_type == t_invalid) {
  4179. operand->mode = Addressing_Invalid;
  4180. operand->type = t_invalid;
  4181. return Expr_Stmt;
  4182. }
  4183. Type *pt = base_type(proc_type);
  4184. if (result_type == nullptr) {
  4185. operand->mode = Addressing_NoValue;
  4186. } else {
  4187. GB_ASSERT(is_type_tuple(result_type));
  4188. switch (result_type->Tuple.variables.count) {
  4189. case 0:
  4190. operand->mode = Addressing_NoValue;
  4191. break;
  4192. case 1:
  4193. operand->mode = Addressing_Value;
  4194. operand->type = result_type->Tuple.variables[0]->type;
  4195. break;
  4196. default:
  4197. operand->mode = Addressing_Value;
  4198. operand->type = result_type;
  4199. break;
  4200. }
  4201. }
  4202. operand->expr = call;
  4203. return Expr_Expr;
  4204. }
  4205. void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  4206. check_expr_base(c, o, e, t);
  4207. check_not_tuple(c, o);
  4208. char *err_str = nullptr;
  4209. switch (o->mode) {
  4210. case Addressing_NoValue:
  4211. err_str = "used as a value";
  4212. break;
  4213. case Addressing_Type:
  4214. err_str = "is not an expression";
  4215. break;
  4216. case Addressing_Builtin:
  4217. err_str = "must be called";
  4218. break;
  4219. }
  4220. if (err_str != nullptr) {
  4221. gbString str = expr_to_string(e);
  4222. error(e, "'%s' %s", str, err_str);
  4223. gb_string_free(str);
  4224. o->mode = Addressing_Invalid;
  4225. }
  4226. }
  4227. void check_set_mode_with_indirection(Operand *o, bool indirection) {
  4228. if (o->mode != Addressing_Immutable) {
  4229. if (indirection) {
  4230. o->mode = Addressing_Variable;
  4231. } else if (o->mode != Addressing_Variable &&
  4232. o->mode != Addressing_Constant) {
  4233. o->mode = Addressing_Value;
  4234. }
  4235. }
  4236. }
  4237. bool check_set_index_data(Operand *o, Type *type, bool indirection, i64 *max_count) {
  4238. Type *t = base_type(type_deref(type));
  4239. switch (t->kind) {
  4240. case Type_Basic:
  4241. if (t->Basic.kind == Basic_string) {
  4242. if (o->mode == Addressing_Constant) {
  4243. *max_count = o->value.value_string.len;
  4244. }
  4245. check_set_mode_with_indirection(o, indirection);
  4246. o->type = t_u8;
  4247. return true;
  4248. }
  4249. break;
  4250. case Type_Array:
  4251. *max_count = t->Array.count;
  4252. check_set_mode_with_indirection(o, indirection);
  4253. o->type = t->Array.elem;
  4254. return true;
  4255. case Type_Slice:
  4256. o->type = t->Slice.elem;
  4257. if (o->mode != Addressing_Immutable) {
  4258. o->mode = Addressing_Variable;
  4259. }
  4260. return true;
  4261. case Type_DynamicArray:
  4262. o->type = t->DynamicArray.elem;
  4263. check_set_mode_with_indirection(o, indirection);
  4264. return true;
  4265. }
  4266. return false;
  4267. }
  4268. bool ternary_compare_types(Type *x, Type *y) {
  4269. if (is_type_untyped_undef(x) && type_has_undef(y)) {
  4270. return true;
  4271. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  4272. return true;
  4273. } else if (is_type_untyped_undef(y) && type_has_undef(x)) {
  4274. return true;
  4275. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  4276. return true;
  4277. }
  4278. return are_types_identical(x, y);
  4279. }
  4280. ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  4281. ExprKind kind = Expr_Stmt;
  4282. o->mode = Addressing_Invalid;
  4283. o->type = t_invalid;
  4284. switch (node->kind) {
  4285. default:
  4286. return kind;
  4287. case_ast_node(be, BadExpr, node)
  4288. return kind;
  4289. case_end;
  4290. case_ast_node(i, Implicit, node)
  4291. switch (i->kind) {
  4292. case Token_context:
  4293. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  4294. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  4295. return kind;
  4296. }
  4297. init_core_context(c->checker);
  4298. o->mode = Addressing_Context;
  4299. o->type = t_context;
  4300. break;
  4301. case Token_size_of:
  4302. o->mode = Addressing_Builtin;
  4303. o->builtin_id = BuiltinProc_size_of;
  4304. break;
  4305. case Token_align_of:
  4306. o->mode = Addressing_Builtin;
  4307. o->builtin_id = BuiltinProc_align_of;
  4308. break;
  4309. case Token_offset_of:
  4310. o->mode = Addressing_Builtin;
  4311. o->builtin_id = BuiltinProc_offset_of;
  4312. break;
  4313. case Token_type_of:
  4314. o->mode = Addressing_Builtin;
  4315. o->builtin_id = BuiltinProc_type_of;
  4316. break;
  4317. default:
  4318. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  4319. return kind;
  4320. }
  4321. case_end;
  4322. case_ast_node(i, Ident, node);
  4323. check_ident(c, o, node, nullptr, type_hint, false);
  4324. case_end;
  4325. case_ast_node(u, Undef, node);
  4326. o->mode = Addressing_Value;
  4327. o->type = t_untyped_undef;
  4328. case_end;
  4329. case_ast_node(bl, BasicLit, node);
  4330. // NOTE(bill, 2018-06-17): Placing this in the parser is slower than
  4331. // placing it here for some reason. So don't move it to the parsing
  4332. // stage if you _think_ it will be faster, only do it if you _know_ it
  4333. // will be faster.
  4334. Type *t = t_invalid;
  4335. switch (bl->token.kind) {
  4336. case Token_Integer: t = t_untyped_integer; break;
  4337. case Token_Float: t = t_untyped_float; break;
  4338. case Token_String: t = t_untyped_string; break;
  4339. case Token_Rune: t = t_untyped_rune; break;
  4340. case Token_Imag: {
  4341. String s = bl->token.string;
  4342. Rune r = s[s.len-1];
  4343. switch (r) {
  4344. case 'i': t = t_untyped_complex; break;
  4345. }
  4346. break;
  4347. }
  4348. default:
  4349. GB_PANIC("Unknown literal");
  4350. break;
  4351. }
  4352. o->mode = Addressing_Constant;
  4353. o->type = t;
  4354. o->value = exact_value_from_basic_literal(bl->token);
  4355. case_end;
  4356. case_ast_node(bd, BasicDirective, node);
  4357. o->mode = Addressing_Constant;
  4358. if (bd->name == "file") {
  4359. o->type = t_untyped_string;
  4360. o->value = exact_value_string(bd->token.pos.file);
  4361. } else if (bd->name == "line") {
  4362. o->type = t_untyped_integer;
  4363. o->value = exact_value_i64(bd->token.pos.line);
  4364. } else if (bd->name == "procedure") {
  4365. if (c->curr_proc_decl == nullptr) {
  4366. error(node, "#procedure may only be used within procedures");
  4367. o->type = t_untyped_string;
  4368. o->value = exact_value_string(str_lit(""));
  4369. } else {
  4370. o->type = t_untyped_string;
  4371. o->value = exact_value_string(c->proc_name);
  4372. }
  4373. } else if (bd->name == "caller_location") {
  4374. init_core_source_code_location(c->checker);
  4375. error(node, "#caller_location may only be used as a default argument parameter");
  4376. o->type = t_source_code_location;
  4377. o->mode = Addressing_Value;
  4378. } else {
  4379. GB_PANIC("Unknown basic directive");
  4380. }
  4381. case_end;
  4382. case_ast_node(pg, ProcGroup, node);
  4383. error(node, "Illegal use of a procedure group");
  4384. o->mode = Addressing_Invalid;
  4385. case_end;
  4386. case_ast_node(pl, ProcLit, node);
  4387. CheckerContext ctx = *c;
  4388. DeclInfo *decl = nullptr;
  4389. Type *type = alloc_type(Type_Proc);
  4390. check_open_scope(&ctx, pl->type);
  4391. {
  4392. decl = make_decl_info(ctx.allocator, ctx.scope, ctx.decl);
  4393. decl->proc_lit = node;
  4394. ctx.decl = decl;
  4395. if (pl->tags != 0) {
  4396. error(node, "A procedure literal cannot have tags");
  4397. pl->tags = 0; // TODO(bill): Should I zero this?!
  4398. }
  4399. check_procedure_type(&ctx, type, pl->type);
  4400. if (!is_type_proc(type)) {
  4401. gbString str = expr_to_string(node);
  4402. error(node, "Invalid procedure literal '%s'", str);
  4403. gb_string_free(str);
  4404. check_close_scope(&ctx);
  4405. return kind;
  4406. }
  4407. if (pl->body == nullptr) {
  4408. error(node, "A procedure literal must have a body");
  4409. return kind;
  4410. }
  4411. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  4412. }
  4413. check_close_scope(&ctx);
  4414. o->mode = Addressing_Value;
  4415. o->type = type;
  4416. case_end;
  4417. case_ast_node(te, TernaryExpr, node);
  4418. Operand cond = {Addressing_Invalid};
  4419. check_expr(c, &cond, te->cond);
  4420. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  4421. error(te->cond, "Non-boolean condition in if expression");
  4422. }
  4423. Operand x = {Addressing_Invalid};
  4424. Operand y = {Addressing_Invalid};
  4425. check_expr_or_type(c, &x, te->x, type_hint);
  4426. if (te->y != nullptr) {
  4427. check_expr_or_type(c, &y, te->y, type_hint);
  4428. } else {
  4429. error(node, "A ternary expression must have an else clause");
  4430. return kind;
  4431. }
  4432. if (x.type == nullptr || x.type == t_invalid ||
  4433. y.type == nullptr || y.type == t_invalid) {
  4434. return kind;
  4435. }
  4436. if (x.mode == Addressing_Type && y.mode == Addressing_Type &&
  4437. cond.mode == Addressing_Constant && is_type_boolean(cond.type)) {
  4438. o->mode = Addressing_Type;
  4439. if (cond.value.value_bool) {
  4440. o->type = x.type;
  4441. o->expr = x.expr;
  4442. } else {
  4443. o->type = y.type;
  4444. o->expr = y.expr;
  4445. }
  4446. return Expr_Expr;
  4447. }
  4448. convert_to_typed(c, &x, y.type);
  4449. if (x.mode == Addressing_Invalid) {
  4450. return kind;
  4451. }
  4452. convert_to_typed(c, &y, x.type);
  4453. if (y.mode == Addressing_Invalid) {
  4454. x.mode = Addressing_Invalid;
  4455. return kind;
  4456. }
  4457. if (!ternary_compare_types(x.type, y.type)) {
  4458. gbString its = type_to_string(x.type);
  4459. gbString ets = type_to_string(y.type);
  4460. error(node, "Mismatched types in ternary expression, %s vs %s", its, ets);
  4461. gb_string_free(ets);
  4462. gb_string_free(its);
  4463. return kind;
  4464. }
  4465. Type *type = x.type;
  4466. if (is_type_untyped_nil(type) || is_type_untyped_undef(type)) {
  4467. type = y.type;
  4468. }
  4469. o->type = type;
  4470. o->mode = Addressing_Value;
  4471. if (cond.mode == Addressing_Constant && is_type_boolean(cond.type) &&
  4472. x.mode == Addressing_Constant &&
  4473. y.mode == Addressing_Constant) {
  4474. o->mode = Addressing_Constant;
  4475. if (cond.value.value_bool) {
  4476. o->value = x.value;
  4477. } else {
  4478. o->value = y.value;
  4479. }
  4480. }
  4481. case_end;
  4482. case_ast_node(cl, CompoundLit, node);
  4483. Type *type = type_hint;
  4484. bool is_to_be_determined_array_count = false;
  4485. bool is_constant = true;
  4486. if (cl->type != nullptr) {
  4487. type = nullptr;
  4488. // [?]Type
  4489. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  4490. Ast *count = cl->type->ArrayType.count;
  4491. if (count->kind == Ast_UnaryExpr &&
  4492. count->UnaryExpr.op.kind == Token_Question) {
  4493. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  4494. is_to_be_determined_array_count = true;
  4495. }
  4496. }
  4497. if (type == nullptr) {
  4498. type = check_type(c, cl->type);
  4499. }
  4500. }
  4501. if (type == nullptr) {
  4502. error(node, "Missing type in compound literal");
  4503. return kind;
  4504. }
  4505. Type *t = base_type(type);
  4506. if (is_type_polymorphic(t)) {
  4507. gbString str = type_to_string(type);
  4508. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  4509. o->expr = node;
  4510. o->type = type;
  4511. gb_string_free(str);
  4512. return kind;
  4513. }
  4514. switch (t->kind) {
  4515. case Type_Struct: {
  4516. if (cl->elems.count == 0) {
  4517. break; // NOTE(bill): No need to init
  4518. }
  4519. if (!is_type_struct(t)) {
  4520. if (cl->elems.count != 0) {
  4521. gbString type_str = type_to_string(type);
  4522. error(node, "Illegal compound literal type '%s'", type_str);
  4523. gb_string_free(type_str);
  4524. }
  4525. break;
  4526. }
  4527. if (is_type_struct(t)) { // Checker values
  4528. isize field_count = t->Struct.fields.count;
  4529. isize min_field_count = t->Struct.fields.count;
  4530. for (isize i = min_field_count-1; i >= 0; i--) {
  4531. Entity *e = t->Struct.fields[i];
  4532. GB_ASSERT(e->kind == Entity_Variable);
  4533. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4534. min_field_count--;
  4535. } else {
  4536. break;
  4537. }
  4538. }
  4539. if (cl->elems[0]->kind == Ast_FieldValue) {
  4540. bool *fields_visited = gb_alloc_array(c->allocator, bool, field_count);
  4541. for_array(i, cl->elems) {
  4542. Ast *elem = cl->elems[i];
  4543. if (elem->kind != Ast_FieldValue) {
  4544. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  4545. continue;
  4546. }
  4547. ast_node(fv, FieldValue, elem);
  4548. if (fv->field->kind != Ast_Ident) {
  4549. gbString expr_str = expr_to_string(fv->field);
  4550. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  4551. gb_string_free(expr_str);
  4552. continue;
  4553. }
  4554. String name = fv->field->Ident.token.string;
  4555. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  4556. bool is_unknown = sel.entity == nullptr;
  4557. if (is_unknown) {
  4558. error(elem, "Unknown field '%.*s' in structure literal", LIT(name));
  4559. continue;
  4560. }
  4561. if (sel.index.count > 1) {
  4562. error(elem, "Cannot assign to an anonymous field '%.*s' in a structure literal (at the moment)", LIT(name));
  4563. continue;
  4564. }
  4565. Entity *field = t->Struct.fields[sel.index[0]];
  4566. add_entity_use(c, fv->field, field);
  4567. if (fields_visited[sel.index[0]]) {
  4568. error(elem, "Duplicate field '%.*s' in structure literal", LIT(name));
  4569. continue;
  4570. }
  4571. fields_visited[sel.index[0]] = true;
  4572. check_expr_with_type_hint(c, o, fv->value, field->type);
  4573. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type)) {
  4574. is_constant = false;
  4575. }
  4576. if (is_constant) {
  4577. is_constant = o->mode == Addressing_Constant;
  4578. }
  4579. check_assignment(c, o, field->type, str_lit("structure literal"));
  4580. }
  4581. } else {
  4582. bool seen_field_value = false;
  4583. for_array(index, cl->elems) {
  4584. Entity *field = nullptr;
  4585. Ast *elem = cl->elems[index];
  4586. if (elem->kind == Ast_FieldValue) {
  4587. seen_field_value = true;
  4588. // error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  4589. // continue;
  4590. } else if (seen_field_value) {
  4591. error(elem, "Value elements cannot be used after a 'field = value'");
  4592. continue;
  4593. }
  4594. if (index >= field_count) {
  4595. error(o->expr, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  4596. break;
  4597. }
  4598. if (field == nullptr) {
  4599. field = t->Struct.fields[index];
  4600. }
  4601. check_expr_with_type_hint(c, o, elem, field->type);
  4602. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type)) {
  4603. is_constant = false;
  4604. }
  4605. if (is_constant) {
  4606. is_constant = o->mode == Addressing_Constant;
  4607. }
  4608. check_assignment(c, o, field->type, str_lit("structure literal"));
  4609. }
  4610. if (cl->elems.count < field_count) {
  4611. if (min_field_count < field_count) {
  4612. if (cl->elems.count < min_field_count) {
  4613. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  4614. }
  4615. } else {
  4616. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  4617. }
  4618. }
  4619. }
  4620. }
  4621. break;
  4622. }
  4623. case Type_Slice:
  4624. case Type_Array:
  4625. case Type_DynamicArray:
  4626. {
  4627. Type *elem_type = nullptr;
  4628. String context_name = {};
  4629. i64 max_type_count = -1;
  4630. if (t->kind == Type_Slice) {
  4631. elem_type = t->Slice.elem;
  4632. context_name = str_lit("slice literal");
  4633. } else if (t->kind == Type_Array) {
  4634. elem_type = t->Array.elem;
  4635. context_name = str_lit("array literal");
  4636. if (!is_to_be_determined_array_count) {
  4637. max_type_count = t->Array.count;
  4638. }
  4639. } else if (t->kind == Type_DynamicArray) {
  4640. elem_type = t->DynamicArray.elem;
  4641. context_name = str_lit("dynamic array literal");
  4642. is_constant = false;
  4643. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  4644. add_package_dependency(c, "runtime", "__dynamic_array_append");
  4645. } else {
  4646. GB_PANIC("unreachable");
  4647. }
  4648. i64 max = 0;
  4649. isize index = 0;
  4650. Type *bet = base_type(elem_type);
  4651. if (!elem_type_can_be_constant(bet)) {
  4652. is_constant = false;
  4653. }
  4654. if (bet == t_invalid) {
  4655. break;
  4656. }
  4657. for (; index < cl->elems.count; index++) {
  4658. Ast *e = cl->elems[index];
  4659. if (e == nullptr) {
  4660. error(node, "Invalid literal element");
  4661. continue;
  4662. }
  4663. if (e->kind == Ast_FieldValue) {
  4664. error(e, "'field = value' is only allowed in struct literals");
  4665. continue;
  4666. }
  4667. if (0 <= max_type_count && max_type_count <= index) {
  4668. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  4669. }
  4670. Operand operand = {};
  4671. check_expr_with_type_hint(c, &operand, e, elem_type);
  4672. check_assignment(c, &operand, elem_type, context_name);
  4673. is_constant = is_constant && operand.mode == Addressing_Constant;
  4674. }
  4675. if (max < index) {
  4676. max = index;
  4677. }
  4678. if (t->kind == Type_Array) {
  4679. if (is_to_be_determined_array_count) {
  4680. t->Array.count = max;
  4681. } else if (0 < max && max < t->Array.count) {
  4682. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  4683. }
  4684. }
  4685. break;
  4686. }
  4687. case Type_Basic: {
  4688. if (!is_type_any(t)) {
  4689. if (cl->elems.count != 0) {
  4690. error(node, "Illegal compound literal");
  4691. }
  4692. break;
  4693. }
  4694. if (cl->elems.count == 0) {
  4695. break; // NOTE(bill): No need to init
  4696. }
  4697. { // Checker values
  4698. Type *field_types[2] = {t_rawptr, t_typeid};
  4699. isize field_count = 2;
  4700. if (cl->elems[0]->kind == Ast_FieldValue) {
  4701. bool fields_visited[2] = {};
  4702. for_array(i, cl->elems) {
  4703. Ast *elem = cl->elems[i];
  4704. if (elem->kind != Ast_FieldValue) {
  4705. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  4706. continue;
  4707. }
  4708. ast_node(fv, FieldValue, elem);
  4709. if (fv->field->kind != Ast_Ident) {
  4710. gbString expr_str = expr_to_string(fv->field);
  4711. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  4712. gb_string_free(expr_str);
  4713. continue;
  4714. }
  4715. String name = fv->field->Ident.token.string;
  4716. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  4717. if (sel.entity == nullptr) {
  4718. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  4719. continue;
  4720. }
  4721. isize index = sel.index[0];
  4722. if (fields_visited[index]) {
  4723. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  4724. continue;
  4725. }
  4726. fields_visited[index] = true;
  4727. check_expr(c, o, fv->value);
  4728. // NOTE(bill): 'any' literals can never be constant
  4729. is_constant = false;
  4730. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  4731. }
  4732. } else {
  4733. for_array(index, cl->elems) {
  4734. Ast *elem = cl->elems[index];
  4735. if (elem->kind == Ast_FieldValue) {
  4736. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  4737. continue;
  4738. }
  4739. check_expr(c, o, elem);
  4740. if (index >= field_count) {
  4741. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  4742. break;
  4743. }
  4744. // NOTE(bill): 'any' literals can never be constant
  4745. is_constant = false;
  4746. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  4747. }
  4748. if (cl->elems.count < field_count) {
  4749. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  4750. }
  4751. }
  4752. }
  4753. break;
  4754. }
  4755. case Type_Map: {
  4756. if (cl->elems.count == 0) {
  4757. break;
  4758. }
  4759. is_constant = false;
  4760. { // Checker values
  4761. for_array(i, cl->elems) {
  4762. Ast *elem = cl->elems[i];
  4763. if (elem->kind != Ast_FieldValue) {
  4764. error(elem, "Only 'field = value' elements are allowed in a map literal");
  4765. continue;
  4766. }
  4767. ast_node(fv, FieldValue, elem);
  4768. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  4769. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  4770. if (o->mode == Addressing_Invalid) {
  4771. continue;
  4772. }
  4773. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  4774. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  4775. }
  4776. }
  4777. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  4778. add_package_dependency(c, "runtime", "__dynamic_map_set");
  4779. break;
  4780. }
  4781. case Type_BitSet: {
  4782. if (cl->elems.count == 0) {
  4783. break; // NOTE(bill): No need to init
  4784. }
  4785. Type *et = base_type(t->BitSet.base_type);
  4786. isize field_count = 0;
  4787. if (et->kind == Type_Enum) {
  4788. field_count = et->Enum.fields.count;
  4789. }
  4790. if (cl->elems[0]->kind == Ast_FieldValue) {
  4791. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  4792. is_constant = false;
  4793. } else {
  4794. for_array(index, cl->elems) {
  4795. Entity *field = nullptr;
  4796. Ast *elem = cl->elems[index];
  4797. if (elem->kind == Ast_FieldValue) {
  4798. error(elem, "'field = value' in a bit_set a literal is not allowed");
  4799. continue;
  4800. }
  4801. check_expr(c, o, elem);
  4802. if (is_constant) {
  4803. is_constant = o->mode == Addressing_Constant;
  4804. }
  4805. check_assignment(c, o, t->BitSet.base_type, str_lit("bit_set literal"));
  4806. }
  4807. }
  4808. break;
  4809. }
  4810. default: {
  4811. if (cl->elems.count == 0) {
  4812. break; // NOTE(bill): No need to init
  4813. }
  4814. gbString str = type_to_string(type);
  4815. error(node, "Invalid compound literal type '%s'", str);
  4816. gb_string_free(str);
  4817. return kind;
  4818. }
  4819. }
  4820. if (is_constant) {
  4821. o->mode = Addressing_Constant;
  4822. if (is_type_bit_set(type)) {
  4823. // NOTE(bill): Encode as an integer
  4824. i64 lower = base_type(type)->BitSet.min;
  4825. u64 bits = 0;
  4826. for_array(index, cl->elems) {
  4827. Entity *field = nullptr;
  4828. Ast *elem = cl->elems[index];
  4829. GB_ASSERT(elem->kind != Ast_FieldValue);
  4830. TypeAndValue tav = elem->tav;
  4831. ExactValue i = exact_value_to_integer(tav.value);
  4832. if (i.kind != ExactValue_Integer) {
  4833. continue;
  4834. }
  4835. i64 val = big_int_to_i64(&i.value_integer);
  4836. val -= lower;
  4837. u64 bit = u64(1ll<<val);
  4838. bits |= bit;
  4839. }
  4840. o->value = exact_value_u64(bits);
  4841. } else {
  4842. o->value = exact_value_compound(node);
  4843. }
  4844. } else {
  4845. o->mode = Addressing_Value;
  4846. }
  4847. o->type = type;
  4848. case_end;
  4849. case_ast_node(pe, ParenExpr, node);
  4850. kind = check_expr_base(c, o, pe->expr, type_hint);
  4851. o->expr = node;
  4852. case_end;
  4853. case_ast_node(te, TagExpr, node);
  4854. String name = te->name.string;
  4855. error(node, "Unknown tag expression, #%.*s", LIT(name));
  4856. if (te->expr) {
  4857. kind = check_expr_base(c, o, te->expr, type_hint);
  4858. }
  4859. o->expr = node;
  4860. case_end;
  4861. case_ast_node(re, RunExpr, node);
  4862. // TODO(bill): Tag expressions
  4863. kind = check_expr_base(c, o, re->expr, type_hint);
  4864. o->expr = node;
  4865. case_end;
  4866. case_ast_node(ta, TypeAssertion, node);
  4867. check_expr(c, o, ta->expr);
  4868. if (o->mode == Addressing_Invalid) {
  4869. o->expr = node;
  4870. return kind;
  4871. }
  4872. Type *t = check_type(c, ta->type);
  4873. if (o->mode == Addressing_Constant) {
  4874. gbString expr_str = expr_to_string(o->expr);
  4875. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  4876. gb_string_free(expr_str);
  4877. o->mode = Addressing_Invalid;
  4878. o->expr = node;
  4879. return kind;
  4880. }
  4881. if (is_type_untyped(o->type)) {
  4882. gbString expr_str = expr_to_string(o->expr);
  4883. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  4884. gb_string_free(expr_str);
  4885. o->mode = Addressing_Invalid;
  4886. o->expr = node;
  4887. return kind;
  4888. }
  4889. bool src_is_ptr = is_type_pointer(o->type);
  4890. Type *src = type_deref(o->type);
  4891. Type *dst = t;
  4892. Type *bsrc = base_type(src);
  4893. Type *bdst = base_type(dst);
  4894. if (is_type_union(src)) {
  4895. bool ok = false;
  4896. for_array(i, bsrc->Union.variants) {
  4897. Type *vt = bsrc->Union.variants[i];
  4898. if (are_types_identical(vt, dst)) {
  4899. ok = true;
  4900. break;
  4901. }
  4902. }
  4903. if (!ok) {
  4904. gbString expr_str = expr_to_string(o->expr);
  4905. gbString dst_type_str = type_to_string(t);
  4906. defer (gb_string_free(expr_str));
  4907. defer (gb_string_free(dst_type_str));
  4908. if (bsrc->Union.variants.count == 0) {
  4909. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  4910. } else {
  4911. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  4912. }
  4913. o->mode = Addressing_Invalid;
  4914. o->expr = node;
  4915. return kind;
  4916. }
  4917. add_type_info_type(c, o->type);
  4918. add_type_info_type(c, t);
  4919. o->type = t;
  4920. o->mode = Addressing_OptionalOk;
  4921. } else if (is_type_any(src)) {
  4922. o->type = t;
  4923. o->mode = Addressing_OptionalOk;
  4924. add_type_info_type(c, o->type);
  4925. add_type_info_type(c, t);
  4926. } else {
  4927. gbString str = type_to_string(o->type);
  4928. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  4929. gb_string_free(str);
  4930. o->mode = Addressing_Invalid;
  4931. o->expr = node;
  4932. return kind;
  4933. }
  4934. add_package_dependency(c, "runtime", "type_assertion_check");
  4935. case_end;
  4936. case_ast_node(tc, TypeCast, node);
  4937. check_expr_or_type(c, o, tc->type);
  4938. if (o->mode != Addressing_Type) {
  4939. gbString str = expr_to_string(tc->type);
  4940. error(tc->type, "Expected a type, got %s", str);
  4941. gb_string_free(str);
  4942. o->mode = Addressing_Invalid;
  4943. }
  4944. if (o->mode == Addressing_Invalid) {
  4945. o->expr = node;
  4946. return kind;
  4947. }
  4948. Type *type = o->type;
  4949. check_expr_base(c, o, tc->expr, type);
  4950. if (o->mode != Addressing_Invalid) {
  4951. switch (tc->token.kind) {
  4952. case Token_transmute:
  4953. check_transmute(c, node, o, type);
  4954. break;
  4955. case Token_cast:
  4956. check_cast(c, o, type);
  4957. break;
  4958. default:
  4959. error(node, "Invalid AST: Invalid casting expression");
  4960. o->mode = Addressing_Invalid;
  4961. break;
  4962. }
  4963. }
  4964. return Expr_Expr;
  4965. case_end;
  4966. case_ast_node(ac, AutoCast, node);
  4967. check_expr_base(c, o, ac->expr, type_hint);
  4968. if (o->mode == Addressing_Invalid) {
  4969. o->expr = node;
  4970. return kind;
  4971. }
  4972. if (type_hint) {
  4973. check_cast(c, o, type_hint);
  4974. }
  4975. o->expr = node;
  4976. return Expr_Expr;
  4977. case_end;
  4978. case_ast_node(ue, UnaryExpr, node);
  4979. check_expr_base(c, o, ue->expr, type_hint);
  4980. if (o->mode == Addressing_Invalid) {
  4981. o->expr = node;
  4982. return kind;
  4983. }
  4984. check_unary_expr(c, o, ue->op, node);
  4985. if (o->mode == Addressing_Invalid) {
  4986. o->expr = node;
  4987. return kind;
  4988. }
  4989. case_end;
  4990. case_ast_node(be, BinaryExpr, node);
  4991. check_binary_expr(c, o, node);
  4992. if (o->mode == Addressing_Invalid) {
  4993. o->expr = node;
  4994. return kind;
  4995. }
  4996. case_end;
  4997. case_ast_node(se, SelectorExpr, node);
  4998. check_selector(c, o, node, type_hint);
  4999. case_end;
  5000. case_ast_node(ie, IndexExpr, node);
  5001. check_expr(c, o, ie->expr);
  5002. if (o->mode == Addressing_Invalid) {
  5003. o->expr = node;
  5004. return kind;
  5005. }
  5006. Type *t = base_type(type_deref(o->type));
  5007. bool is_ptr = is_type_pointer(o->type);
  5008. bool is_const = o->mode == Addressing_Constant;
  5009. if (is_type_map(t)) {
  5010. Operand key = {};
  5011. check_expr(c, &key, ie->index);
  5012. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  5013. if (key.mode == Addressing_Invalid) {
  5014. o->mode = Addressing_Invalid;
  5015. o->expr = node;
  5016. return kind;
  5017. }
  5018. o->mode = Addressing_MapIndex;
  5019. o->type = t->Map.value;
  5020. o->expr = node;
  5021. add_package_dependency(c, "runtime", "__dynamic_map_get");
  5022. add_package_dependency(c, "runtime", "__dynamic_map_set");
  5023. return Expr_Expr;
  5024. }
  5025. i64 max_count = -1;
  5026. bool valid = check_set_index_data(o, t, is_ptr, &max_count);
  5027. if (is_const) {
  5028. valid = false;
  5029. }
  5030. if (!valid) {
  5031. gbString str = expr_to_string(o->expr);
  5032. gbString type_str = type_to_string(o->type);
  5033. defer (gb_string_free(str));
  5034. defer (gb_string_free(type_str));
  5035. if (is_const) {
  5036. error(o->expr, "Cannot index a constant '%s'", str);
  5037. } else {
  5038. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  5039. }
  5040. o->mode = Addressing_Invalid;
  5041. o->expr = node;
  5042. return kind;
  5043. }
  5044. if (ie->index == nullptr) {
  5045. gbString str = expr_to_string(o->expr);
  5046. error(o->expr, "Missing index for '%s'", str);
  5047. gb_string_free(str);
  5048. o->mode = Addressing_Invalid;
  5049. o->expr = node;
  5050. return kind;
  5051. }
  5052. i64 index = 0;
  5053. bool ok = check_index_value(c, false, ie->index, max_count, &index);
  5054. case_end;
  5055. case_ast_node(se, SliceExpr, node);
  5056. check_expr(c, o, se->expr);
  5057. if (o->mode == Addressing_Invalid) {
  5058. o->mode = Addressing_Invalid;
  5059. o->expr = node;
  5060. return kind;
  5061. }
  5062. bool valid = false;
  5063. i64 max_count = -1;
  5064. Type *t = base_type(type_deref(o->type));
  5065. switch (t->kind) {
  5066. case Type_Basic:
  5067. if (t->Basic.kind == Basic_string) {
  5068. valid = true;
  5069. if (o->mode == Addressing_Constant) {
  5070. max_count = o->value.value_string.len;
  5071. }
  5072. o->type = t_string;
  5073. }
  5074. break;
  5075. case Type_Array:
  5076. valid = true;
  5077. max_count = t->Array.count;
  5078. if (o->mode != Addressing_Variable) {
  5079. gbString str = expr_to_string(node);
  5080. error(node, "Cannot slice array '%s', value is not addressable", str);
  5081. gb_string_free(str);
  5082. o->mode = Addressing_Invalid;
  5083. o->expr = node;
  5084. return kind;
  5085. }
  5086. o->type = alloc_type_slice(t->Array.elem);
  5087. break;
  5088. case Type_Slice:
  5089. valid = true;
  5090. o->type = type_deref(o->type);
  5091. break;
  5092. case Type_DynamicArray:
  5093. valid = true;
  5094. o->type = alloc_type_slice(t->DynamicArray.elem);
  5095. break;
  5096. }
  5097. if (!valid) {
  5098. gbString str = expr_to_string(o->expr);
  5099. error(o->expr, "Cannot slice '%s'", str);
  5100. gb_string_free(str);
  5101. o->mode = Addressing_Invalid;
  5102. o->expr = node;
  5103. return kind;
  5104. }
  5105. if (o->mode != Addressing_Immutable) {
  5106. o->mode = Addressing_Value;
  5107. }
  5108. if (se->low == nullptr && se->high != nullptr) {
  5109. // error(se->interval0, "1st index is required if a 2nd index is specified");
  5110. // It is okay to continue as it will assume the 1st index is zero
  5111. }
  5112. i64 indices[2] = {};
  5113. Ast *nodes[2] = {se->low, se->high};
  5114. for (isize i = 0; i < gb_count_of(nodes); i++) {
  5115. i64 index = max_count;
  5116. if (nodes[i] != nullptr) {
  5117. i64 capacity = -1;
  5118. if (max_count >= 0) {
  5119. capacity = max_count;
  5120. }
  5121. i64 j = 0;
  5122. if (check_index_value(c, false, nodes[i], capacity, &j)) {
  5123. index = j;
  5124. }
  5125. } else if (i == 0) {
  5126. index = 0;
  5127. }
  5128. indices[i] = index;
  5129. }
  5130. for (isize i = 0; i < gb_count_of(indices); i++) {
  5131. i64 a = indices[i];
  5132. for (isize j = i+1; j < gb_count_of(indices); j++) {
  5133. i64 b = indices[j];
  5134. if (a > b && b >= 0) {
  5135. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  5136. }
  5137. }
  5138. }
  5139. case_end;
  5140. case_ast_node(ce, CallExpr, node);
  5141. return check_call_expr(c, o, node);
  5142. case_end;
  5143. case_ast_node(de, DerefExpr, node);
  5144. check_expr_or_type(c, o, de->expr);
  5145. if (o->mode == Addressing_Invalid) {
  5146. o->mode = Addressing_Invalid;
  5147. o->expr = node;
  5148. return kind;
  5149. } else {
  5150. Type *t = base_type(o->type);
  5151. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  5152. if (o->mode != Addressing_Immutable) {
  5153. o->mode = Addressing_Variable;
  5154. }
  5155. o->type = t->Pointer.elem;
  5156. } else {
  5157. gbString str = expr_to_string(o->expr);
  5158. gbString typ = type_to_string(o->type);
  5159. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  5160. gb_string_free(typ);
  5161. gb_string_free(str);
  5162. o->mode = Addressing_Invalid;
  5163. o->expr = node;
  5164. return kind;
  5165. }
  5166. }
  5167. case_end;
  5168. case Ast_TypeType:
  5169. case Ast_PolyType:
  5170. case Ast_ProcType:
  5171. case Ast_PointerType:
  5172. case Ast_ArrayType:
  5173. case Ast_DynamicArrayType:
  5174. case Ast_StructType:
  5175. case Ast_UnionType:
  5176. // case Ast_RawUnionType:
  5177. case Ast_EnumType:
  5178. case Ast_MapType:
  5179. o->mode = Addressing_Type;
  5180. o->type = check_type(c, node);
  5181. break;
  5182. }
  5183. kind = Expr_Expr;
  5184. o->expr = node;
  5185. return kind;
  5186. }
  5187. ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  5188. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  5189. Type *type = nullptr;
  5190. ExactValue value = {ExactValue_Invalid};
  5191. switch (o->mode) {
  5192. case Addressing_Invalid:
  5193. type = t_invalid;
  5194. break;
  5195. case Addressing_NoValue:
  5196. type = nullptr;
  5197. break;
  5198. case Addressing_Constant:
  5199. value = o->value;
  5200. type = o->type;
  5201. break;
  5202. default:
  5203. type = o->type;
  5204. break;
  5205. }
  5206. if (type != nullptr && is_type_untyped(type)) {
  5207. add_untyped(&c->checker->info, node, false, o->mode, type, value);
  5208. } else {
  5209. add_type_and_value(&c->checker->info, node, o->mode, type, value);
  5210. }
  5211. return kind;
  5212. }
  5213. void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  5214. check_expr_base(c, o, e, nullptr);
  5215. switch (o->mode) {
  5216. default:
  5217. return; // NOTE(bill): Valid
  5218. case Addressing_NoValue:
  5219. error_operand_no_value(o);
  5220. break;
  5221. case Addressing_Type:
  5222. error_operand_not_expression(o);
  5223. break;
  5224. }
  5225. o->mode = Addressing_Invalid;
  5226. }
  5227. void check_not_tuple(CheckerContext *c, Operand *o) {
  5228. if (o->mode == Addressing_Value) {
  5229. // NOTE(bill): Tuples are not first class thus never named
  5230. if (o->type->kind == Type_Tuple) {
  5231. isize count = o->type->Tuple.variables.count;
  5232. GB_ASSERT(count != 1);
  5233. error(o->expr,
  5234. "%td-valued tuple found where single value expected", count);
  5235. o->mode = Addressing_Invalid;
  5236. }
  5237. }
  5238. }
  5239. void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  5240. check_multi_expr(c, o, e);
  5241. check_not_tuple(c, o);
  5242. }
  5243. void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  5244. check_expr_base(c, o, e, type_hint);
  5245. check_not_tuple(c, o);
  5246. error_operand_no_value(o);
  5247. }
  5248. gbString write_expr_to_string(gbString str, Ast *node);
  5249. gbString write_struct_fields_to_string(gbString str, Array<Ast *> const &params) {
  5250. for_array(i, params) {
  5251. if (i > 0) {
  5252. str = gb_string_appendc(str, ", ");
  5253. }
  5254. str = write_expr_to_string(str, params[i]);
  5255. }
  5256. return str;
  5257. }
  5258. gbString string_append_string(gbString str, String string) {
  5259. if (string.len > 0) {
  5260. return gb_string_append_length(str, &string[0], string.len);
  5261. }
  5262. return str;
  5263. }
  5264. gbString string_append_token(gbString str, Token token) {
  5265. return string_append_string(str, token.string);
  5266. }
  5267. gbString write_expr_to_string(gbString str, Ast *node) {
  5268. if (node == nullptr)
  5269. return str;
  5270. if (is_ast_stmt(node)) {
  5271. GB_ASSERT("stmt passed to write_expr_to_string");
  5272. }
  5273. switch (node->kind) {
  5274. default:
  5275. str = gb_string_appendc(str, "(BadExpr)");
  5276. break;
  5277. case_ast_node(i, Ident, node);
  5278. str = string_append_token(str, i->token);
  5279. case_end;
  5280. case_ast_node(i, Implicit, node);
  5281. str = string_append_token(str, *i);
  5282. case_end;
  5283. case_ast_node(bl, BasicLit, node);
  5284. str = string_append_token(str, bl->token);
  5285. case_end;
  5286. case_ast_node(bd, BasicDirective, node);
  5287. str = gb_string_append_rune(str, '#');
  5288. str = string_append_string(str, bd->name);
  5289. case_end;
  5290. case_ast_node(ud, Undef, node);
  5291. str = gb_string_appendc(str, "---");
  5292. case_end;
  5293. case_ast_node(pg, ProcGroup, node);
  5294. str = gb_string_appendc(str, "proc[");
  5295. for_array(i, pg->args) {
  5296. if (i > 0) str = gb_string_appendc(str, ", ");
  5297. str = write_expr_to_string(str, pg->args[i]);
  5298. }
  5299. str = gb_string_append_rune(str, ']');
  5300. case_end;
  5301. case_ast_node(pl, ProcLit, node);
  5302. str = write_expr_to_string(str, pl->type);
  5303. case_end;
  5304. case_ast_node(cl, CompoundLit, node);
  5305. str = write_expr_to_string(str, cl->type);
  5306. str = gb_string_append_rune(str, '{');
  5307. for_array(i, cl->elems) {
  5308. if (i > 0) str = gb_string_appendc(str, ", ");
  5309. str = write_expr_to_string(str, cl->elems[i]);
  5310. }
  5311. str = gb_string_append_rune(str, '}');
  5312. case_end;
  5313. case_ast_node(te, TagExpr, node);
  5314. str = gb_string_append_rune(str, '#');
  5315. str = string_append_token(str, te->name);
  5316. str = write_expr_to_string(str, te->expr);
  5317. case_end;
  5318. case_ast_node(ue, UnaryExpr, node);
  5319. str = string_append_token(str, ue->op);
  5320. str = write_expr_to_string(str, ue->expr);
  5321. case_end;
  5322. case_ast_node(de, DerefExpr, node);
  5323. str = write_expr_to_string(str, de->expr);
  5324. str = gb_string_append_rune(str, '^');
  5325. case_end;
  5326. case_ast_node(be, BinaryExpr, node);
  5327. str = write_expr_to_string(str, be->left);
  5328. str = gb_string_append_rune(str, ' ');
  5329. str = string_append_token(str, be->op);
  5330. str = gb_string_append_rune(str, ' ');
  5331. str = write_expr_to_string(str, be->right);
  5332. case_end;
  5333. case_ast_node(te, TernaryExpr, node);
  5334. str = write_expr_to_string(str, te->cond);
  5335. str = gb_string_appendc(str, " ? ");
  5336. str = write_expr_to_string(str, te->x);
  5337. str = gb_string_appendc(str, " : ");
  5338. str = write_expr_to_string(str, te->y);
  5339. case_end;
  5340. case_ast_node(pe, ParenExpr, node);
  5341. str = gb_string_append_rune(str, '(');
  5342. str = write_expr_to_string(str, pe->expr);
  5343. str = gb_string_append_rune(str, ')');
  5344. case_end;
  5345. case_ast_node(se, SelectorExpr, node);
  5346. str = write_expr_to_string(str, se->expr);
  5347. str = gb_string_append_rune(str, '.');
  5348. str = write_expr_to_string(str, se->selector);
  5349. case_end;
  5350. case_ast_node(ta, TypeAssertion, node);
  5351. str = write_expr_to_string(str, ta->expr);
  5352. str = gb_string_appendc(str, ".(");
  5353. str = write_expr_to_string(str, ta->type);
  5354. str = gb_string_append_rune(str, ')');
  5355. case_end;
  5356. case_ast_node(tc, TypeCast, node);
  5357. str = string_append_token(str, tc->token);
  5358. str = gb_string_append_rune(str, '(');
  5359. str = write_expr_to_string(str, tc->type);
  5360. str = gb_string_append_rune(str, ')');
  5361. str = write_expr_to_string(str, tc->expr);
  5362. case_end;
  5363. case_ast_node(ac, AutoCast, node);
  5364. str = string_append_token(str, ac->token);
  5365. str = gb_string_append_rune(str, ' ');
  5366. str = write_expr_to_string(str, ac->expr);
  5367. case_end;
  5368. case_ast_node(ie, IndexExpr, node);
  5369. str = write_expr_to_string(str, ie->expr);
  5370. str = gb_string_append_rune(str, '[');
  5371. str = write_expr_to_string(str, ie->index);
  5372. str = gb_string_append_rune(str, ']');
  5373. case_end;
  5374. case_ast_node(se, SliceExpr, node);
  5375. str = write_expr_to_string(str, se->expr);
  5376. str = gb_string_append_rune(str, '[');
  5377. str = write_expr_to_string(str, se->low);
  5378. str = string_append_token(str, se->interval);
  5379. str = write_expr_to_string(str, se->high);
  5380. str = gb_string_append_rune(str, ']');
  5381. case_end;
  5382. case_ast_node(e, Ellipsis, node);
  5383. str = gb_string_appendc(str, "...");
  5384. str = write_expr_to_string(str, e->expr);
  5385. case_end;
  5386. case_ast_node(fv, FieldValue, node);
  5387. str = write_expr_to_string(str, fv->field);
  5388. str = gb_string_appendc(str, " = ");
  5389. str = write_expr_to_string(str, fv->value);
  5390. case_end;
  5391. case_ast_node(ht, HelperType, node);
  5392. str = gb_string_appendc(str, "#type ");
  5393. str = write_expr_to_string(str, ht->type);
  5394. case_end;
  5395. case_ast_node(ht, DistinctType, node);
  5396. str = gb_string_appendc(str, "distinct ");
  5397. str = write_expr_to_string(str, ht->type);
  5398. case_end;
  5399. case_ast_node(pt, PolyType, node);
  5400. str = gb_string_append_rune(str, '$');
  5401. str = write_expr_to_string(str, pt->type);
  5402. if (pt->specialization != nullptr) {
  5403. str = gb_string_append_rune(str, '/');
  5404. str = write_expr_to_string(str, pt->specialization);
  5405. }
  5406. case_end;
  5407. case_ast_node(pt, PointerType, node);
  5408. str = gb_string_append_rune(str, '^');
  5409. str = write_expr_to_string(str, pt->type);
  5410. case_end;
  5411. case_ast_node(at, ArrayType, node);
  5412. str = gb_string_append_rune(str, '[');
  5413. if (at->count != nullptr &&
  5414. at->count->kind == Ast_UnaryExpr &&
  5415. at->count->UnaryExpr.op.kind == Token_Question) {
  5416. str = gb_string_appendc(str, "?");
  5417. } else {
  5418. str = write_expr_to_string(str, at->count);
  5419. }
  5420. str = gb_string_append_rune(str, ']');
  5421. str = write_expr_to_string(str, at->elem);
  5422. case_end;
  5423. case_ast_node(at, DynamicArrayType, node);
  5424. str = gb_string_appendc(str, "[dynamic]");
  5425. str = write_expr_to_string(str, at->elem);
  5426. case_end;
  5427. case_ast_node(bf, BitFieldType, node);
  5428. str = gb_string_appendc(str, "bit_field ");
  5429. if (bf->align) {
  5430. str = gb_string_appendc(str, "#align ");
  5431. str = write_expr_to_string(str, bf->align);
  5432. }
  5433. str = gb_string_appendc(str, "{");
  5434. str = write_struct_fields_to_string(str, bf->fields);
  5435. str = gb_string_appendc(str, "}");
  5436. case_end;
  5437. case_ast_node(bs, BitSetType, node);
  5438. str = gb_string_appendc(str, "bit_set[");
  5439. str = write_expr_to_string(str, bs->base_type);
  5440. str = gb_string_appendc(str, "]");
  5441. case_end;
  5442. case_ast_node(mt, MapType, node);
  5443. str = gb_string_appendc(str, "map[");
  5444. str = write_expr_to_string(str, mt->key);
  5445. str = gb_string_append_rune(str, ']');
  5446. str = write_expr_to_string(str, mt->value);
  5447. case_end;
  5448. case_ast_node(f, Field, node);
  5449. if (f->flags&FieldFlag_using) {
  5450. str = gb_string_appendc(str, "using ");
  5451. }
  5452. if (f->flags&FieldFlag_no_alias) {
  5453. str = gb_string_appendc(str, "#no_alias ");
  5454. }
  5455. if (f->flags&FieldFlag_c_vararg) {
  5456. str = gb_string_appendc(str, "#c_vararg ");
  5457. }
  5458. if (f->flags&FieldFlag_auto_cast) {
  5459. str = gb_string_appendc(str, "auto_cast ");
  5460. }
  5461. for_array(i, f->names) {
  5462. Ast *name = f->names[i];
  5463. if (i > 0) str = gb_string_appendc(str, ", ");
  5464. str = write_expr_to_string(str, name);
  5465. }
  5466. if (f->names.count > 0) {
  5467. if (f->type == nullptr && f->default_value != nullptr) {
  5468. str = gb_string_append_rune(str, ' ');
  5469. }
  5470. str = gb_string_appendc(str, ":");
  5471. }
  5472. if (f->type != nullptr) {
  5473. str = gb_string_append_rune(str, ' ');
  5474. str = write_expr_to_string(str, f->type);
  5475. }
  5476. if (f->default_value != nullptr) {
  5477. if (f->type != nullptr) {
  5478. str = gb_string_append_rune(str, ' ');
  5479. }
  5480. str = gb_string_appendc(str, "= ");
  5481. str = write_expr_to_string(str, f->default_value);
  5482. }
  5483. case_end;
  5484. case_ast_node(f, FieldList, node);
  5485. bool has_name = false;
  5486. for_array(i, f->list) {
  5487. ast_node(field, Field, f->list[i]);
  5488. if (field->names.count > 1) {
  5489. has_name = true;
  5490. break;
  5491. }
  5492. if (field->names.count == 0) {
  5493. continue;
  5494. }
  5495. if (!is_blank_ident(field->names[0])) {
  5496. has_name = true;
  5497. break;
  5498. }
  5499. }
  5500. for_array(i, f->list) {
  5501. if (i > 0) str = gb_string_appendc(str, ", ");
  5502. if (has_name) {
  5503. str = write_expr_to_string(str, f->list[i]);
  5504. } else {
  5505. ast_node(field, Field, f->list[i]);
  5506. if (field->flags&FieldFlag_using) {
  5507. str = gb_string_appendc(str, "using ");
  5508. }
  5509. if (field->flags&FieldFlag_no_alias) {
  5510. str = gb_string_appendc(str, "#no_alias ");
  5511. }
  5512. if (field->flags&FieldFlag_c_vararg) {
  5513. str = gb_string_appendc(str, "#c_vararg ");
  5514. }
  5515. str = write_expr_to_string(str, field->type);
  5516. }
  5517. }
  5518. case_end;
  5519. case_ast_node(f, UnionField, node);
  5520. str = write_expr_to_string(str, f->name);
  5521. str = gb_string_append_rune(str, '{');
  5522. str = write_expr_to_string(str, f->list);
  5523. str = gb_string_append_rune(str, '}');
  5524. case_end;
  5525. case_ast_node(ce, CallExpr, node);
  5526. str = write_expr_to_string(str, ce->proc);
  5527. str = gb_string_appendc(str, "(");
  5528. for_array(i, ce->args) {
  5529. Ast *arg = ce->args[i];
  5530. if (i > 0) {
  5531. str = gb_string_appendc(str, ", ");
  5532. }
  5533. str = write_expr_to_string(str, arg);
  5534. }
  5535. str = gb_string_appendc(str, ")");
  5536. case_end;
  5537. case_ast_node(tt, TypeType, node);
  5538. str = gb_string_appendc(str, "type");
  5539. if (tt->specialization) {
  5540. str = gb_string_appendc(str, "/");
  5541. str = write_expr_to_string(str, tt->specialization);
  5542. }
  5543. case_end;
  5544. case_ast_node(pt, ProcType, node);
  5545. str = gb_string_appendc(str, "proc(");
  5546. str = write_expr_to_string(str, pt->params);
  5547. str = gb_string_appendc(str, ")");
  5548. if (pt->results != nullptr) {
  5549. str = gb_string_appendc(str, " -> ");
  5550. str = write_expr_to_string(str, pt->results);
  5551. }
  5552. case_end;
  5553. case_ast_node(st, StructType, node);
  5554. str = gb_string_appendc(str, "struct ");
  5555. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  5556. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  5557. str = gb_string_append_rune(str, '{');
  5558. str = write_struct_fields_to_string(str, st->fields);
  5559. str = gb_string_append_rune(str, '}');
  5560. case_end;
  5561. case_ast_node(st, UnionType, node);
  5562. str = gb_string_appendc(str, "union ");
  5563. str = gb_string_append_rune(str, '{');
  5564. str = write_struct_fields_to_string(str, st->variants);
  5565. str = gb_string_append_rune(str, '}');
  5566. case_end;
  5567. case_ast_node(et, EnumType, node);
  5568. str = gb_string_appendc(str, "enum ");
  5569. if (et->base_type != nullptr) {
  5570. str = write_expr_to_string(str, et->base_type);
  5571. str = gb_string_append_rune(str, ' ');
  5572. }
  5573. str = gb_string_append_rune(str, '{');
  5574. for_array(i, et->fields) {
  5575. if (i > 0) {
  5576. str = gb_string_appendc(str, ", ");
  5577. }
  5578. str = write_expr_to_string(str, et->fields[i]);
  5579. }
  5580. str = gb_string_append_rune(str, '}');
  5581. case_end;
  5582. }
  5583. return str;
  5584. }
  5585. gbString expr_to_string(Ast *expression) {
  5586. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression);
  5587. }