check_expr.cpp 194 KB

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