check_expr.cpp 175 KB

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