check_expr.cpp 177 KB

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