check_expr.cpp 236 KB

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