check_expr.cpp 202 KB

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