check_expr.cpp 235 KB

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