check_expr.cpp 177 KB

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