check_expr.cpp 174 KB

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