check_expr.cpp 178 KB

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