check_expr.cpp 172 KB

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