check_expr.cpp 321 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal Entity * find_polymorphic_record_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> const &ordered_operands, bool *failure);
  73. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  74. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  75. gb_internal gbString expr_to_string (Ast *expression);
  76. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  77. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  78. gb_internal bool check_is_terminating (Ast *node, String const &label);
  79. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  80. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  81. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  82. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  83. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  84. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  85. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  86. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  87. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  88. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  89. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  90. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type);
  91. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_);
  96. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  97. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  98. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  99. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal bool is_diverging_expr(Ast *expr);
  101. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  102. enum LoadDirectiveResult {
  103. LoadDirective_Success = 0,
  104. LoadDirective_Error = 1,
  105. LoadDirective_NotFound = 2,
  106. };
  107. gb_internal bool is_load_directive_call(Ast *call) {
  108. call = unparen_expr(call);
  109. if (call->kind != Ast_CallExpr) {
  110. return false;
  111. }
  112. ast_node(ce, CallExpr, call);
  113. if (ce->proc->kind != Ast_BasicDirective) {
  114. return false;
  115. }
  116. ast_node(bd, BasicDirective, ce->proc);
  117. String name = bd->name.string;
  118. return name == "load";
  119. }
  120. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  121. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  122. auto results = did_you_mean_results(d);
  123. if (results.count != 0) {
  124. error_line("\tSuggestion: Did you mean?\n");
  125. for (auto const &result : results) {
  126. String const &target = result.target;
  127. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  128. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  129. }
  130. }
  131. }
  132. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  133. if (e->kind != Entity_TypeName) {
  134. return;
  135. }
  136. if (e->TypeName.objc_metadata == nullptr) {
  137. return;
  138. }
  139. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  140. Type *t = base_type(e->type);
  141. GB_ASSERT(t->kind == Type_Struct);
  142. if (is_type) {
  143. for (auto const &entry : objc_metadata->type_entries) {
  144. string_set_add(set, entry.name);
  145. }
  146. } else {
  147. for (auto const &entry : objc_metadata->value_entries) {
  148. string_set_add(set, entry.name);
  149. }
  150. }
  151. for (Entity *f : t->Struct.fields) {
  152. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  153. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  154. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  155. }
  156. }
  157. }
  158. }
  159. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  160. if (build_context.terse_errors) { return; }
  161. ERROR_BLOCK();
  162. GB_ASSERT(e->kind == Entity_TypeName);
  163. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  164. auto *objc_metadata = e->TypeName.objc_metadata;
  165. MUTEX_GUARD(objc_metadata->mutex);
  166. StringSet set = {};
  167. defer (string_set_destroy(&set));
  168. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  169. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  170. defer (did_you_mean_destroy(&d));
  171. for (String const &target : set) {
  172. did_you_mean_append(&d, target);
  173. }
  174. check_did_you_mean_print(&d, prefix);
  175. }
  176. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  177. if (build_context.terse_errors) { return; }
  178. ERROR_BLOCK();
  179. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  180. defer (did_you_mean_destroy(&d));
  181. for (Entity *e : fields) {
  182. did_you_mean_append(&d, e->token.string);
  183. }
  184. check_did_you_mean_print(&d, prefix);
  185. }
  186. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  187. if (build_context.terse_errors) { return; }
  188. ERROR_BLOCK();
  189. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  190. defer (did_you_mean_destroy(&d));
  191. for (Entity *e : fields) {
  192. did_you_mean_append(&d, e->token.string);
  193. }
  194. check_did_you_mean_print(&d, prefix);
  195. }
  196. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  197. if (build_context.terse_errors) { return; }
  198. ERROR_BLOCK();
  199. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  200. defer (did_you_mean_destroy(&d));
  201. rw_mutex_shared_lock(&scope->mutex);
  202. for (auto const &entry : scope->elements) {
  203. Entity *e = entry.value;
  204. did_you_mean_append(&d, e->token.string);
  205. }
  206. rw_mutex_shared_unlock(&scope->mutex);
  207. check_did_you_mean_print(&d, prefix);
  208. }
  209. gb_internal Entity *entity_from_expr(Ast *expr) {
  210. expr = unparen_expr(expr);
  211. switch (expr->kind) {
  212. case Ast_Ident:
  213. return expr->Ident.entity;
  214. case Ast_SelectorExpr:
  215. return entity_from_expr(expr->SelectorExpr.selector);
  216. }
  217. return nullptr;
  218. }
  219. gb_internal void error_operand_not_expression(Operand *o) {
  220. if (o->mode == Addressing_Type) {
  221. gbString err = expr_to_string(o->expr);
  222. error(o->expr, "'%s' is not an expression but a type", err);
  223. gb_string_free(err);
  224. o->mode = Addressing_Invalid;
  225. }
  226. }
  227. gb_internal void error_operand_no_value(Operand *o) {
  228. if (o->mode == Addressing_NoValue) {
  229. gbString err = expr_to_string(o->expr);
  230. Ast *x = unparen_expr(o->expr);
  231. if (x->kind == Ast_CallExpr) {
  232. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  233. } else {
  234. error(o->expr, "'%s' used as a value", err);
  235. }
  236. gb_string_free(err);
  237. o->mode = Addressing_Invalid;
  238. }
  239. }
  240. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  241. if (build_context.dynamic_map_calls) {
  242. add_package_dependency(c, "runtime", "__dynamic_map_get");
  243. } else {
  244. add_package_dependency(c, "runtime", "map_desired_position");
  245. add_package_dependency(c, "runtime", "map_probe_distance");
  246. }
  247. }
  248. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  249. init_core_source_code_location(c->checker);
  250. if (t_map_set_proc == nullptr) {
  251. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  252. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  253. }
  254. if (build_context.dynamic_map_calls) {
  255. add_package_dependency(c, "runtime", "__dynamic_map_set");
  256. } else {
  257. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  258. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  259. }
  260. }
  261. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  262. init_core_source_code_location(c->checker);
  263. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  264. }
  265. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  266. Scope *s = c->scope;
  267. check_collect_entities(c, nodes);
  268. for (auto const &entry : s->elements) {
  269. Entity *e = entry.value;
  270. switch (e->kind) {
  271. case Entity_Constant:
  272. case Entity_TypeName:
  273. case Entity_Procedure:
  274. break;
  275. default:
  276. continue;
  277. }
  278. DeclInfo *d = decl_info_of_entity(e);
  279. if (d != nullptr) {
  280. check_entity_decl(c, e, d, nullptr);
  281. }
  282. }
  283. }
  284. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  285. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  286. ///////////////////////////////////////////////////////////////////////////////
  287. // //
  288. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  289. // //
  290. ///////////////////////////////////////////////////////////////////////////////
  291. CheckerInfo *info = old_c->info;
  292. if (base_entity == nullptr) {
  293. return false;
  294. }
  295. if (!is_type_proc(base_entity->type)) {
  296. return false;
  297. }
  298. if (base_entity->flags & EntityFlag_Disabled) {
  299. return false;
  300. }
  301. String name = base_entity->token.string;
  302. Type *src = base_type(base_entity->type);
  303. Type *dst = nullptr;
  304. if (type != nullptr) {
  305. dst = base_type(type);
  306. }
  307. if (param_operands == nullptr) {
  308. GB_ASSERT(dst != nullptr);
  309. }
  310. if (param_operands != nullptr) {
  311. GB_ASSERT(dst == nullptr);
  312. }
  313. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  314. return false;
  315. }
  316. if (dst != nullptr) {
  317. if (dst->Proc.is_polymorphic) {
  318. return false;
  319. }
  320. if (dst->Proc.param_count != src->Proc.param_count ||
  321. dst->Proc.result_count != src->Proc.result_count) {
  322. return false;
  323. }
  324. }
  325. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  326. if (old_decl == nullptr) {
  327. return false;
  328. }
  329. gbAllocator a = heap_allocator();
  330. Array<Operand> operands = {};
  331. if (param_operands) {
  332. operands = *param_operands;
  333. } else {
  334. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  335. for (isize i = 0; i < dst->Proc.param_count; i++) {
  336. Entity *param = dst->Proc.params->Tuple.variables[i];
  337. Operand o = {Addressing_Value};
  338. o.type = param->type;
  339. array_add(&operands, o);
  340. }
  341. }
  342. defer (if (param_operands == nullptr) {
  343. array_free(&operands);
  344. });
  345. CheckerContext nctx = *old_c;
  346. Scope *scope = create_scope(info, base_entity->scope);
  347. scope->flags |= ScopeFlag_Proc;
  348. nctx.scope = scope;
  349. nctx.allow_polymorphic_types = true;
  350. if (nctx.polymorphic_scope == nullptr) {
  351. nctx.polymorphic_scope = scope;
  352. }
  353. auto *pt = &src->Proc;
  354. // NOTE(bill): This is slightly memory leaking if the type already exists
  355. // Maybe it's better to check with the previous types first?
  356. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  357. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  358. if (!success) {
  359. return false;
  360. }
  361. GenProcsData *gen_procs = nullptr;
  362. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  363. GB_ASSERT(base_entity->kind == Entity_Procedure);
  364. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  365. gen_procs = base_entity->Procedure.gen_procs;
  366. if (gen_procs) {
  367. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  368. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  369. for (Entity *other : gen_procs->procs) {
  370. Type *pt = base_type(other->type);
  371. if (are_types_identical(pt, final_proc_type)) {
  372. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  373. if (poly_proc_data) {
  374. poly_proc_data->gen_entity = other;
  375. }
  376. return true;
  377. }
  378. }
  379. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  380. } else {
  381. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  382. gen_procs->procs.allocator = heap_allocator();
  383. base_entity->Procedure.gen_procs = gen_procs;
  384. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  385. }
  386. {
  387. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  388. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  389. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  390. nctx.no_polymorphic_errors = false;
  391. // NOTE(bill): Reset scope from the failed procedure type
  392. scope_reset(scope);
  393. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  394. Ast *cloned_proc_type_node = clone_ast(pt->node);
  395. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  396. if (!success) {
  397. return false;
  398. }
  399. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  400. for (Entity *other : gen_procs->procs) {
  401. Type *pt = base_type(other->type);
  402. if (are_types_identical(pt, final_proc_type)) {
  403. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  404. if (poly_proc_data) {
  405. poly_proc_data->gen_entity = other;
  406. }
  407. DeclInfo *decl = other->decl_info;
  408. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  409. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  410. proc_info->file = other->file;
  411. proc_info->token = other->token;
  412. proc_info->decl = decl;
  413. proc_info->type = other->type;
  414. proc_info->body = decl->proc_lit->ProcLit.body;
  415. proc_info->tags = other->Procedure.tags;;
  416. proc_info->generated_from_polymorphic = true;
  417. proc_info->poly_def_node = poly_def_node;
  418. check_procedure_later(nctx.checker, proc_info);
  419. }
  420. return true;
  421. }
  422. }
  423. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  424. }
  425. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  426. ast_node(pl, ProcLit, proc_lit);
  427. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  428. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  429. final_proc_type->Proc.is_poly_specialized = true;
  430. final_proc_type->Proc.is_polymorphic = true;
  431. final_proc_type->Proc.variadic = src->Proc.variadic;
  432. final_proc_type->Proc.require_results = src->Proc.require_results;
  433. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  434. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  435. final_proc_type->Proc.diverging = src->Proc.diverging;
  436. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  437. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  438. for (isize i = 0; i < operands.count; i++) {
  439. Operand o = operands[i];
  440. if (final_proc_type == o.type ||
  441. base_entity->type == o.type) {
  442. // NOTE(bill): Cycle
  443. final_proc_type->Proc.is_poly_specialized = false;
  444. break;
  445. }
  446. }
  447. u64 tags = base_entity->Procedure.tags;
  448. Ast *ident = clone_ast(base_entity->identifier);
  449. Token token = ident->Ident.token;
  450. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  451. d->gen_proc_type = final_proc_type;
  452. d->type_expr = pl->type;
  453. d->proc_lit = proc_lit;
  454. d->proc_checked_state = ProcCheckedState_Unchecked;
  455. d->defer_use_checked = false;
  456. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  457. entity->identifier = ident;
  458. add_entity_and_decl_info(&nctx, ident, entity, d);
  459. // NOTE(bill): Set the scope afterwards as this is not real overloading
  460. entity->scope = scope->parent;
  461. entity->file = base_entity->file;
  462. entity->pkg = base_entity->pkg;
  463. entity->flags = 0;
  464. d->entity = entity;
  465. AstFile *file = nullptr;
  466. {
  467. Scope *s = entity->scope;
  468. while (s != nullptr && s->file == nullptr) {
  469. file = s->file;
  470. s = s->parent;
  471. }
  472. }
  473. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  474. array_add(&gen_procs->procs, entity);
  475. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  476. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  477. proc_info->file = file;
  478. proc_info->token = token;
  479. proc_info->decl = d;
  480. proc_info->type = final_proc_type;
  481. proc_info->body = pl->body;
  482. proc_info->tags = tags;
  483. proc_info->generated_from_polymorphic = true;
  484. proc_info->poly_def_node = poly_def_node;
  485. if (poly_proc_data) {
  486. poly_proc_data->gen_entity = entity;
  487. poly_proc_data->proc_info = proc_info;
  488. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  489. }
  490. // NOTE(bill): Check the newly generated procedure body
  491. check_procedure_later(nctx.checker, proc_info);
  492. return true;
  493. }
  494. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  495. if (operand->expr == nullptr) return false;
  496. Entity *base_entity = entity_of_node(operand->expr);
  497. if (base_entity == nullptr) return false;
  498. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  499. }
  500. gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> const *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  501. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  502. }
  503. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  504. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  505. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  506. #define MAXIMUM_TYPE_DISTANCE 10
  507. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  508. if (c == nullptr) {
  509. GB_ASSERT(operand->mode == Addressing_Value);
  510. GB_ASSERT(is_type_typed(operand->type));
  511. }
  512. if (operand->mode == Addressing_Invalid ||
  513. type == t_invalid) {
  514. return -1;
  515. }
  516. if (operand->mode == Addressing_Builtin) {
  517. return -1;
  518. }
  519. if (operand->mode == Addressing_Type) {
  520. if (is_type_typeid(type)) {
  521. if (is_type_polymorphic(operand->type)) {
  522. return -1;
  523. }
  524. add_type_info_type(c, operand->type);
  525. return 4;
  526. }
  527. return -1;
  528. }
  529. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  530. return -1;
  531. }
  532. Type *s = operand->type;
  533. if (are_types_identical(s, type)) {
  534. return 0;
  535. }
  536. Type *src = base_type(s);
  537. Type *dst = base_type(type);
  538. if (is_type_untyped_uninit(src)) {
  539. return 1;
  540. }
  541. if (is_type_untyped_nil(src)) {
  542. if (type_has_nil(dst)) {
  543. return 1;
  544. }
  545. return -1;
  546. }
  547. if (is_type_untyped(src)) {
  548. if (is_type_any(dst)) {
  549. // NOTE(bill): Anything can cast to 'Any'
  550. add_type_info_type(c, s);
  551. return MAXIMUM_TYPE_DISTANCE;
  552. }
  553. if (dst->kind == Type_Basic) {
  554. if (operand->mode == Addressing_Constant) {
  555. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  556. if (is_type_typed(dst) && src->kind == Type_Basic) {
  557. switch (src->Basic.kind) {
  558. case Basic_UntypedBool:
  559. if (is_type_boolean(dst)) {
  560. return 1;
  561. }
  562. break;
  563. case Basic_UntypedRune:
  564. if (is_type_integer(dst) || is_type_rune(dst)) {
  565. return 1;
  566. }
  567. break;
  568. case Basic_UntypedInteger:
  569. if (is_type_integer(dst) || is_type_rune(dst)) {
  570. return 1;
  571. }
  572. break;
  573. case Basic_UntypedString:
  574. if (is_type_string(dst)) {
  575. return 1;
  576. }
  577. break;
  578. case Basic_UntypedFloat:
  579. if (is_type_float(dst)) {
  580. return 1;
  581. }
  582. break;
  583. case Basic_UntypedComplex:
  584. if (is_type_complex(dst)) {
  585. return 1;
  586. }
  587. if (is_type_quaternion(dst)) {
  588. return 2;
  589. }
  590. break;
  591. case Basic_UntypedQuaternion:
  592. if (is_type_quaternion(dst)) {
  593. return 1;
  594. }
  595. break;
  596. }
  597. }
  598. return 2;
  599. }
  600. return -1;
  601. }
  602. if (src->kind == Type_Basic) {
  603. Type *d = base_array_type(dst);
  604. i64 score = -1;
  605. switch (src->Basic.kind) {
  606. case Basic_UntypedBool:
  607. if (is_type_boolean(d)) {
  608. score = 1;
  609. }
  610. break;
  611. case Basic_UntypedRune:
  612. if (is_type_integer(d) || is_type_rune(d)) {
  613. score = 1;
  614. }
  615. break;
  616. case Basic_UntypedInteger:
  617. if (is_type_integer(d) || is_type_rune(d)) {
  618. score = 1;
  619. }
  620. break;
  621. case Basic_UntypedString:
  622. if (is_type_string(d)) {
  623. score = 1;
  624. }
  625. break;
  626. case Basic_UntypedFloat:
  627. if (is_type_float(d)) {
  628. score = 1;
  629. }
  630. break;
  631. case Basic_UntypedComplex:
  632. if (is_type_complex(d)) {
  633. score = 1;
  634. }
  635. if (is_type_quaternion(d)) {
  636. score = 2;
  637. }
  638. break;
  639. case Basic_UntypedQuaternion:
  640. if (is_type_quaternion(d)) {
  641. score = 1;
  642. }
  643. break;
  644. }
  645. if (score > 0) {
  646. if (is_type_typed(d)) {
  647. score += 1;
  648. }
  649. if (d != dst) {
  650. score += 6;
  651. }
  652. }
  653. return score;
  654. }
  655. }
  656. }
  657. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  658. if (c->in_enum_type) {
  659. return 3;
  660. }
  661. }
  662. {
  663. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  664. if (subtype_level > 0) {
  665. return 4 + subtype_level;
  666. }
  667. }
  668. // rawptr <- ^T
  669. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  670. return 5;
  671. }
  672. // rawptr <- [^]T
  673. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  674. return 5;
  675. }
  676. // ^T <- [^]T
  677. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  678. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  679. return 4;
  680. }
  681. }
  682. // [^]T <- ^T
  683. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  684. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  685. return 4;
  686. }
  687. }
  688. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  689. bool modify_type = !c->no_polymorphic_errors;
  690. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  691. return 2;
  692. }
  693. }
  694. if (is_type_union(dst)) {
  695. for (Type *vt : dst->Union.variants) {
  696. if (are_types_identical(vt, s)) {
  697. return 1;
  698. }
  699. }
  700. if (dst->Union.variants.count == 1) {
  701. Type *vt = dst->Union.variants[0];
  702. i64 score = check_distance_between_types(c, operand, vt);
  703. if (score >= 0) {
  704. return score+2;
  705. }
  706. } else if (is_type_untyped(src)) {
  707. i64 prev_lowest_score = -1;
  708. i64 lowest_score = -1;
  709. for (Type *vt : dst->Union.variants) {
  710. i64 score = check_distance_between_types(c, operand, vt);
  711. if (score >= 0) {
  712. if (lowest_score < 0) {
  713. lowest_score = score;
  714. } else {
  715. if (prev_lowest_score < 0) {
  716. prev_lowest_score = lowest_score;
  717. } else {
  718. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  719. }
  720. lowest_score = gb_min(lowest_score, score);
  721. }
  722. }
  723. }
  724. if (lowest_score >= 0) {
  725. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  726. return lowest_score+2;
  727. }
  728. }
  729. }
  730. }
  731. if (is_type_relative_pointer(dst)) {
  732. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  733. if (score >= 0) {
  734. return score+2;
  735. }
  736. }
  737. if (is_type_relative_multi_pointer(dst)) {
  738. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type);
  739. if (score >= 0) {
  740. return score+2;
  741. }
  742. }
  743. if (is_type_proc(dst)) {
  744. if (are_types_identical(src, dst)) {
  745. return 3;
  746. }
  747. PolyProcData poly_proc_data = {};
  748. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  749. Entity *e = poly_proc_data.gen_entity;
  750. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  751. add_entity_use(c, operand->expr, e);
  752. return 4;
  753. }
  754. }
  755. if (is_type_complex_or_quaternion(dst)) {
  756. Type *elem = base_complex_elem_type(dst);
  757. if (are_types_identical(elem, base_type(src))) {
  758. return 5;
  759. }
  760. }
  761. if (is_type_array(dst)) {
  762. Type *elem = base_array_type(dst);
  763. i64 distance = check_distance_between_types(c, operand, elem);
  764. if (distance >= 0) {
  765. return distance + 6;
  766. }
  767. }
  768. if (is_type_simd_vector(dst)) {
  769. Type *dst_elem = base_array_type(dst);
  770. i64 distance = check_distance_between_types(c, operand, dst_elem);
  771. if (distance >= 0) {
  772. return distance + 6;
  773. }
  774. }
  775. if (is_type_matrix(dst)) {
  776. if (are_types_identical(src, dst)) {
  777. return 5;
  778. }
  779. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  780. Type *dst_elem = base_array_type(dst);
  781. i64 distance = check_distance_between_types(c, operand, dst_elem);
  782. if (distance >= 0) {
  783. return distance + 7;
  784. }
  785. }
  786. }
  787. if (is_type_any(dst)) {
  788. if (!is_type_polymorphic(src)) {
  789. if (operand->mode == Addressing_Context && operand->type == t_context) {
  790. return -1;
  791. } else {
  792. // NOTE(bill): Anything can cast to 'Any'
  793. add_type_info_type(c, s);
  794. return MAXIMUM_TYPE_DISTANCE;
  795. }
  796. }
  797. }
  798. Ast *expr = unparen_expr(operand->expr);
  799. if (expr != nullptr) {
  800. if (expr->kind == Ast_AutoCast) {
  801. Operand x = *operand;
  802. x.expr = expr->AutoCast.expr;
  803. if (check_cast_internal(c, &x, type)) {
  804. return MAXIMUM_TYPE_DISTANCE;
  805. }
  806. }
  807. }
  808. return -1;
  809. }
  810. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  811. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  812. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  813. // TODO(bill): A decent score function
  814. i64 d = distance*distance; // x^2
  815. if (is_variadic && d >= 0) {
  816. d += distance + 1; // x^2 + x + 1
  817. }
  818. return gb_max(c - d, 0);
  819. }
  820. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  821. i64 score = 0;
  822. i64 distance = check_distance_between_types(c, operand, type);
  823. bool ok = distance >= 0;
  824. if (ok) {
  825. score = assign_score_function(distance, is_variadic);
  826. }
  827. if (score_) *score_ = score;
  828. return ok;
  829. }
  830. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  831. i64 score = 0;
  832. return check_is_assignable_to_with_score(c, operand, type, &score);
  833. }
  834. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  835. Operand x = {};
  836. x.type = src;
  837. x.mode = Addressing_Value;
  838. return check_is_assignable_to(nullptr, &x, dst);
  839. }
  840. gb_internal AstPackage *get_package_of_type(Type *type) {
  841. for (;;) {
  842. if (type == nullptr) {
  843. return nullptr;
  844. }
  845. switch (type->kind) {
  846. case Type_Basic:
  847. return builtin_pkg;
  848. case Type_Named:
  849. if (type->Named.type_name != nullptr) {
  850. return type->Named.type_name->pkg;
  851. }
  852. return nullptr;
  853. case Type_Pointer:
  854. type = type->Pointer.elem;
  855. continue;
  856. case Type_Array:
  857. type = type->Array.elem;
  858. continue;
  859. case Type_Slice:
  860. type = type->Slice.elem;
  861. continue;
  862. case Type_DynamicArray:
  863. type = type->DynamicArray.elem;
  864. continue;
  865. case Type_RelativePointer:
  866. type = type->RelativePointer.pointer_type;
  867. continue;
  868. case Type_RelativeMultiPointer:
  869. type = type->RelativeMultiPointer.pointer_type;
  870. continue;
  871. }
  872. return nullptr;
  873. }
  874. }
  875. // NOTE(bill): 'content_name' is for debugging and error messages
  876. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  877. check_not_tuple(c, operand);
  878. if (operand->mode == Addressing_Invalid) {
  879. return;
  880. }
  881. if (is_type_untyped(operand->type)) {
  882. Type *target_type = type;
  883. if (type == nullptr || is_type_any(type)) {
  884. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  885. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  886. operand->mode = Addressing_Invalid;
  887. return;
  888. }
  889. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  890. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  891. operand->mode = Addressing_Invalid;
  892. return;
  893. }
  894. target_type = default_type(operand->type);
  895. if (type != nullptr && !is_type_any(type)) {
  896. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  897. }
  898. add_type_info_type(c, type);
  899. add_type_info_type(c, target_type);
  900. }
  901. convert_to_typed(c, operand, target_type);
  902. if (operand->mode == Addressing_Invalid) {
  903. return;
  904. }
  905. }
  906. if (type == nullptr) {
  907. return;
  908. }
  909. if (operand->mode == Addressing_ProcGroup) {
  910. bool good = false;
  911. if (type != nullptr && is_type_proc(type)) {
  912. Array<Entity *> procs = proc_group_entities(c, *operand);
  913. // NOTE(bill): These should be done
  914. for (Entity *e : procs) {
  915. Type *t = base_type(e->type);
  916. if (t == t_invalid) {
  917. continue;
  918. }
  919. Operand x = {};
  920. x.mode = Addressing_Value;
  921. x.type = t;
  922. if (check_is_assignable_to(c, &x, type)) {
  923. add_entity_use(c, operand->expr, e);
  924. good = true;
  925. break;
  926. }
  927. }
  928. }
  929. if (!good) {
  930. gbString expr_str = expr_to_string(operand->expr);
  931. gbString op_type_str = type_to_string(operand->type);
  932. gbString type_str = type_to_string(type);
  933. defer (gb_string_free(type_str));
  934. defer (gb_string_free(op_type_str));
  935. defer (gb_string_free(expr_str));
  936. // TODO(bill): is this a good enough error message?
  937. error(operand->expr,
  938. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  939. expr_str,
  940. op_type_str,
  941. LIT(context_name));
  942. operand->mode = Addressing_Invalid;
  943. }
  944. convert_to_typed(c, operand, type);
  945. return;
  946. }
  947. if (check_is_assignable_to(c, operand, type)) {
  948. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  949. add_type_info_type(c, operand->type);
  950. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  951. }
  952. } else {
  953. gbString expr_str = expr_to_string(operand->expr);
  954. gbString op_type_str = type_to_string(operand->type);
  955. gbString type_str = type_to_string(type);
  956. defer (gb_string_free(type_str));
  957. defer (gb_string_free(op_type_str));
  958. defer (gb_string_free(expr_str));
  959. switch (operand->mode) {
  960. case Addressing_Builtin:
  961. error(operand->expr,
  962. "Cannot assign built-in procedure '%s' in %.*s",
  963. expr_str,
  964. LIT(context_name));
  965. break;
  966. case Addressing_Type:
  967. if (is_type_polymorphic(operand->type)) {
  968. error(operand->expr,
  969. "Cannot assign '%s' which is a polymorphic type in %.*s",
  970. op_type_str,
  971. LIT(context_name));
  972. } else {
  973. error(operand->expr,
  974. "Cannot assign '%s' which is a type in %.*s",
  975. op_type_str,
  976. LIT(context_name));
  977. }
  978. break;
  979. default:
  980. // TODO(bill): is this a good enough error message?
  981. {
  982. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  983. gbString type_extra = gb_string_make(heap_allocator(), "");
  984. defer (gb_string_free(op_type_extra));
  985. defer (gb_string_free(type_extra));
  986. isize on = gb_string_length(op_type_str);
  987. isize tn = gb_string_length(type_str);
  988. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  989. AstPackage *op_pkg = get_package_of_type(operand->type);
  990. AstPackage *type_pkg = get_package_of_type(type);
  991. if (op_pkg != nullptr) {
  992. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  993. }
  994. if (type_pkg != nullptr) {
  995. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  996. }
  997. }
  998. ERROR_BLOCK();
  999. error(operand->expr,
  1000. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  1001. expr_str,
  1002. op_type_str, op_type_extra,
  1003. type_str, type_extra,
  1004. LIT(context_name));
  1005. check_assignment_error_suggestion(c, operand, type);
  1006. }
  1007. break;
  1008. }
  1009. operand->mode = Addressing_Invalid;
  1010. return;
  1011. }
  1012. }
  1013. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1014. Type *gt = *gt_;
  1015. GB_ASSERT(gt->kind == Type_Generic);
  1016. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1017. GB_ASSERT(e != nullptr);
  1018. if (e->kind == Entity_TypeName) {
  1019. *gt_ = nullptr;
  1020. *dst_count = source_count;
  1021. e->kind = Entity_Constant;
  1022. e->Constant.value = exact_value_i64(source_count);
  1023. e->type = t_untyped_integer;
  1024. return true;
  1025. } else if (e->kind == Entity_Constant) {
  1026. *gt_ = nullptr;
  1027. if (e->Constant.value.kind != ExactValue_Integer) {
  1028. return false;
  1029. }
  1030. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1031. if (count != source_count) {
  1032. return false;
  1033. }
  1034. *dst_count = source_count;
  1035. return true;
  1036. }
  1037. return false;
  1038. }
  1039. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1040. Operand o = {Addressing_Value};
  1041. o.type = source;
  1042. switch (poly->kind) {
  1043. case Type_Basic:
  1044. if (compound) return are_types_identical(poly, source);
  1045. return check_is_assignable_to(c, &o, poly);
  1046. case Type_Named: {
  1047. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1048. return true;
  1049. }
  1050. if (compound || !is_type_generic(poly)) {
  1051. return are_types_identical(poly, source);
  1052. }
  1053. return check_is_assignable_to(c, &o, poly);
  1054. }
  1055. case Type_Generic: {
  1056. if (poly->Generic.specialized != nullptr) {
  1057. Type *s = poly->Generic.specialized;
  1058. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1059. return false;
  1060. }
  1061. }
  1062. if (modify_type) {
  1063. Type *ds = default_type(source);
  1064. gb_memmove(poly, ds, gb_size_of(Type));
  1065. }
  1066. return true;
  1067. }
  1068. case Type_Pointer:
  1069. if (source->kind == Type_Pointer) {
  1070. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1071. if (level > 0) {
  1072. return true;
  1073. }
  1074. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1075. } else if (source->kind == Type_MultiPointer) {
  1076. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1077. if (level > 0) {
  1078. return true;
  1079. }
  1080. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1081. }
  1082. return false;
  1083. case Type_MultiPointer:
  1084. if (source->kind == Type_MultiPointer) {
  1085. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1086. if (level > 0) {
  1087. return true;
  1088. }
  1089. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1090. } else if (source->kind == Type_Pointer) {
  1091. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1092. if (level > 0) {
  1093. return true;
  1094. }
  1095. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1096. }
  1097. return false;
  1098. case Type_Array:
  1099. if (source->kind == Type_Array) {
  1100. if (poly->Array.generic_count != nullptr) {
  1101. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1102. return false;
  1103. }
  1104. }
  1105. if (poly->Array.count == source->Array.count) {
  1106. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1107. }
  1108. } else if (source->kind == Type_EnumeratedArray) {
  1109. if (poly->Array.generic_count != nullptr) {
  1110. Type *gt = poly->Array.generic_count;
  1111. GB_ASSERT(gt->kind == Type_Generic);
  1112. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1113. GB_ASSERT(e != nullptr);
  1114. if (e->kind == Entity_TypeName) {
  1115. Type *index = source->EnumeratedArray.index;
  1116. Type *it = base_type(index);
  1117. if (it->kind != Type_Enum) {
  1118. return false;
  1119. }
  1120. poly->kind = Type_EnumeratedArray;
  1121. poly->cached_size = -1;
  1122. poly->cached_align = -1;
  1123. poly->flags.exchange(source->flags);
  1124. poly->failure = false;
  1125. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1126. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1127. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1128. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1129. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1130. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1131. e->kind = Entity_TypeName;
  1132. e->TypeName.is_type_alias = true;
  1133. e->type = index;
  1134. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1135. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1136. }
  1137. }
  1138. }
  1139. }
  1140. return false;
  1141. case Type_EnumeratedArray:
  1142. if (source->kind == Type_EnumeratedArray) {
  1143. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1144. return false;
  1145. }
  1146. if (poly->EnumeratedArray.op) {
  1147. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1148. return false;
  1149. }
  1150. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1151. return false;
  1152. }
  1153. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1154. return false;
  1155. }
  1156. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1157. }
  1158. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1159. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1160. return index || elem;
  1161. }
  1162. return false;
  1163. case Type_DynamicArray:
  1164. if (source->kind == Type_DynamicArray) {
  1165. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1166. }
  1167. return false;
  1168. case Type_Slice:
  1169. if (source->kind == Type_Slice) {
  1170. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1171. }
  1172. return false;
  1173. case Type_Enum:
  1174. return false;
  1175. case Type_BitSet:
  1176. if (source->kind == Type_BitSet) {
  1177. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1178. return false;
  1179. }
  1180. if (poly->BitSet.underlying == nullptr) {
  1181. if (modify_type) {
  1182. poly->BitSet.underlying = source->BitSet.underlying;
  1183. }
  1184. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1185. return false;
  1186. }
  1187. return true;
  1188. }
  1189. return false;
  1190. case Type_Union:
  1191. if (source->kind == Type_Union) {
  1192. TypeUnion *x = &poly->Union;
  1193. TypeUnion *y = &source->Union;
  1194. if (x->variants.count != y->variants.count) {
  1195. return false;
  1196. }
  1197. for_array(i, x->variants) {
  1198. Type *a = x->variants[i];
  1199. Type *b = y->variants[i];
  1200. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1201. if (!ok) return false;
  1202. }
  1203. return true;
  1204. }
  1205. return false;
  1206. case Type_Struct:
  1207. if (source->kind == Type_Struct) {
  1208. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1209. poly->Struct.soa_kind != StructSoa_None) {
  1210. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1211. if (ok) switch (source->Struct.soa_kind) {
  1212. case StructSoa_Fixed:
  1213. default:
  1214. GB_PANIC("Unhandled SOA Kind");
  1215. break;
  1216. case StructSoa_Slice:
  1217. if (modify_type) {
  1218. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1219. gb_memmove(poly, type, gb_size_of(*type));
  1220. }
  1221. break;
  1222. case StructSoa_Dynamic:
  1223. if (modify_type) {
  1224. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1225. gb_memmove(poly, type, gb_size_of(*type));
  1226. }
  1227. break;
  1228. }
  1229. return ok;
  1230. }
  1231. // NOTE(bill): Check for subtypes of
  1232. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1233. }
  1234. return false;
  1235. case Type_Tuple:
  1236. GB_PANIC("This should never happen");
  1237. return false;
  1238. case Type_Proc:
  1239. if (source->kind == Type_Proc) {
  1240. TypeProc *x = &poly->Proc;
  1241. TypeProc *y = &source->Proc;
  1242. if (x->calling_convention != y->calling_convention) {
  1243. return false;
  1244. }
  1245. if (x->c_vararg != y->c_vararg) {
  1246. return false;
  1247. }
  1248. if (x->variadic != y->variadic) {
  1249. return false;
  1250. }
  1251. if (x->param_count != y->param_count) {
  1252. return false;
  1253. }
  1254. if (x->result_count != y->result_count) {
  1255. return false;
  1256. }
  1257. for (isize i = 0; i < x->param_count; i++) {
  1258. Entity *a = x->params->Tuple.variables[i];
  1259. Entity *b = y->params->Tuple.variables[i];
  1260. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1261. if (!ok) return false;
  1262. }
  1263. for (isize i = 0; i < x->result_count; i++) {
  1264. Entity *a = x->results->Tuple.variables[i];
  1265. Entity *b = y->results->Tuple.variables[i];
  1266. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1267. if (!ok) return false;
  1268. }
  1269. return true;
  1270. }
  1271. return false;
  1272. case Type_Map:
  1273. if (source->kind == Type_Map) {
  1274. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1275. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1276. if (key || value) {
  1277. poly->Map.lookup_result_type = nullptr;
  1278. init_map_internal_types(poly);
  1279. return true;
  1280. }
  1281. }
  1282. return false;
  1283. case Type_Matrix:
  1284. if (source->kind == Type_Matrix) {
  1285. if (poly->Matrix.generic_row_count != nullptr) {
  1286. poly->Matrix.stride_in_bytes = 0;
  1287. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1288. return false;
  1289. }
  1290. }
  1291. if (poly->Matrix.generic_column_count != nullptr) {
  1292. poly->Matrix.stride_in_bytes = 0;
  1293. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1294. return false;
  1295. }
  1296. }
  1297. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1298. poly->Matrix.column_count == source->Matrix.column_count) {
  1299. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1300. }
  1301. }
  1302. return false;
  1303. case Type_SimdVector:
  1304. if (source->kind == Type_SimdVector) {
  1305. if (poly->SimdVector.generic_count != nullptr) {
  1306. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1307. return false;
  1308. }
  1309. }
  1310. if (poly->SimdVector.count == source->SimdVector.count) {
  1311. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1312. }
  1313. }
  1314. return false;
  1315. }
  1316. return false;
  1317. }
  1318. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1319. if (curr->state != EntityState_InProgress) {
  1320. return false;
  1321. }
  1322. for_array(i, *c->type_path) {
  1323. Entity *prev = c->type_path->data[i];
  1324. if (prev == curr) {
  1325. if (report) {
  1326. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1327. for (isize j = i; j < c->type_path->count; j++) {
  1328. Entity *curr = (*c->type_path)[j];
  1329. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1330. }
  1331. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1332. curr->type = t_invalid;
  1333. }
  1334. return true;
  1335. }
  1336. }
  1337. return false;
  1338. }
  1339. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1340. GB_ASSERT(n->kind == Ast_Ident);
  1341. o->mode = Addressing_Invalid;
  1342. o->expr = n;
  1343. String name = n->Ident.token.string;
  1344. Entity *e = scope_lookup(c->scope, name);
  1345. if (e == nullptr) {
  1346. if (is_blank_ident(name)) {
  1347. error(n, "'_' cannot be used as a value");
  1348. } else {
  1349. error(n, "Undeclared name: %.*s", LIT(name));
  1350. }
  1351. o->type = t_invalid;
  1352. o->mode = Addressing_Invalid;
  1353. if (named_type != nullptr) {
  1354. set_base_type(named_type, t_invalid);
  1355. }
  1356. return nullptr;
  1357. }
  1358. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1359. if (e->parent_proc_decl != nullptr &&
  1360. e->parent_proc_decl != c->curr_proc_decl) {
  1361. if (e->kind == Entity_Variable) {
  1362. if ((e->flags & EntityFlag_Static) == 0) {
  1363. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1364. return nullptr;
  1365. }
  1366. } else if (e->kind == Entity_Label) {
  1367. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1368. return nullptr;
  1369. }
  1370. }
  1371. if (e->kind == Entity_ProcGroup) {
  1372. auto *pge = &e->ProcGroup;
  1373. DeclInfo *d = decl_info_of_entity(e);
  1374. check_entity_decl(c, e, d, nullptr);
  1375. Array<Entity *> procs = pge->entities;
  1376. bool skip = false;
  1377. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1378. // NOTE(bill): These should be done
  1379. for (Entity *proc : procs) {
  1380. Type *t = base_type(proc->type);
  1381. if (t == t_invalid) {
  1382. continue;
  1383. }
  1384. Operand x = {};
  1385. x.mode = Addressing_Value;
  1386. x.type = t;
  1387. if (check_is_assignable_to(c, &x, type_hint)) {
  1388. e = proc;
  1389. add_entity_use(c, n, e);
  1390. skip = true;
  1391. break;
  1392. }
  1393. }
  1394. }
  1395. if (!skip) {
  1396. o->mode = Addressing_ProcGroup;
  1397. o->type = t_invalid;
  1398. o->proc_group = e;
  1399. return nullptr;
  1400. }
  1401. }
  1402. add_entity_use(c, n, e);
  1403. if (e->state == EntityState_Unresolved) {
  1404. check_entity_decl(c, e, nullptr, named_type);
  1405. }
  1406. if (e->type == nullptr) {
  1407. // TODO(bill): Which is correct? return or compiler_error?
  1408. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1409. return nullptr;
  1410. }
  1411. e->flags |= EntityFlag_Used;
  1412. Type *type = e->type;
  1413. o->type = type;
  1414. switch (e->kind) {
  1415. case Entity_Constant:
  1416. if (type == t_invalid) {
  1417. o->type = t_invalid;
  1418. return e;
  1419. }
  1420. o->value = e->Constant.value;
  1421. if (o->value.kind == ExactValue_Invalid) {
  1422. return e;
  1423. }
  1424. if (o->value.kind == ExactValue_Procedure) {
  1425. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1426. if (proc != nullptr) {
  1427. o->mode = Addressing_Value;
  1428. o->type = proc->type;
  1429. return proc;
  1430. }
  1431. }
  1432. o->mode = Addressing_Constant;
  1433. break;
  1434. case Entity_Variable:
  1435. e->flags |= EntityFlag_Used;
  1436. if (type == t_invalid) {
  1437. o->type = t_invalid;
  1438. return e;
  1439. }
  1440. o->mode = Addressing_Variable;
  1441. if (e->flags & EntityFlag_Value) {
  1442. o->mode = Addressing_Value;
  1443. }
  1444. break;
  1445. case Entity_Procedure:
  1446. o->mode = Addressing_Value;
  1447. o->value = exact_value_procedure(n);
  1448. break;
  1449. case Entity_Builtin:
  1450. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1451. o->mode = Addressing_Builtin;
  1452. break;
  1453. case Entity_TypeName:
  1454. o->mode = Addressing_Type;
  1455. if (check_cycle(c, e, true)) {
  1456. o->type = t_invalid;
  1457. }
  1458. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1459. o->type = base_type(o->type);
  1460. }
  1461. break;
  1462. case Entity_ImportName:
  1463. if (!allow_import_name) {
  1464. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1465. }
  1466. return e;
  1467. case Entity_LibraryName:
  1468. if (!allow_import_name) {
  1469. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1470. }
  1471. return e;
  1472. case Entity_Label:
  1473. o->mode = Addressing_NoValue;
  1474. break;
  1475. case Entity_Nil:
  1476. o->mode = Addressing_Value;
  1477. break;
  1478. default:
  1479. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1480. break;
  1481. }
  1482. return e;
  1483. }
  1484. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1485. if (o->type == nullptr) {
  1486. gbString str = expr_to_string(o->expr);
  1487. error(o->expr, "Expression has no value '%s'", str);
  1488. gb_string_free(str);
  1489. return false;
  1490. }
  1491. Type *type = base_type(core_array_type(o->type));
  1492. gbString str = nullptr;
  1493. switch (op.kind) {
  1494. case Token_Add:
  1495. case Token_Sub:
  1496. if (!is_type_numeric(type)) {
  1497. str = expr_to_string(o->expr);
  1498. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1499. gb_string_free(str);
  1500. }
  1501. break;
  1502. case Token_Xor:
  1503. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1504. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1505. }
  1506. break;
  1507. case Token_Not:
  1508. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1509. ERROR_BLOCK();
  1510. str = expr_to_string(o->expr);
  1511. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1512. gb_string_free(str);
  1513. if (is_type_integer(type)) {
  1514. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1515. }
  1516. } else {
  1517. o->type = t_untyped_bool;
  1518. }
  1519. break;
  1520. default:
  1521. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1522. return false;
  1523. }
  1524. return true;
  1525. }
  1526. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1527. Type *main_type = o->type;
  1528. Type *type = base_type(core_array_type(main_type));
  1529. Type *ct = core_type(type);
  1530. switch (op.kind) {
  1531. case Token_Sub:
  1532. case Token_SubEq:
  1533. if (is_type_bit_set(type)) {
  1534. return true;
  1535. } else if (!is_type_numeric(type)) {
  1536. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1537. return false;
  1538. }
  1539. break;
  1540. case Token_Quo:
  1541. case Token_QuoEq:
  1542. if (is_type_matrix(main_type)) {
  1543. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1544. return false;
  1545. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1546. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1547. return false;
  1548. }
  1549. /*fallthrough*/
  1550. case Token_Mul:
  1551. case Token_MulEq:
  1552. case Token_AddEq:
  1553. if (is_type_bit_set(type)) {
  1554. return true;
  1555. } else if (!is_type_numeric(type)) {
  1556. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1557. return false;
  1558. }
  1559. break;
  1560. case Token_Add:
  1561. if (is_type_string(type)) {
  1562. if (o->mode == Addressing_Constant) {
  1563. return true;
  1564. }
  1565. error(op, "String concatenation is only allowed with constant strings");
  1566. return false;
  1567. } else if (is_type_bit_set(type)) {
  1568. return true;
  1569. } else if (!is_type_numeric(type)) {
  1570. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1571. return false;
  1572. }
  1573. break;
  1574. case Token_And:
  1575. case Token_Or:
  1576. case Token_AndEq:
  1577. case Token_OrEq:
  1578. case Token_Xor:
  1579. case Token_XorEq:
  1580. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1581. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1582. return false;
  1583. }
  1584. break;
  1585. case Token_Mod:
  1586. case Token_ModMod:
  1587. case Token_ModEq:
  1588. case Token_ModModEq:
  1589. if (is_type_matrix(main_type)) {
  1590. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1591. return false;
  1592. }
  1593. if (!is_type_integer(type)) {
  1594. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1595. return false;
  1596. } else if (is_type_simd_vector(main_type)) {
  1597. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1598. return false;
  1599. }
  1600. break;
  1601. case Token_AndNot:
  1602. case Token_AndNotEq:
  1603. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1604. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1605. return false;
  1606. }
  1607. break;
  1608. case Token_CmpAnd:
  1609. case Token_CmpOr:
  1610. case Token_CmpAndEq:
  1611. case Token_CmpOrEq:
  1612. if (!is_type_boolean(type)) {
  1613. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1614. return false;
  1615. }
  1616. break;
  1617. default:
  1618. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1619. return false;
  1620. }
  1621. return true;
  1622. }
  1623. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1624. if (in_value.kind == ExactValue_Invalid) {
  1625. // NOTE(bill): There's already been an error
  1626. return true;
  1627. }
  1628. type = core_type(type);
  1629. if (type == t_invalid) {
  1630. return false;
  1631. } else if (is_type_boolean(type)) {
  1632. return in_value.kind == ExactValue_Bool;
  1633. } else if (is_type_string(type)) {
  1634. return in_value.kind == ExactValue_String;
  1635. } else if (is_type_integer(type) || is_type_rune(type)) {
  1636. if (in_value.kind == ExactValue_Bool) {
  1637. return false;
  1638. }
  1639. ExactValue v = exact_value_to_integer(in_value);
  1640. if (v.kind != ExactValue_Integer) {
  1641. return false;
  1642. }
  1643. if (out_value) *out_value = v;
  1644. if (is_type_untyped(type)) {
  1645. return true;
  1646. }
  1647. BigInt i = v.value_integer;
  1648. i64 bit_size = type_size_of(type);
  1649. BigInt umax = {};
  1650. BigInt imin = {};
  1651. BigInt imax = {};
  1652. if (bit_size < 16) {
  1653. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1654. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1655. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1656. } else {
  1657. big_int_from_u64(&umax, 1);
  1658. big_int_from_i64(&imin, 1);
  1659. big_int_from_i64(&imax, 1);
  1660. BigInt bi128 = {};
  1661. BigInt bi127 = {};
  1662. big_int_from_i64(&bi128, 128);
  1663. big_int_from_i64(&bi127, 127);
  1664. big_int_shl_eq(&umax, &bi128);
  1665. mp_decr(&umax);
  1666. big_int_shl_eq(&imin, &bi127);
  1667. big_int_neg(&imin, &imin);
  1668. big_int_shl_eq(&imax, &bi127);
  1669. mp_decr(&imax);
  1670. }
  1671. switch (type->Basic.kind) {
  1672. case Basic_rune:
  1673. case Basic_i8:
  1674. case Basic_i16:
  1675. case Basic_i32:
  1676. case Basic_i64:
  1677. case Basic_i128:
  1678. case Basic_int:
  1679. case Basic_i16le:
  1680. case Basic_i32le:
  1681. case Basic_i64le:
  1682. case Basic_i128le:
  1683. case Basic_i16be:
  1684. case Basic_i32be:
  1685. case Basic_i64be:
  1686. case Basic_i128be:
  1687. {
  1688. // return imin <= i && i <= imax;
  1689. int a = big_int_cmp(&imin, &i);
  1690. int b = big_int_cmp(&i, &imax);
  1691. return (a <= 0) && (b <= 0);
  1692. }
  1693. case Basic_u8:
  1694. case Basic_u16:
  1695. case Basic_u32:
  1696. case Basic_u64:
  1697. case Basic_u128:
  1698. case Basic_uint:
  1699. case Basic_uintptr:
  1700. case Basic_u16le:
  1701. case Basic_u32le:
  1702. case Basic_u64le:
  1703. case Basic_u128le:
  1704. case Basic_u16be:
  1705. case Basic_u32be:
  1706. case Basic_u64be:
  1707. case Basic_u128be:
  1708. {
  1709. // return 0ull <= i && i <= umax;
  1710. int b = big_int_cmp(&i, &umax);
  1711. return !i.sign && (b <= 0);
  1712. }
  1713. case Basic_UntypedInteger:
  1714. return true;
  1715. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1716. }
  1717. } else if (is_type_float(type)) {
  1718. ExactValue v = exact_value_to_float(in_value);
  1719. if (v.kind != ExactValue_Float) {
  1720. return false;
  1721. }
  1722. if (out_value) *out_value = v;
  1723. switch (type->Basic.kind) {
  1724. case Basic_f16:
  1725. case Basic_f32:
  1726. case Basic_f64:
  1727. return true;
  1728. case Basic_f16le:
  1729. case Basic_f16be:
  1730. case Basic_f32le:
  1731. case Basic_f32be:
  1732. case Basic_f64le:
  1733. case Basic_f64be:
  1734. return true;
  1735. case Basic_UntypedFloat:
  1736. return true;
  1737. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1738. }
  1739. } else if (is_type_complex(type)) {
  1740. ExactValue v = exact_value_to_complex(in_value);
  1741. if (v.kind != ExactValue_Complex) {
  1742. return false;
  1743. }
  1744. switch (type->Basic.kind) {
  1745. case Basic_complex32:
  1746. case Basic_complex64:
  1747. case Basic_complex128: {
  1748. ExactValue real = exact_value_real(v);
  1749. ExactValue imag = exact_value_imag(v);
  1750. if (real.kind != ExactValue_Invalid &&
  1751. imag.kind != ExactValue_Invalid) {
  1752. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1753. return true;
  1754. }
  1755. break;
  1756. }
  1757. case Basic_UntypedComplex:
  1758. return true;
  1759. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1760. }
  1761. return false;
  1762. } else if (is_type_quaternion(type)) {
  1763. ExactValue v = exact_value_to_quaternion(in_value);
  1764. if (v.kind != ExactValue_Quaternion) {
  1765. return false;
  1766. }
  1767. switch (type->Basic.kind) {
  1768. case Basic_quaternion64:
  1769. case Basic_quaternion128:
  1770. case Basic_quaternion256: {
  1771. ExactValue real = exact_value_real(v);
  1772. ExactValue imag = exact_value_imag(v);
  1773. ExactValue jmag = exact_value_jmag(v);
  1774. ExactValue kmag = exact_value_kmag(v);
  1775. if (real.kind != ExactValue_Invalid &&
  1776. imag.kind != ExactValue_Invalid) {
  1777. if (out_value) *out_value = exact_value_quaternion(exact_value_to_f64(real), exact_value_to_f64(imag), exact_value_to_f64(jmag), exact_value_to_f64(kmag));
  1778. return true;
  1779. }
  1780. break;
  1781. }
  1782. case Basic_UntypedComplex:
  1783. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1784. return true;
  1785. case Basic_UntypedQuaternion:
  1786. return true;
  1787. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1788. }
  1789. return false;
  1790. } else if (is_type_pointer(type)) {
  1791. if (in_value.kind == ExactValue_Pointer) {
  1792. return true;
  1793. }
  1794. if (in_value.kind == ExactValue_Integer) {
  1795. return false;
  1796. // return true;
  1797. }
  1798. if (in_value.kind == ExactValue_String) {
  1799. return false;
  1800. }
  1801. if (out_value) *out_value = in_value;
  1802. } else if (is_type_bit_set(type)) {
  1803. if (in_value.kind == ExactValue_Integer) {
  1804. return true;
  1805. }
  1806. }
  1807. return false;
  1808. }
  1809. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1810. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1811. gbString b = type_to_string(type);
  1812. i64 sz = type_size_of(type);
  1813. BigInt *bi = &o->value.value_integer;
  1814. if (is_type_unsigned(type)) {
  1815. if (big_int_is_neg(bi)) {
  1816. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1817. } else {
  1818. BigInt one = big_int_make_u64(1);
  1819. BigInt max_size = big_int_make_u64(1);
  1820. BigInt bits = big_int_make_i64(8*sz);
  1821. big_int_shl_eq(&max_size, &bits);
  1822. big_int_sub_eq(&max_size, &one);
  1823. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1824. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1825. }
  1826. } else {
  1827. BigInt zero = big_int_make_u64(0);
  1828. BigInt one = big_int_make_u64(1);
  1829. BigInt max_size = big_int_make_u64(1);
  1830. BigInt bits = big_int_make_i64(8*sz - 1);
  1831. big_int_shl_eq(&max_size, &bits);
  1832. if (big_int_is_neg(bi)) {
  1833. big_int_neg(&max_size, &max_size);
  1834. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1835. error_line("\tThe minimum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1836. } else {
  1837. big_int_sub_eq(&max_size, &one);
  1838. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1839. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1840. }
  1841. }
  1842. gb_string_free(b);
  1843. return true;
  1844. }
  1845. return false;
  1846. }
  1847. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1848. gbString a = expr_to_string(o->expr);
  1849. gbString b = type_to_string(type);
  1850. defer(
  1851. gb_string_free(b);
  1852. gb_string_free(a);
  1853. );
  1854. Type *src = base_type(o->type);
  1855. Type *dst = base_type(type);
  1856. if (is_type_array(src) && is_type_slice(dst)) {
  1857. Type *s = src->Array.elem;
  1858. Type *d = dst->Slice.elem;
  1859. if (are_types_identical(s, d)) {
  1860. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1861. }
  1862. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1863. Type *s = src->DynamicArray.elem;
  1864. Type *d = dst->Slice.elem;
  1865. if (are_types_identical(s, d)) {
  1866. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1867. }
  1868. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1869. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1870. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1871. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1872. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1873. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1874. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1875. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1876. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1877. return;
  1878. }
  1879. }
  1880. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1881. gbString a = expr_to_string(o->expr);
  1882. gbString b = type_to_string(type);
  1883. defer(
  1884. gb_string_free(b);
  1885. gb_string_free(a);
  1886. );
  1887. Type *src = base_type(o->type);
  1888. Type *dst = base_type(type);
  1889. if (is_type_array(src) && is_type_slice(dst)) {
  1890. Type *s = src->Array.elem;
  1891. Type *d = dst->Slice.elem;
  1892. if (are_types_identical(s, d)) {
  1893. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1894. }
  1895. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1896. if (is_type_uintptr(type)) {
  1897. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1898. } else {
  1899. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1900. i64 x = type_size_of(o->type);
  1901. i64 y = type_size_of(type);
  1902. if (x != y) {
  1903. error_line("\tNote: the type of expression and the type of the cast have a different size in bytes, %lld vs %lld\n", x, y);
  1904. }
  1905. }
  1906. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  1907. if (is_type_uintptr(o->type)) {
  1908. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  1909. } else {
  1910. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  1911. }
  1912. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1913. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1914. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1915. return;
  1916. }
  1917. }
  1918. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  1919. GB_ASSERT(o->mode == Addressing_Constant);
  1920. ExactValue out_value = o->value;
  1921. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  1922. o->value = out_value;
  1923. return true;
  1924. } else {
  1925. o->value = out_value;
  1926. gbString a = expr_to_string(o->expr);
  1927. gbString b = type_to_string(type);
  1928. gbString c = type_to_string(o->type);
  1929. gbString s = exact_value_to_string(o->value);
  1930. defer(
  1931. gb_string_free(s);
  1932. gb_string_free(c);
  1933. gb_string_free(b);
  1934. gb_string_free(a);
  1935. o->mode = Addressing_Invalid;
  1936. );
  1937. ERROR_BLOCK();
  1938. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1939. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1940. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  1941. } else {
  1942. if (are_types_identical(o->type, type)) {
  1943. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  1944. } else {
  1945. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  1946. }
  1947. check_assignment_error_suggestion(ctx, o, type);
  1948. }
  1949. } else {
  1950. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  1951. check_assignment_error_suggestion(ctx, o, type);
  1952. }
  1953. return false;
  1954. }
  1955. }
  1956. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1957. if (o->mode == Addressing_OptionalOk) {
  1958. Ast *expr = unselector_expr(o->expr);
  1959. if (expr->kind != Ast_TypeAssertion) {
  1960. return true;
  1961. }
  1962. ast_node(ta, TypeAssertion, expr);
  1963. TypeAndValue tv = ta->expr->tav;
  1964. if (is_type_pointer(tv.type)) {
  1965. return false;
  1966. }
  1967. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1968. return false;
  1969. }
  1970. if (is_type_any(tv.type)) {
  1971. return false;
  1972. }
  1973. return true;
  1974. }
  1975. if (o->mode == Addressing_MapIndex) {
  1976. return false;
  1977. }
  1978. Ast *expr = unparen_expr(o->expr);
  1979. if (expr->kind == Ast_CompoundLit) {
  1980. return false;
  1981. }
  1982. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  1983. }
  1984. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  1985. if (!(build_context.strict_style || (check_vet_flags(expr) & VetFlag_Style))) {
  1986. return;
  1987. }
  1988. Entity *e = entity_of_node(expr);
  1989. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  1990. GB_ASSERT(e->kind == Entity_Variable);
  1991. ERROR_BLOCK();
  1992. if ((e->flags & EntityFlag_ForValue) != 0) {
  1993. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  1994. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  1995. if (is_type_map(parent_type)) {
  1996. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  1997. } else {
  1998. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  1999. }
  2000. } else {
  2001. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  2002. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  2003. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2004. }
  2005. }
  2006. }
  2007. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2008. switch (op.kind) {
  2009. case Token_And: { // Pointer address
  2010. if (check_is_not_addressable(c, o)) {
  2011. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2012. ast_node(ue, UnaryExpr, node);
  2013. gbString str = expr_to_string(ue->expr);
  2014. defer (gb_string_free(str));
  2015. Entity *e = entity_of_node(ue->expr);
  2016. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2017. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2018. } else {
  2019. switch (o->mode) {
  2020. case Addressing_Constant:
  2021. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2022. break;
  2023. case Addressing_SwizzleValue:
  2024. case Addressing_SwizzleVariable:
  2025. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2026. break;
  2027. default:
  2028. {
  2029. ERROR_BLOCK();
  2030. error(op, "Cannot take the pointer address of '%s'", str);
  2031. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2032. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2033. if (parent_type != nullptr && is_type_string(parent_type)) {
  2034. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2035. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2036. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2037. } else {
  2038. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2039. }
  2040. }
  2041. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2042. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2043. }
  2044. }
  2045. break;
  2046. }
  2047. }
  2048. }
  2049. o->mode = Addressing_Invalid;
  2050. return;
  2051. }
  2052. if (o->mode == Addressing_SoaVariable) {
  2053. ast_node(ue, UnaryExpr, node);
  2054. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2055. ast_node(ie, IndexExpr, ue->expr);
  2056. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2057. GB_ASSERT(is_type_soa_struct(soa_type));
  2058. o->type = alloc_type_soa_pointer(soa_type);
  2059. } else {
  2060. o->type = alloc_type_pointer(o->type);
  2061. }
  2062. } else {
  2063. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2064. ast_node(ue, UnaryExpr, node);
  2065. check_old_for_or_switch_value_usage(ue->expr);
  2066. }
  2067. o->type = alloc_type_pointer(o->type);
  2068. }
  2069. switch (o->mode) {
  2070. case Addressing_OptionalOk:
  2071. case Addressing_MapIndex:
  2072. o->mode = Addressing_OptionalOkPtr;
  2073. break;
  2074. default:
  2075. o->mode = Addressing_Value;
  2076. break;
  2077. }
  2078. return;
  2079. }
  2080. }
  2081. if (!check_unary_op(c, o, op)) {
  2082. o->mode = Addressing_Invalid;
  2083. return;
  2084. }
  2085. if (o->mode == Addressing_Constant) {
  2086. Type *type = base_type(o->type);
  2087. if (!is_type_constant_type(o->type)) {
  2088. gbString xt = type_to_string(o->type);
  2089. gbString err_str = expr_to_string(node);
  2090. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2091. gb_string_free(err_str);
  2092. gb_string_free(xt);
  2093. o->mode = Addressing_Invalid;
  2094. return;
  2095. }
  2096. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2097. gbString err_str = expr_to_string(node);
  2098. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2099. gb_string_free(err_str);
  2100. o->mode = Addressing_Invalid;
  2101. return;
  2102. }
  2103. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2104. gbString err_str = expr_to_string(node);
  2105. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2106. gb_string_free(err_str);
  2107. o->mode = Addressing_Invalid;
  2108. return;
  2109. }
  2110. i32 precision = 0;
  2111. if (is_type_typed(type)) {
  2112. precision = cast(i32)(8 * type_size_of(type));
  2113. }
  2114. bool is_unsigned = is_type_unsigned(type);
  2115. if (is_type_rune(type)) {
  2116. GB_ASSERT(!is_unsigned);
  2117. }
  2118. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2119. if (is_type_typed(type)) {
  2120. if (node != nullptr) {
  2121. o->expr = node;
  2122. }
  2123. check_is_expressible(c, o, type);
  2124. }
  2125. return;
  2126. }
  2127. o->mode = Addressing_Value;
  2128. }
  2129. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2130. if (t == nullptr) {
  2131. return;
  2132. }
  2133. t = base_type(t);
  2134. if (!is_type_comparable(t)) {
  2135. return;
  2136. }
  2137. switch (t->kind) {
  2138. case Type_Basic:
  2139. switch (t->Basic.kind) {
  2140. case Basic_complex32:
  2141. add_package_dependency(c, "runtime", "complex32_eq");
  2142. add_package_dependency(c, "runtime", "complex32_ne");
  2143. break;
  2144. case Basic_complex64:
  2145. add_package_dependency(c, "runtime", "complex64_eq");
  2146. add_package_dependency(c, "runtime", "complex64_ne");
  2147. break;
  2148. case Basic_complex128:
  2149. add_package_dependency(c, "runtime", "complex128_eq");
  2150. add_package_dependency(c, "runtime", "complex128_ne");
  2151. break;
  2152. case Basic_quaternion64:
  2153. add_package_dependency(c, "runtime", "quaternion64_eq");
  2154. add_package_dependency(c, "runtime", "quaternion64_ne");
  2155. break;
  2156. case Basic_quaternion128:
  2157. add_package_dependency(c, "runtime", "quaternion128_eq");
  2158. add_package_dependency(c, "runtime", "quaternion128_ne");
  2159. break;
  2160. case Basic_quaternion256:
  2161. add_package_dependency(c, "runtime", "quaternion256_eq");
  2162. add_package_dependency(c, "runtime", "quaternion256_ne");
  2163. break;
  2164. case Basic_cstring:
  2165. add_package_dependency(c, "runtime", "cstring_eq");
  2166. add_package_dependency(c, "runtime", "cstring_ne");
  2167. break;
  2168. case Basic_string:
  2169. add_package_dependency(c, "runtime", "string_eq");
  2170. add_package_dependency(c, "runtime", "string_ne");
  2171. break;
  2172. }
  2173. break;
  2174. case Type_Struct:
  2175. for (Entity *field : t->Struct.fields) {
  2176. add_comparison_procedures_for_fields(c, field->type);
  2177. }
  2178. break;
  2179. }
  2180. }
  2181. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2182. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2183. bool comp = are_types_identical(x->type, y->type);
  2184. switch (op) {
  2185. case Token_CmpEq: /* comp = comp; */ break;
  2186. case Token_NotEq: comp = !comp; break;
  2187. }
  2188. x->mode = Addressing_Constant;
  2189. x->type = t_untyped_bool;
  2190. x->value = exact_value_bool(comp);
  2191. return;
  2192. }
  2193. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2194. add_type_info_type(c, x->type);
  2195. add_type_info_type(c, y->type);
  2196. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2197. x->mode = Addressing_Value;
  2198. x->type = t_untyped_bool;
  2199. return;
  2200. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2201. add_type_info_type(c, x->type);
  2202. add_type_info_type(c, y->type);
  2203. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2204. x->mode = Addressing_Value;
  2205. x->type = t_untyped_bool;
  2206. return;
  2207. }
  2208. TEMPORARY_ALLOCATOR_GUARD();
  2209. gbString err_str = nullptr;
  2210. if (check_is_assignable_to(c, x, y->type) ||
  2211. check_is_assignable_to(c, y, x->type)) {
  2212. Type *err_type = x->type;
  2213. bool defined = false;
  2214. switch (op) {
  2215. case Token_CmpEq:
  2216. case Token_NotEq:
  2217. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2218. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2219. (is_operand_nil(*y) && type_has_nil(x->type));
  2220. break;
  2221. case Token_Lt:
  2222. case Token_Gt:
  2223. case Token_LtEq:
  2224. case Token_GtEq:
  2225. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2226. defined = true;
  2227. } else {
  2228. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2229. }
  2230. break;
  2231. }
  2232. if (!defined) {
  2233. gbString xs = type_to_string(x->type, temporary_allocator());
  2234. gbString ys = type_to_string(y->type, temporary_allocator());
  2235. err_str = gb_string_make(temporary_allocator(),
  2236. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2237. );
  2238. } else {
  2239. Type *comparison_type = x->type;
  2240. if (x->type == err_type && is_operand_nil(*x)) {
  2241. comparison_type = y->type;
  2242. }
  2243. add_comparison_procedures_for_fields(c, comparison_type);
  2244. }
  2245. } else {
  2246. gbString xt, yt;
  2247. if (x->mode == Addressing_ProcGroup) {
  2248. xt = gb_string_make(temporary_allocator(), "procedure group");
  2249. } else {
  2250. xt = type_to_string(x->type);
  2251. }
  2252. if (y->mode == Addressing_ProcGroup) {
  2253. yt = gb_string_make(temporary_allocator(), "procedure group");
  2254. } else {
  2255. yt = type_to_string(y->type);
  2256. }
  2257. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2258. }
  2259. if (err_str != nullptr) {
  2260. error(node, "Cannot compare expression, %s", err_str);
  2261. x->type = t_untyped_bool;
  2262. } else {
  2263. if (x->mode == Addressing_Constant &&
  2264. y->mode == Addressing_Constant) {
  2265. if (is_type_constant_type(x->type)) {
  2266. if (is_type_bit_set(x->type)) {
  2267. switch (op) {
  2268. case Token_CmpEq:
  2269. case Token_NotEq:
  2270. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2271. break;
  2272. case Token_Lt:
  2273. case Token_LtEq:
  2274. {
  2275. ExactValue lhs = x->value;
  2276. ExactValue rhs = y->value;
  2277. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2278. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2279. if (op == Token_Lt) {
  2280. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2281. }
  2282. x->value = res;
  2283. break;
  2284. }
  2285. case Token_Gt:
  2286. case Token_GtEq:
  2287. {
  2288. ExactValue lhs = x->value;
  2289. ExactValue rhs = y->value;
  2290. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2291. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2292. if (op == Token_Gt) {
  2293. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2294. }
  2295. x->value = res;
  2296. break;
  2297. }
  2298. }
  2299. } else {
  2300. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2301. }
  2302. } else {
  2303. x->mode = Addressing_Value;
  2304. }
  2305. } else {
  2306. x->mode = Addressing_Value;
  2307. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2308. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2309. i64 size = 0;
  2310. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2311. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2312. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2313. switch (op) {
  2314. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2315. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2316. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2317. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2318. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2319. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2320. }
  2321. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2322. switch (op) {
  2323. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2324. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2325. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2326. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2327. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2328. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2329. }
  2330. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2331. switch (op) {
  2332. case Token_CmpEq:
  2333. switch (8*size) {
  2334. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2335. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2336. }
  2337. break;
  2338. case Token_NotEq:
  2339. switch (8*size) {
  2340. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2341. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2342. }
  2343. break;
  2344. }
  2345. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2346. switch (op) {
  2347. case Token_CmpEq:
  2348. switch (8*size) {
  2349. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2350. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2351. }
  2352. break;
  2353. case Token_NotEq:
  2354. switch (8*size) {
  2355. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2356. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2357. }
  2358. break;
  2359. }
  2360. }
  2361. }
  2362. x->type = t_untyped_bool;
  2363. }
  2364. }
  2365. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2366. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2367. ast_node(be, BinaryExpr, node);
  2368. ExactValue x_val = {};
  2369. if (x->mode == Addressing_Constant) {
  2370. x_val = exact_value_to_integer(x->value);
  2371. }
  2372. bool x_is_untyped = is_type_untyped(x->type);
  2373. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2374. gbString err_str = expr_to_string(x->expr);
  2375. error(node, "Shifted operand '%s' must be an integer", err_str);
  2376. gb_string_free(err_str);
  2377. x->mode = Addressing_Invalid;
  2378. return;
  2379. }
  2380. if (is_type_unsigned(y->type)) {
  2381. } else if (is_type_untyped(y->type)) {
  2382. convert_to_typed(c, y, t_untyped_integer);
  2383. if (y->mode == Addressing_Invalid) {
  2384. x->mode = Addressing_Invalid;
  2385. return;
  2386. }
  2387. } else {
  2388. gbString err_str = expr_to_string(y->expr);
  2389. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2390. gb_string_free(err_str);
  2391. x->mode = Addressing_Invalid;
  2392. return;
  2393. }
  2394. if (x->mode == Addressing_Constant) {
  2395. if (y->mode == Addressing_Constant) {
  2396. ExactValue y_val = exact_value_to_integer(y->value);
  2397. if (y_val.kind != ExactValue_Integer) {
  2398. gbString err_str = expr_to_string(y->expr);
  2399. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2400. gb_string_free(err_str);
  2401. x->mode = Addressing_Invalid;
  2402. return;
  2403. }
  2404. BigInt max_shift = {};
  2405. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2406. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2407. gbString err_str = expr_to_string(y->expr);
  2408. error(node, "Shift amount too large: '%s'", err_str);
  2409. gb_string_free(err_str);
  2410. x->mode = Addressing_Invalid;
  2411. return;
  2412. }
  2413. if (!is_type_integer(x->type)) {
  2414. // NOTE(bill): It could be an untyped float but still representable
  2415. // as an integer
  2416. x->type = t_untyped_integer;
  2417. }
  2418. x->expr = node;
  2419. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2420. if (is_type_typed(x->type)) {
  2421. check_is_expressible(c, x, x->type);
  2422. }
  2423. return;
  2424. }
  2425. TokenPos pos = ast_token(x->expr).pos;
  2426. if (x_is_untyped) {
  2427. if (x->expr != nullptr) {
  2428. x->expr->tav.is_lhs = true;
  2429. }
  2430. x->mode = Addressing_Value;
  2431. if (type_hint) {
  2432. if (is_type_integer(type_hint)) {
  2433. x->type = type_hint;
  2434. } else {
  2435. gbString x_str = expr_to_string(x->expr);
  2436. gbString to_type = type_to_string(type_hint);
  2437. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2438. gb_string_free(x_str);
  2439. gb_string_free(to_type);
  2440. x->mode = Addressing_Invalid;
  2441. }
  2442. } else if (!is_type_integer(x->type)) {
  2443. gbString x_str = expr_to_string(x->expr);
  2444. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2445. gb_string_free(x_str);
  2446. x->mode = Addressing_Invalid;
  2447. }
  2448. // x->value = x_val;
  2449. return;
  2450. }
  2451. }
  2452. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2453. gbString err_str = expr_to_string(y->expr);
  2454. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2455. gb_string_free(err_str);
  2456. }
  2457. if (!is_type_integer(x->type)) {
  2458. gbString err_str = expr_to_string(x->expr);
  2459. error(node, "Shift operand '%s' must be an integer", err_str);
  2460. gb_string_free(err_str);
  2461. x->mode = Addressing_Invalid;
  2462. return;
  2463. }
  2464. if (is_type_untyped(y->type)) {
  2465. convert_to_typed(c, y, t_uint);
  2466. }
  2467. x->mode = Addressing_Value;
  2468. }
  2469. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2470. if (check_is_assignable_to(c, operand, y)) {
  2471. return true;
  2472. }
  2473. bool is_constant = operand->mode == Addressing_Constant;
  2474. Type *x = operand->type;
  2475. Type *src = core_type(x);
  2476. Type *dst = core_type(y);
  2477. if (are_types_identical(src, dst)) {
  2478. return true;
  2479. }
  2480. // if (is_type_tuple(src)) {
  2481. // Ast *expr = unparen_expr(operand->expr);
  2482. // if (expr && expr->kind == Ast_CallExpr) {
  2483. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2484. // ast_node(ce, CallExpr, expr);
  2485. // Type *pt = base_type(type_of_expr(ce->proc));
  2486. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2487. // if (pt->Proc.result_count > 0) {
  2488. // Operand op = *operand;
  2489. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2490. // bool ok = check_is_castable_to(c, &op, y);
  2491. // if (ok) {
  2492. // ce->optional_ok_one = true;
  2493. // }
  2494. // return ok;
  2495. // }
  2496. // }
  2497. // }
  2498. // }
  2499. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2500. if (is_type_u8_array(dst)) {
  2501. String s = operand->value.value_string;
  2502. return s.len == dst->Array.count;
  2503. }
  2504. if (is_type_rune_array(dst)) {
  2505. String s = operand->value.value_string;
  2506. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2507. }
  2508. }
  2509. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2510. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2511. return dst->Array.count == src->Array.count;
  2512. }
  2513. }
  2514. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2515. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2516. }
  2517. // Cast between booleans and integers
  2518. if (is_type_boolean(src) || is_type_integer(src)) {
  2519. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2520. return true;
  2521. }
  2522. }
  2523. // Cast between numbers
  2524. if (is_type_integer(src) || is_type_float(src)) {
  2525. if (is_type_integer(dst) || is_type_float(dst)) {
  2526. return true;
  2527. }
  2528. }
  2529. if (is_type_integer(src) && is_type_rune(dst)) {
  2530. return true;
  2531. }
  2532. if (is_type_rune(src) && is_type_integer(dst)) {
  2533. return true;
  2534. }
  2535. if (is_type_complex(src) && is_type_complex(dst)) {
  2536. return true;
  2537. }
  2538. if (is_type_float(src) && is_type_complex(dst)) {
  2539. return true;
  2540. }
  2541. if (is_type_float(src) && is_type_quaternion(dst)) {
  2542. return true;
  2543. }
  2544. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2545. return true;
  2546. }
  2547. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2548. return true;
  2549. }
  2550. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2551. GB_ASSERT(src->kind == Type_Matrix);
  2552. GB_ASSERT(dst->kind == Type_Matrix);
  2553. Operand op = *operand;
  2554. op.type = src->Matrix.elem;
  2555. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2556. return false;
  2557. }
  2558. if (src->Matrix.row_count != src->Matrix.column_count) {
  2559. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2560. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2561. return src_count == dst_count;
  2562. }
  2563. return is_matrix_square(dst) && is_matrix_square(src);
  2564. }
  2565. // Cast between pointers
  2566. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2567. return true;
  2568. }
  2569. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2570. return true;
  2571. }
  2572. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2573. return true;
  2574. }
  2575. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2576. return true;
  2577. }
  2578. // uintptr <-> pointer
  2579. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2580. return true;
  2581. }
  2582. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2583. return true;
  2584. }
  2585. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2586. return true;
  2587. }
  2588. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2589. return true;
  2590. }
  2591. // []byte/[]u8 <-> string (not cstring)
  2592. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2593. return true;
  2594. }
  2595. // cstring -> string
  2596. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2597. if (operand->mode != Addressing_Constant) {
  2598. add_package_dependency(c, "runtime", "cstring_to_string");
  2599. }
  2600. return true;
  2601. }
  2602. // cstring -> ^u8
  2603. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2604. return !is_constant;
  2605. }
  2606. // cstring -> [^]u8
  2607. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2608. return !is_constant;
  2609. }
  2610. // cstring -> rawptr
  2611. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2612. return !is_constant;
  2613. }
  2614. // ^u8 -> cstring
  2615. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2616. return !is_constant;
  2617. }
  2618. // [^]u8 -> cstring
  2619. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2620. return !is_constant;
  2621. }
  2622. // rawptr -> cstring
  2623. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2624. return !is_constant;
  2625. }
  2626. // proc <-> proc
  2627. if (is_type_proc(src) && is_type_proc(dst)) {
  2628. if (is_type_polymorphic(dst)) {
  2629. if (is_type_polymorphic(src) &&
  2630. operand->mode == Addressing_Variable) {
  2631. return true;
  2632. }
  2633. return false;
  2634. }
  2635. return true;
  2636. }
  2637. // proc -> rawptr
  2638. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2639. return true;
  2640. }
  2641. // rawptr -> proc
  2642. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2643. return true;
  2644. }
  2645. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2646. if (src->SimdVector.count != dst->SimdVector.count) {
  2647. return false;
  2648. }
  2649. Type *elem_src = base_array_type(src);
  2650. Type *elem_dst = base_array_type(dst);
  2651. Operand x = {};
  2652. x.type = elem_src;
  2653. x.mode = Addressing_Value;
  2654. return check_is_castable_to(c, &x, elem_dst);
  2655. }
  2656. if (is_type_simd_vector(dst)) {
  2657. Type *elem = base_array_type(dst);
  2658. if (check_is_castable_to(c, operand, elem)) {
  2659. return true;
  2660. }
  2661. }
  2662. return false;
  2663. }
  2664. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2665. bool is_const_expr = x->mode == Addressing_Constant;
  2666. Type *bt = base_type(type);
  2667. if (is_const_expr && is_type_constant_type(bt)) {
  2668. if (core_type(bt)->kind == Type_Basic) {
  2669. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2670. return true;
  2671. } else if (check_is_castable_to(c, x, type)) {
  2672. if (is_type_pointer(type)) {
  2673. return true;
  2674. }
  2675. }
  2676. } else if (check_is_castable_to(c, x, type)) {
  2677. x->value = {};
  2678. x->mode = Addressing_Value;
  2679. return true;
  2680. }
  2681. } else if (check_is_castable_to(c, x, type)) {
  2682. if (x->mode != Addressing_Constant) {
  2683. x->mode = Addressing_Value;
  2684. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2685. x->mode = Addressing_Value;
  2686. } else if (is_type_union(type)) {
  2687. x->mode = Addressing_Value;
  2688. }
  2689. if (x->mode == Addressing_Value) {
  2690. x->value = {};
  2691. }
  2692. return true;
  2693. }
  2694. return false;
  2695. }
  2696. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2697. if (!is_operand_value(*x)) {
  2698. error(x->expr, "Only values can be casted");
  2699. x->mode = Addressing_Invalid;
  2700. return;
  2701. }
  2702. bool is_const_expr = x->mode == Addressing_Constant;
  2703. bool can_convert = check_cast_internal(c, x, type);
  2704. if (!can_convert) {
  2705. TEMPORARY_ALLOCATOR_GUARD();
  2706. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2707. gbString to_type = type_to_string(type, temporary_allocator());
  2708. gbString from_type = type_to_string(x->type, temporary_allocator());
  2709. x->mode = Addressing_Invalid;
  2710. ERROR_BLOCK();
  2711. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2712. if (is_const_expr) {
  2713. gbString val_str = exact_value_to_string(x->value);
  2714. if (is_type_float(x->type) && is_type_integer(type)) {
  2715. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2716. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2717. x->mode = Addressing_Constant;
  2718. x->type = type;
  2719. } else {
  2720. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2721. if (is_type_numeric(type)) {
  2722. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2723. x->mode = Addressing_Constant;
  2724. x->type = type;
  2725. }
  2726. }
  2727. gb_string_free(val_str);
  2728. }
  2729. check_cast_error_suggestion(c, x, type);
  2730. return;
  2731. }
  2732. if (is_type_untyped(x->type)) {
  2733. Type *final_type = type;
  2734. if (is_const_expr && !is_type_constant_type(type)) {
  2735. final_type = default_type(x->type);
  2736. }
  2737. update_untyped_expr_type(c, x->expr, final_type, true);
  2738. } else {
  2739. Type *src = core_type(x->type);
  2740. Type *dst = core_type(type);
  2741. if (src != dst) {
  2742. bool const REQUIRE = true;
  2743. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  2744. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  2745. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  2746. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  2747. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  2748. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  2749. } else if (src == t_f16 && is_type_float(dst)) {
  2750. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  2751. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  2752. } else if (is_type_float(dst) && dst == t_f16) {
  2753. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  2754. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  2755. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  2756. }
  2757. }
  2758. }
  2759. x->type = type;
  2760. }
  2761. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2762. if (!is_operand_value(*o)) {
  2763. error(o->expr, "'transmute' can only be applied to values");
  2764. o->mode = Addressing_Invalid;
  2765. return false;
  2766. }
  2767. // if (o->mode == Addressing_Constant) {
  2768. // gbString expr_str = expr_to_string(o->expr);
  2769. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2770. // gb_string_free(expr_str);
  2771. // o->mode = Addressing_Invalid;
  2772. // o->expr = node;
  2773. // return false;
  2774. // }
  2775. Type *src_t = o->type;
  2776. Type *dst_t = t;
  2777. Type *src_bt = base_type(src_t);
  2778. Type *dst_bt = base_type(dst_t);
  2779. if (is_type_untyped(src_t)) {
  2780. gbString expr_str = expr_to_string(o->expr);
  2781. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2782. gb_string_free(expr_str);
  2783. o->mode = Addressing_Invalid;
  2784. o->expr = node;
  2785. return false;
  2786. }
  2787. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2788. GB_ASSERT(global_error_collector.count != 0);
  2789. o->mode = Addressing_Invalid;
  2790. o->expr = node;
  2791. return false;
  2792. }
  2793. if (src_bt == nullptr || src_bt == t_invalid) {
  2794. // NOTE(bill): this should be an error
  2795. GB_ASSERT(global_error_collector.count != 0);
  2796. o->mode = Addressing_Value;
  2797. o->expr = node;
  2798. o->type = dst_t;
  2799. return true;
  2800. }
  2801. i64 srcz = type_size_of(src_t);
  2802. i64 dstz = type_size_of(dst_t);
  2803. if (srcz != dstz) {
  2804. gbString expr_str = expr_to_string(o->expr);
  2805. gbString type_str = type_to_string(dst_t);
  2806. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2807. gb_string_free(type_str);
  2808. gb_string_free(expr_str);
  2809. o->mode = Addressing_Invalid;
  2810. o->expr = node;
  2811. return false;
  2812. }
  2813. o->expr = node;
  2814. o->type = dst_t;
  2815. if (o->mode == Addressing_Constant) {
  2816. if (are_types_identical(src_bt, dst_bt)) {
  2817. return true;
  2818. }
  2819. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2820. if (types_have_same_internal_endian(src_t, dst_t)) {
  2821. ExactValue src_v = exact_value_to_integer(o->value);
  2822. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2823. BigInt v = src_v.value_integer;
  2824. BigInt smax = {};
  2825. BigInt umax = {};
  2826. big_int_from_u64(&smax, 0);
  2827. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2828. big_int_from_u64(&umax, 1);
  2829. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2830. big_int_shl_eq(&umax, &sz_in_bits);
  2831. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2832. if (big_int_cmp(&v, &smax) >= 0) {
  2833. big_int_sub_eq(&v, &umax);
  2834. }
  2835. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2836. if (big_int_is_neg(&v)) {
  2837. big_int_add_eq(&v, &umax);
  2838. }
  2839. }
  2840. o->value.kind = ExactValue_Integer;
  2841. o->value.value_integer = v;
  2842. return true;
  2843. }
  2844. }
  2845. }
  2846. o->mode = Addressing_Value;
  2847. o->value = {};
  2848. return true;
  2849. }
  2850. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2851. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2852. if (check_is_assignable_to(c, y, x->type)) {
  2853. if (check_binary_op(c, x, op)) {
  2854. return true;
  2855. }
  2856. }
  2857. }
  2858. return false;
  2859. }
  2860. gb_internal bool is_ise_expr(Ast *node) {
  2861. node = unparen_expr(node);
  2862. return node->kind == Ast_ImplicitSelectorExpr;
  2863. }
  2864. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2865. if (use_lhs_as_type_hint) { // RHS in this case
  2866. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2867. }
  2868. return false;
  2869. }
  2870. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2871. Type *xt = base_type(matrix);
  2872. if (type_hint != nullptr) {
  2873. Type *th = base_type(type_hint);
  2874. if (are_types_identical(th, xt)) {
  2875. return type_hint;
  2876. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2877. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2878. // ignore
  2879. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2880. return type_hint;
  2881. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2882. return type_hint;
  2883. }
  2884. }
  2885. }
  2886. return matrix;
  2887. }
  2888. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2889. if (!check_binary_op(c, x, op)) {
  2890. x->mode = Addressing_Invalid;
  2891. return;
  2892. }
  2893. Type *xt = base_type(x->type);
  2894. Type *yt = base_type(y->type);
  2895. if (is_type_matrix(x->type)) {
  2896. GB_ASSERT(xt->kind == Type_Matrix);
  2897. if (op.kind == Token_Mul) {
  2898. if (yt->kind == Type_Matrix) {
  2899. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2900. goto matrix_error;
  2901. }
  2902. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2903. goto matrix_error;
  2904. }
  2905. x->mode = Addressing_Value;
  2906. if (are_types_identical(xt, yt)) {
  2907. if (!is_type_named(x->type) && is_type_named(y->type)) {
  2908. // prefer the named type
  2909. x->type = y->type;
  2910. }
  2911. } else {
  2912. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2913. }
  2914. goto matrix_success;
  2915. } else if (yt->kind == Type_Array) {
  2916. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2917. goto matrix_error;
  2918. }
  2919. if (xt->Matrix.column_count != yt->Array.count) {
  2920. goto matrix_error;
  2921. }
  2922. // Treat arrays as column vectors
  2923. x->mode = Addressing_Value;
  2924. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2925. x->type = y->type;
  2926. } else {
  2927. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2928. }
  2929. goto matrix_success;
  2930. }
  2931. }
  2932. if (!are_types_identical(xt, yt)) {
  2933. goto matrix_error;
  2934. }
  2935. x->mode = Addressing_Value;
  2936. x->type = xt;
  2937. goto matrix_success;
  2938. } else {
  2939. GB_ASSERT(!is_type_matrix(xt));
  2940. GB_ASSERT(is_type_matrix(yt));
  2941. if (op.kind == Token_Mul) {
  2942. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2943. if (xt->kind == Type_Array) {
  2944. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2945. goto matrix_error;
  2946. }
  2947. if (xt->Array.count != yt->Matrix.row_count) {
  2948. goto matrix_error;
  2949. }
  2950. // Treat arrays as row vectors
  2951. x->mode = Addressing_Value;
  2952. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2953. x->type = x->type;
  2954. } else {
  2955. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2956. }
  2957. goto matrix_success;
  2958. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  2959. x->type = check_matrix_type_hint(y->type, type_hint);
  2960. return;
  2961. }
  2962. }
  2963. if (!are_types_identical(xt, yt)) {
  2964. goto matrix_error;
  2965. }
  2966. x->mode = Addressing_Value;
  2967. x->type = xt;
  2968. goto matrix_success;
  2969. }
  2970. matrix_success:
  2971. x->type = check_matrix_type_hint(x->type, type_hint);
  2972. return;
  2973. matrix_error:
  2974. gbString xts = type_to_string(x->type);
  2975. gbString yts = type_to_string(y->type);
  2976. gbString expr_str = expr_to_string(x->expr);
  2977. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2978. gb_string_free(expr_str);
  2979. gb_string_free(yts);
  2980. gb_string_free(xts);
  2981. x->type = t_invalid;
  2982. x->mode = Addressing_Invalid;
  2983. return;
  2984. }
  2985. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2986. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2987. Operand y_ = {}, *y = &y_;
  2988. ast_node(be, BinaryExpr, node);
  2989. defer({
  2990. node->viral_state_flags |= be->left->viral_state_flags;
  2991. node->viral_state_flags |= be->right->viral_state_flags;
  2992. });
  2993. Token op = be->op;
  2994. switch (op.kind) {
  2995. case Token_CmpEq:
  2996. case Token_NotEq: {
  2997. // NOTE(bill): Allow comparisons between types
  2998. if (is_ise_expr(be->left)) {
  2999. // Evalute the right before the left for an '.X' expression
  3000. check_expr_or_type(c, y, be->right, type_hint);
  3001. check_expr_or_type(c, x, be->left, y->type);
  3002. } else {
  3003. check_expr_or_type(c, x, be->left, type_hint);
  3004. check_expr_or_type(c, y, be->right, x->type);
  3005. }
  3006. bool xt = x->mode == Addressing_Type;
  3007. bool yt = y->mode == Addressing_Type;
  3008. // If only one is a type, this is an error
  3009. if (xt ^ yt) {
  3010. GB_ASSERT(xt != yt);
  3011. if (xt) {
  3012. if (!is_type_typeid(y->type)) {
  3013. error_operand_not_expression(x);
  3014. }
  3015. }
  3016. if (yt) {
  3017. if (!is_type_typeid(x->type)) {
  3018. error_operand_not_expression(y);
  3019. }
  3020. }
  3021. }
  3022. break;
  3023. }
  3024. case Token_in:
  3025. case Token_not_in:
  3026. {
  3027. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3028. check_expr(c, y, be->right);
  3029. Type *rhs_type = type_deref(y->type);
  3030. if (is_type_bit_set(rhs_type)) {
  3031. Type *elem = base_type(rhs_type)->BitSet.elem;
  3032. check_expr_with_type_hint(c, x, be->left, elem);
  3033. } else if (is_type_map(rhs_type)) {
  3034. Type *key = base_type(rhs_type)->Map.key;
  3035. check_expr_with_type_hint(c, x, be->left, key);
  3036. } else {
  3037. check_expr(c, x, be->left);
  3038. }
  3039. if (x->mode == Addressing_Invalid) {
  3040. return;
  3041. }
  3042. if (y->mode == Addressing_Invalid) {
  3043. x->mode = Addressing_Invalid;
  3044. x->expr = y->expr;
  3045. return;
  3046. }
  3047. if (is_type_map(rhs_type)) {
  3048. Type *yt = base_type(rhs_type);
  3049. if (op.kind == Token_in) {
  3050. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3051. } else {
  3052. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3053. }
  3054. add_map_get_dependencies(c);
  3055. } else if (is_type_bit_set(rhs_type)) {
  3056. Type *yt = base_type(rhs_type);
  3057. if (op.kind == Token_in) {
  3058. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3059. } else {
  3060. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3061. }
  3062. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3063. ExactValue k = exact_value_to_integer(x->value);
  3064. ExactValue v = exact_value_to_integer(y->value);
  3065. GB_ASSERT(k.kind == ExactValue_Integer);
  3066. GB_ASSERT(v.kind == ExactValue_Integer);
  3067. i64 key = big_int_to_i64(&k.value_integer);
  3068. i64 lower = yt->BitSet.lower;
  3069. i64 upper = yt->BitSet.upper;
  3070. if (lower <= key && key <= upper) {
  3071. i64 bit = 1ll<<key;
  3072. i64 bits = big_int_to_i64(&v.value_integer);
  3073. x->mode = Addressing_Constant;
  3074. x->type = t_untyped_bool;
  3075. if (op.kind == Token_in) {
  3076. x->value = exact_value_bool((bit & bits) != 0);
  3077. } else {
  3078. x->value = exact_value_bool((bit & bits) == 0);
  3079. }
  3080. x->expr = node;
  3081. return;
  3082. } else {
  3083. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3084. x->mode = Addressing_Invalid;
  3085. }
  3086. }
  3087. } else {
  3088. gbString t = type_to_string(y->type);
  3089. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3090. gb_string_free(t);
  3091. x->expr = node;
  3092. x->mode = Addressing_Invalid;
  3093. return;
  3094. }
  3095. if (x->mode != Addressing_Invalid) {
  3096. x->mode = Addressing_Value;
  3097. x->type = t_untyped_bool;
  3098. }
  3099. x->expr = node;
  3100. return;
  3101. }
  3102. default:
  3103. if (is_ise_expr(be->left)) {
  3104. // Evalute the right before the left for an '.X' expression
  3105. check_expr_or_type(c, y, be->right, type_hint);
  3106. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3107. check_expr_or_type(c, x, be->left, y->type);
  3108. } else {
  3109. check_expr_with_type_hint(c, x, be->left, type_hint);
  3110. }
  3111. } else {
  3112. check_expr_with_type_hint(c, x, be->left, type_hint);
  3113. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3114. check_expr_with_type_hint(c, y, be->right, x->type);
  3115. } else {
  3116. check_expr_with_type_hint(c, y, be->right, type_hint);
  3117. }
  3118. }
  3119. break;
  3120. }
  3121. if (x->mode == Addressing_Invalid) {
  3122. return;
  3123. }
  3124. if (y->mode == Addressing_Invalid) {
  3125. x->mode = Addressing_Invalid;
  3126. x->expr = y->expr;
  3127. return;
  3128. }
  3129. if (x->mode == Addressing_Builtin) {
  3130. x->mode = Addressing_Invalid;
  3131. error(x->expr, "built-in expression in binary expression");
  3132. return;
  3133. }
  3134. if (y->mode == Addressing_Builtin) {
  3135. x->mode = Addressing_Invalid;
  3136. error(y->expr, "built-in expression in binary expression");
  3137. return;
  3138. }
  3139. if (x->mode == Addressing_ProcGroup) {
  3140. x->mode = Addressing_Invalid;
  3141. if (x->proc_group != nullptr) {
  3142. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3143. } else {
  3144. error(x->expr, "procedure group used in binary expression");
  3145. }
  3146. return;
  3147. }
  3148. if (y->mode == Addressing_ProcGroup) {
  3149. x->mode = Addressing_Invalid;
  3150. if (x->proc_group != nullptr) {
  3151. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3152. } else {
  3153. error(y->expr, "procedure group used in binary expression");
  3154. }
  3155. return;
  3156. }
  3157. if (token_is_shift(op.kind)) {
  3158. check_shift(c, x, y, node, type_hint);
  3159. return;
  3160. }
  3161. switch (op.kind) {
  3162. case Token_Quo:
  3163. case Token_Mod:
  3164. case Token_ModMod:
  3165. case Token_QuoEq:
  3166. case Token_ModEq:
  3167. case Token_ModModEq:
  3168. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3169. is_type_float(x->type) && is_type_untyped(x->type)) {
  3170. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3171. gbString t = type_to_string(y->type);
  3172. if (x->value.kind != ExactValue_Invalid) {
  3173. gbString s = exact_value_to_string(x->value);
  3174. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3175. gb_string_free(s);
  3176. } else {
  3177. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3178. }
  3179. gb_string_free(t);
  3180. }
  3181. break;
  3182. }
  3183. convert_to_typed(c, x, y->type);
  3184. if (x->mode == Addressing_Invalid) {
  3185. return;
  3186. }
  3187. convert_to_typed(c, y, x->type);
  3188. if (y->mode == Addressing_Invalid) {
  3189. x->mode = Addressing_Invalid;
  3190. return;
  3191. }
  3192. if (token_is_comparison(op.kind)) {
  3193. check_comparison(c, node, x, y, op.kind);
  3194. return;
  3195. }
  3196. if (check_binary_array_expr(c, op, x, y)) {
  3197. x->mode = Addressing_Value;
  3198. x->type = x->type;
  3199. return;
  3200. }
  3201. if (check_binary_array_expr(c, op, y, x)) {
  3202. x->mode = Addressing_Value;
  3203. x->type = y->type;
  3204. return;
  3205. }
  3206. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3207. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3208. x->expr = node;
  3209. return;
  3210. }
  3211. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3212. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3213. // NOTE(bill, 2022-06-26)
  3214. // Allow any boolean types within `&&` and `||`
  3215. // This is an exception to all other binary expressions since the result
  3216. // of a comparison will always be an untyped boolean, and allowing
  3217. // any boolean between these two simplifies a lot of expressions
  3218. } else if (!are_types_identical(x->type, y->type)) {
  3219. if (x->type != t_invalid &&
  3220. y->type != t_invalid) {
  3221. gbString xt = type_to_string(x->type);
  3222. gbString yt = type_to_string(y->type);
  3223. gbString expr_str = expr_to_string(node);
  3224. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3225. gb_string_free(expr_str);
  3226. gb_string_free(yt);
  3227. gb_string_free(xt);
  3228. }
  3229. x->mode = Addressing_Invalid;
  3230. return;
  3231. }
  3232. if (!check_binary_op(c, x, op)) {
  3233. x->mode = Addressing_Invalid;
  3234. return;
  3235. }
  3236. switch (op.kind) {
  3237. case Token_Quo:
  3238. case Token_Mod:
  3239. case Token_ModMod:
  3240. case Token_QuoEq:
  3241. case Token_ModEq:
  3242. case Token_ModModEq:
  3243. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3244. y->mode == Addressing_Constant) {
  3245. bool fail = false;
  3246. switch (y->value.kind) {
  3247. case ExactValue_Integer:
  3248. if (big_int_is_zero(&y->value.value_integer)) {
  3249. fail = true;
  3250. }
  3251. break;
  3252. case ExactValue_Float:
  3253. if (y->value.value_float == 0.0) {
  3254. fail = true;
  3255. }
  3256. break;
  3257. }
  3258. if (fail) {
  3259. error(y->expr, "Division by zero not allowed");
  3260. x->mode = Addressing_Invalid;
  3261. return;
  3262. }
  3263. }
  3264. break;
  3265. case Token_CmpAnd:
  3266. case Token_CmpOr:
  3267. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3268. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3269. }
  3270. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3271. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3272. }
  3273. break;
  3274. }
  3275. if (x->mode == Addressing_Constant &&
  3276. y->mode == Addressing_Constant) {
  3277. ExactValue a = x->value;
  3278. ExactValue b = y->value;
  3279. if (!is_type_constant_type(x->type)) {
  3280. x->mode = Addressing_Value;
  3281. return;
  3282. }
  3283. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3284. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3285. }
  3286. if (is_type_bit_set(x->type)) {
  3287. switch (op.kind) {
  3288. case Token_Add: op.kind = Token_Or; break;
  3289. case Token_Sub: op.kind = Token_AndNot; break;
  3290. }
  3291. }
  3292. x->value = exact_binary_operator_value(op.kind, a, b);
  3293. if (is_type_typed(x->type)) {
  3294. if (node != nullptr) {
  3295. x->expr = node;
  3296. }
  3297. check_is_expressible(c, x, x->type);
  3298. }
  3299. return;
  3300. } else if (is_type_string(x->type)) {
  3301. error(node, "String concatenation is only allowed with constant strings");
  3302. x->mode = Addressing_Invalid;
  3303. return;
  3304. }
  3305. bool REQUIRE = true;
  3306. Type *bt = base_type(x->type);
  3307. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3308. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3309. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3310. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3311. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3312. }
  3313. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3314. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3315. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3316. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3317. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3318. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3319. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3320. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3321. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3322. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3323. }
  3324. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3325. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3326. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3327. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3328. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3329. case Basic_u128:
  3330. case Basic_i128:
  3331. if (is_arch_wasm()) {
  3332. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3333. }
  3334. break;
  3335. }
  3336. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3337. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3338. case Basic_u128:
  3339. case Basic_i128:
  3340. if (is_arch_wasm()) {
  3341. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3342. }
  3343. break;
  3344. }
  3345. }
  3346. x->mode = Addressing_Value;
  3347. }
  3348. gb_internal Operand make_operand_from_node(Ast *node) {
  3349. GB_ASSERT(node != nullptr);
  3350. Operand x = {};
  3351. x.expr = node;
  3352. x.mode = node->tav.mode;
  3353. x.type = node->tav.type;
  3354. x.value = node->tav.value;
  3355. return x;
  3356. }
  3357. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3358. GB_ASSERT(e != nullptr);
  3359. ExprInfo *old = check_get_expr_info(c, e);
  3360. if (old == nullptr) {
  3361. if (type != nullptr && type != t_invalid) {
  3362. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3363. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3364. if (e->kind == Ast_TernaryIfExpr) {
  3365. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3366. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3367. }
  3368. }
  3369. }
  3370. return;
  3371. }
  3372. switch (e->kind) {
  3373. case_ast_node(ue, UnaryExpr, e);
  3374. if (old->value.kind != ExactValue_Invalid) {
  3375. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3376. // They don't need to be updated as they will be updated later and
  3377. // checked at the end of general checking stage.
  3378. break;
  3379. }
  3380. update_untyped_expr_type(c, ue->expr, type, final);
  3381. case_end;
  3382. case_ast_node(be, BinaryExpr, e);
  3383. if (old->value.kind != ExactValue_Invalid) {
  3384. // See above note in UnaryExpr case
  3385. break;
  3386. }
  3387. if (token_is_comparison(be->op.kind)) {
  3388. // NOTE(bill): Do nothing as the types are fine
  3389. } else if (token_is_shift(be->op.kind)) {
  3390. update_untyped_expr_type(c, be->left, type, final);
  3391. } else {
  3392. update_untyped_expr_type(c, be->left, type, final);
  3393. update_untyped_expr_type(c, be->right, type, final);
  3394. }
  3395. case_end;
  3396. case_ast_node(te, TernaryIfExpr, e);
  3397. if (old->value.kind != ExactValue_Invalid) {
  3398. // See above note in UnaryExpr case
  3399. break;
  3400. }
  3401. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3402. // having an untyped value
  3403. Operand x = make_operand_from_node(te->x);
  3404. Operand y = make_operand_from_node(te->y);
  3405. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3406. update_untyped_expr_type(c, te->x, type, final);
  3407. }
  3408. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3409. update_untyped_expr_type(c, te->y, type, final);
  3410. }
  3411. case_end;
  3412. case_ast_node(te, TernaryWhenExpr, e);
  3413. if (old->value.kind != ExactValue_Invalid) {
  3414. // See above note in UnaryExpr case
  3415. break;
  3416. }
  3417. update_untyped_expr_type(c, te->x, type, final);
  3418. update_untyped_expr_type(c, te->y, type, final);
  3419. case_end;
  3420. case_ast_node(ore, OrReturnExpr, e);
  3421. if (old->value.kind != ExactValue_Invalid) {
  3422. // See above note in UnaryExpr case
  3423. break;
  3424. }
  3425. update_untyped_expr_type(c, ore->expr, type, final);
  3426. case_end;
  3427. case_ast_node(obe, OrBranchExpr, e);
  3428. if (old->value.kind != ExactValue_Invalid) {
  3429. // See above note in UnaryExpr case
  3430. break;
  3431. }
  3432. update_untyped_expr_type(c, obe->expr, type, final);
  3433. case_end;
  3434. case_ast_node(oee, OrElseExpr, e);
  3435. if (old->value.kind != ExactValue_Invalid) {
  3436. // See above note in UnaryExpr case
  3437. break;
  3438. }
  3439. update_untyped_expr_type(c, oee->x, type, final);
  3440. update_untyped_expr_type(c, oee->y, type, final);
  3441. case_end;
  3442. case_ast_node(pe, ParenExpr, e);
  3443. update_untyped_expr_type(c, pe->expr, type, final);
  3444. case_end;
  3445. }
  3446. if (!final && is_type_untyped(type)) {
  3447. old->type = base_type(type);
  3448. return;
  3449. }
  3450. // We need to remove it and then give it a new one
  3451. check_remove_expr_info(c, e);
  3452. if (old->is_lhs && !is_type_integer(type)) {
  3453. gbString expr_str = expr_to_string(e);
  3454. gbString type_str = type_to_string(type);
  3455. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3456. gb_string_free(type_str);
  3457. gb_string_free(expr_str);
  3458. return;
  3459. }
  3460. add_type_and_value(c, e, old->mode, type, old->value);
  3461. }
  3462. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3463. GB_ASSERT(e != nullptr);
  3464. ExprInfo *found = check_get_expr_info(c, e);
  3465. if (found) {
  3466. found->value = value;
  3467. }
  3468. }
  3469. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3470. gbString expr_str = expr_to_string(operand->expr);
  3471. gbString type_str = type_to_string(target_type);
  3472. gbString from_type_str = type_to_string(operand->type);
  3473. char const *extra_text = "";
  3474. if (operand->mode == Addressing_Constant) {
  3475. if (big_int_is_zero(&operand->value.value_integer)) {
  3476. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3477. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3478. extra_text = " - Did you want 'nil'?";
  3479. }
  3480. }
  3481. }
  3482. ERROR_BLOCK();
  3483. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3484. if (operand->value.kind == ExactValue_String) {
  3485. String key = operand->value.value_string;
  3486. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3487. Type *et = base_type(target_type);
  3488. check_did_you_mean_type(key, et->Enum.fields, ".");
  3489. }
  3490. }
  3491. gb_string_free(from_type_str);
  3492. gb_string_free(type_str);
  3493. gb_string_free(expr_str);
  3494. operand->mode = Addressing_Invalid;
  3495. }
  3496. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3497. Type *t = core_type(type);
  3498. if (is_type_boolean(t)) {
  3499. // v = exact_value_to_boolean(v);
  3500. } else if (is_type_float(t)) {
  3501. v = exact_value_to_float(v);
  3502. } else if (is_type_integer(t)) {
  3503. v = exact_value_to_integer(v);
  3504. } else if (is_type_pointer(t)) {
  3505. v = exact_value_to_integer(v);
  3506. } else if (is_type_complex(t)) {
  3507. v = exact_value_to_complex(v);
  3508. } else if (is_type_quaternion(t)) {
  3509. v = exact_value_to_quaternion(v);
  3510. }
  3511. return v;
  3512. }
  3513. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3514. GB_ASSERT_NOT_NULL(target_type);
  3515. if (operand->mode == Addressing_Invalid ||
  3516. operand->mode == Addressing_Type ||
  3517. is_type_typed(operand->type) ||
  3518. target_type == t_invalid) {
  3519. return;
  3520. }
  3521. if (is_type_untyped(target_type)) {
  3522. GB_ASSERT(operand->type->kind == Type_Basic);
  3523. GB_ASSERT(target_type->kind == Type_Basic);
  3524. BasicKind x_kind = operand->type->Basic.kind;
  3525. BasicKind y_kind = target_type->Basic.kind;
  3526. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3527. if (x_kind < y_kind) {
  3528. operand->type = target_type;
  3529. update_untyped_expr_type(c, operand->expr, target_type, false);
  3530. }
  3531. } else if (x_kind != y_kind) {
  3532. operand->mode = Addressing_Invalid;
  3533. convert_untyped_error(c, operand, target_type);
  3534. return;
  3535. }
  3536. return;
  3537. }
  3538. Type *t = base_type(target_type);
  3539. if (c->in_enum_type) {
  3540. t = core_type(target_type);
  3541. }
  3542. switch (t->kind) {
  3543. case Type_Basic:
  3544. if (operand->mode == Addressing_Constant) {
  3545. check_is_expressible(c, operand, t);
  3546. if (operand->mode == Addressing_Invalid) {
  3547. return;
  3548. }
  3549. update_untyped_expr_value(c, operand->expr, operand->value);
  3550. } else {
  3551. switch (operand->type->Basic.kind) {
  3552. case Basic_UntypedBool:
  3553. if (!is_type_boolean(target_type)) {
  3554. operand->mode = Addressing_Invalid;
  3555. convert_untyped_error(c, operand, target_type);
  3556. return;
  3557. }
  3558. break;
  3559. case Basic_UntypedInteger:
  3560. case Basic_UntypedFloat:
  3561. case Basic_UntypedComplex:
  3562. case Basic_UntypedQuaternion:
  3563. case Basic_UntypedRune:
  3564. if (!is_type_numeric(target_type)) {
  3565. operand->mode = Addressing_Invalid;
  3566. convert_untyped_error(c, operand, target_type);
  3567. return;
  3568. }
  3569. break;
  3570. case Basic_UntypedNil:
  3571. if (is_type_any(target_type)) {
  3572. // target_type = t_untyped_nil;
  3573. } else if (is_type_cstring(target_type)) {
  3574. // target_type = t_untyped_nil;
  3575. } else if (!type_has_nil(target_type)) {
  3576. operand->mode = Addressing_Invalid;
  3577. convert_untyped_error(c, operand, target_type);
  3578. return;
  3579. }
  3580. break;
  3581. }
  3582. }
  3583. break;
  3584. case Type_Array: {
  3585. Type *elem = base_array_type(t);
  3586. if (check_is_assignable_to(c, operand, elem)) {
  3587. operand->mode = Addressing_Value;
  3588. } else {
  3589. if (operand->value.kind == ExactValue_String) {
  3590. String s = operand->value.value_string;
  3591. if (is_type_u8_array(t)) {
  3592. if (s.len == t->Array.count) {
  3593. break;
  3594. }
  3595. } else if (is_type_rune_array(t)) {
  3596. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3597. if (rune_count == t->Array.count) {
  3598. break;
  3599. }
  3600. }
  3601. }
  3602. operand->mode = Addressing_Invalid;
  3603. convert_untyped_error(c, operand, target_type);
  3604. return;
  3605. }
  3606. break;
  3607. }
  3608. case Type_Matrix: {
  3609. Type *elem = base_array_type(t);
  3610. if (check_is_assignable_to(c, operand, elem)) {
  3611. if (t->Matrix.row_count != t->Matrix.column_count) {
  3612. operand->mode = Addressing_Invalid;
  3613. ERROR_BLOCK();
  3614. convert_untyped_error(c, operand, target_type);
  3615. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3616. return;
  3617. } else {
  3618. operand->mode = Addressing_Value;
  3619. }
  3620. } else {
  3621. operand->mode = Addressing_Invalid;
  3622. convert_untyped_error(c, operand, target_type);
  3623. return;
  3624. }
  3625. break;
  3626. }
  3627. case Type_Union:
  3628. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3629. TEMPORARY_ALLOCATOR_GUARD();
  3630. isize count = t->Union.variants.count;
  3631. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3632. isize valid_count = 0;
  3633. isize first_success_index = -1;
  3634. for_array(i, t->Union.variants) {
  3635. Type *vt = t->Union.variants[i];
  3636. i64 score = 0;
  3637. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3638. valids[valid_count].index = i;
  3639. valids[valid_count].score = score;
  3640. valid_count += 1;
  3641. if (first_success_index < 0) {
  3642. first_success_index = i;
  3643. }
  3644. }
  3645. }
  3646. if (valid_count > 1) {
  3647. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3648. i64 best_score = valids[0].score;
  3649. for (isize i = 1; i < valid_count; i++) {
  3650. auto v = valids[i];
  3651. if (best_score > v.score) {
  3652. valid_count = i;
  3653. break;
  3654. }
  3655. best_score = v.score;
  3656. }
  3657. first_success_index = valids[0].index;
  3658. }
  3659. gbString type_str = type_to_string(target_type);
  3660. defer (gb_string_free(type_str));
  3661. if (valid_count == 1) {
  3662. operand->mode = Addressing_Value;
  3663. operand->type = t->Union.variants[first_success_index];
  3664. target_type = t->Union.variants[first_success_index];
  3665. break;
  3666. } else if (valid_count > 1) {
  3667. ERROR_BLOCK();
  3668. GB_ASSERT(first_success_index >= 0);
  3669. operand->mode = Addressing_Invalid;
  3670. convert_untyped_error(c, operand, target_type);
  3671. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3672. i32 j = 0;
  3673. for (i32 i = 0; i < valid_count; i++) {
  3674. ValidIndexAndScore valid = valids[i];
  3675. if (j > 0 && valid_count > 2) error_line(", ");
  3676. if (j == valid_count-1) {
  3677. if (valid_count == 2) error_line(" ");
  3678. error_line("or ");
  3679. }
  3680. gbString str = type_to_string(t->Union.variants[valid.index]);
  3681. error_line("'%s'", str);
  3682. gb_string_free(str);
  3683. j++;
  3684. }
  3685. error_line("\n\n");
  3686. return;
  3687. } else if (is_type_untyped_uninit(operand->type)) {
  3688. target_type = t_untyped_uninit;
  3689. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3690. ERROR_BLOCK();
  3691. operand->mode = Addressing_Invalid;
  3692. convert_untyped_error(c, operand, target_type);
  3693. if (count > 0) {
  3694. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3695. error_line("\t");
  3696. for (i32 i = 0; i < count; i++) {
  3697. Type *v = t->Union.variants[i];
  3698. if (i > 0 && count > 2) error_line(", ");
  3699. if (i == count-1) {
  3700. if (count == 2) error_line(" ");
  3701. if (count > 1) {
  3702. error_line("or ");
  3703. }
  3704. }
  3705. gbString str = type_to_string(v);
  3706. error_line("'%s'", str);
  3707. gb_string_free(str);
  3708. }
  3709. error_line("\n\n");
  3710. }
  3711. return;
  3712. }
  3713. }
  3714. /* fallthrough */
  3715. default:
  3716. if (is_type_untyped_uninit(operand->type)) {
  3717. target_type = t_untyped_uninit;
  3718. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3719. target_type = t_untyped_nil;
  3720. } else {
  3721. operand->mode = Addressing_Invalid;
  3722. convert_untyped_error(c, operand, target_type);
  3723. return;
  3724. }
  3725. break;
  3726. }
  3727. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3728. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3729. } else {
  3730. target_type = default_type(operand->type);
  3731. }
  3732. }
  3733. update_untyped_expr_type(c, operand->expr, target_type, true);
  3734. operand->type = target_type;
  3735. }
  3736. gb_internal bool check_index_value(CheckerContext *c, Type *main_type, bool open_range, Ast *index_value, i64 max_count, i64 *value, Type *type_hint=nullptr) {
  3737. Operand operand = {Addressing_Invalid};
  3738. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3739. if (operand.mode == Addressing_Invalid) {
  3740. if (value) *value = 0;
  3741. return false;
  3742. }
  3743. Type *index_type = t_int;
  3744. if (type_hint != nullptr) {
  3745. index_type = type_hint;
  3746. }
  3747. convert_to_typed(c, &operand, index_type);
  3748. if (operand.mode == Addressing_Invalid) {
  3749. if (value) *value = 0;
  3750. return false;
  3751. }
  3752. if (type_hint != nullptr) {
  3753. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3754. gbString expr_str = expr_to_string(operand.expr);
  3755. gbString index_type_str = type_to_string(type_hint);
  3756. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3757. gb_string_free(index_type_str);
  3758. gb_string_free(expr_str);
  3759. if (value) *value = 0;
  3760. return false;
  3761. }
  3762. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3763. gbString expr_str = expr_to_string(operand.expr);
  3764. gbString type_str = type_to_string(operand.type);
  3765. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3766. gb_string_free(type_str);
  3767. gb_string_free(expr_str);
  3768. if (value) *value = 0;
  3769. return false;
  3770. }
  3771. if (operand.mode == Addressing_Constant &&
  3772. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3773. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3774. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3775. TEMPORARY_ALLOCATOR_GUARD();
  3776. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3777. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3778. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3779. if (value) *value = 0;
  3780. return false;
  3781. }
  3782. if (max_count >= 0) {
  3783. if (is_type_enum(index_type)) {
  3784. Type *bt = base_type(index_type);
  3785. GB_ASSERT(bt->kind == Type_Enum);
  3786. ExactValue const &lo = *bt->Enum.min_value;
  3787. ExactValue const &hi = *bt->Enum.max_value;
  3788. String lo_str = {};
  3789. String hi_str = {};
  3790. if (bt->Enum.fields.count > 0) {
  3791. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3792. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3793. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3794. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3795. }
  3796. bool out_of_bounds = false;
  3797. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3798. out_of_bounds = true;
  3799. }
  3800. if (out_of_bounds) {
  3801. gbString expr_str = expr_to_string(operand.expr);
  3802. if (lo_str.len > 0) {
  3803. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3804. } else {
  3805. gbString index_type_str = type_to_string(index_type);
  3806. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3807. gb_string_free(index_type_str);
  3808. }
  3809. gb_string_free(expr_str);
  3810. return false;
  3811. }
  3812. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3813. return true;
  3814. } else { // NOTE(bill): Do array bound checking
  3815. i64 v = -1;
  3816. if (i.used <= 1) {
  3817. v = big_int_to_i64(&i);
  3818. }
  3819. if (value) *value = v;
  3820. bool out_of_bounds = false;
  3821. if (v < 0) {
  3822. out_of_bounds = true;
  3823. } else if (open_range) {
  3824. out_of_bounds = v > max_count;
  3825. } else {
  3826. out_of_bounds = v >= max_count;
  3827. }
  3828. if (out_of_bounds) {
  3829. TEMPORARY_ALLOCATOR_GUARD();
  3830. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3831. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3832. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3833. return false;
  3834. }
  3835. return true;
  3836. }
  3837. } else {
  3838. if (value) *value = exact_value_to_i64(operand.value);
  3839. return true;
  3840. }
  3841. }
  3842. // NOTE(bill): It's alright :D
  3843. if (value) *value = -1;
  3844. return true;
  3845. }
  3846. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3847. if (value.kind == ExactValue_String) {
  3848. GB_ASSERT(0 <= index && index < value.value_string.len);
  3849. u8 val = value.value_string[index];
  3850. if (success_) *success_ = true;
  3851. if (finish_) *finish_ = true;
  3852. return exact_value_u64(val);
  3853. }
  3854. if (value.kind != ExactValue_Compound) {
  3855. if (success_) *success_ = true;
  3856. if (finish_) *finish_ = true;
  3857. return value;
  3858. }
  3859. Ast *node = value.value_compound;
  3860. switch (node->kind) {
  3861. case_ast_node(cl, CompoundLit, node);
  3862. if (cl->elems.count == 0) {
  3863. if (success_) *success_ = true;
  3864. if (finish_) *finish_ = true;
  3865. return empty_exact_value;
  3866. }
  3867. if (cl->elems[0]->kind == Ast_FieldValue) {
  3868. if (is_type_struct(node->tav.type)) {
  3869. bool found = false;
  3870. for (Ast *elem : cl->elems) {
  3871. if (elem->kind != Ast_FieldValue) {
  3872. continue;
  3873. }
  3874. ast_node(fv, FieldValue, elem);
  3875. String name = fv->field->Ident.token.string;
  3876. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3877. defer (array_free(&sub_sel.index));
  3878. if (sub_sel.index[0] == index) {
  3879. value = fv->value->tav.value;
  3880. found = true;
  3881. break;
  3882. }
  3883. }
  3884. if (!found) {
  3885. // Use the zero value if it is not found
  3886. value = {};
  3887. }
  3888. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3889. for (Ast *elem : cl->elems) {
  3890. if (elem->kind != Ast_FieldValue) {
  3891. continue;
  3892. }
  3893. ast_node(fv, FieldValue, elem);
  3894. if (is_ast_range(fv->field)) {
  3895. ast_node(ie, BinaryExpr, fv->field);
  3896. TypeAndValue lo_tav = ie->left->tav;
  3897. TypeAndValue hi_tav = ie->right->tav;
  3898. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3899. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3900. TokenKind op = ie->op.kind;
  3901. i64 lo = exact_value_to_i64(lo_tav.value);
  3902. i64 hi = exact_value_to_i64(hi_tav.value);
  3903. i64 corrected_index = index;
  3904. if (is_type_enumerated_array(node->tav.type)) {
  3905. Type *bt = base_type(node->tav.type);
  3906. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3907. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3908. }
  3909. if (op != Token_RangeHalf) {
  3910. if (lo <= corrected_index && corrected_index <= hi) {
  3911. TypeAndValue tav = fv->value->tav;
  3912. if (success_) *success_ = true;
  3913. if (finish_) *finish_ = false;
  3914. return tav.value;
  3915. }
  3916. } else {
  3917. if (lo <= corrected_index && corrected_index < hi) {
  3918. TypeAndValue tav = fv->value->tav;
  3919. if (success_) *success_ = true;
  3920. if (finish_) *finish_ = false;
  3921. return tav.value;
  3922. }
  3923. }
  3924. } else {
  3925. TypeAndValue index_tav = fv->field->tav;
  3926. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3927. ExactValue index_value = index_tav.value;
  3928. if (is_type_enumerated_array(node->tav.type)) {
  3929. Type *bt = base_type(node->tav.type);
  3930. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3931. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3932. }
  3933. i64 field_index = exact_value_to_i64(index_value);
  3934. if (index == field_index) {
  3935. TypeAndValue tav = fv->value->tav;
  3936. if (success_) *success_ = true;
  3937. if (finish_) *finish_ = false;
  3938. return tav.value;;
  3939. }
  3940. }
  3941. }
  3942. }
  3943. } else {
  3944. i32 count = (i32)cl->elems.count;
  3945. if (count < index) {
  3946. if (success_) *success_ = false;
  3947. if (finish_) *finish_ = true;
  3948. return empty_exact_value;
  3949. }
  3950. if (cl->elems.count <= index) {
  3951. if (success_) *success_ = false;
  3952. if (finish_) *finish_ = false;
  3953. return value;
  3954. }
  3955. TypeAndValue tav = cl->elems[index]->tav;
  3956. if (tav.mode == Addressing_Constant) {
  3957. if (success_) *success_ = true;
  3958. if (finish_) *finish_ = false;
  3959. return tav.value;
  3960. } else {
  3961. GB_ASSERT(is_type_untyped_nil(tav.type));
  3962. if (success_) *success_ = true;
  3963. if (finish_) *finish_ = false;
  3964. return tav.value;
  3965. }
  3966. }
  3967. case_end;
  3968. default:
  3969. if (success_) *success_ = true;
  3970. if (finish_) *finish_ = true;
  3971. return empty_exact_value;
  3972. }
  3973. if (finish_) *finish_ = false;
  3974. return value;
  3975. }
  3976. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3977. if (operand->mode != Addressing_Constant) {
  3978. if (success_) *success_ = false;
  3979. return empty_exact_value;
  3980. }
  3981. if (sel.indirect) {
  3982. if (success_) *success_ = false;
  3983. return empty_exact_value;
  3984. }
  3985. if (sel.index.count == 0) {
  3986. if (success_) *success_ = false;
  3987. return empty_exact_value;
  3988. }
  3989. ExactValue value = operand->value;
  3990. if (value.kind == ExactValue_Compound) {
  3991. while (sel.index.count > 0) {
  3992. i32 index = sel.index[0];
  3993. sel = sub_selection(sel, 1);
  3994. bool finish = false;
  3995. value = get_constant_field_single(c, value, index, success_, &finish);
  3996. if (finish) {
  3997. return value;
  3998. }
  3999. }
  4000. if (success_) *success_ = true;
  4001. return value;
  4002. } else if (value.kind == ExactValue_Quaternion) {
  4003. // @QuaternionLayout
  4004. Quaternion256 q = *value.value_quaternion;
  4005. GB_ASSERT(sel.index.count == 1);
  4006. switch (sel.index[0]) {
  4007. case 3: // w
  4008. if (success_) *success_ = true;
  4009. return exact_value_float(q.real);
  4010. case 0: // x
  4011. if (success_) *success_ = true;
  4012. return exact_value_float(q.imag);
  4013. case 1: // y
  4014. if (success_) *success_ = true;
  4015. return exact_value_float(q.jmag);
  4016. case 2: // z
  4017. if (success_) *success_ = true;
  4018. return exact_value_float(q.kmag);
  4019. }
  4020. if (success_) *success_ = false;
  4021. return empty_exact_value;
  4022. } else if (value.kind == ExactValue_Complex) {
  4023. // @QuaternionLayout
  4024. Complex128 c = *value.value_complex;
  4025. GB_ASSERT(sel.index.count == 1);
  4026. switch (sel.index[0]) {
  4027. case 0: // real
  4028. if (success_) *success_ = true;
  4029. return exact_value_float(c.real);
  4030. case 1: // imag
  4031. if (success_) *success_ = true;
  4032. return exact_value_float(c.imag);
  4033. }
  4034. if (success_) *success_ = false;
  4035. return empty_exact_value;
  4036. }
  4037. if (success_) *success_ = true;
  4038. return empty_exact_value;
  4039. }
  4040. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4041. Type *array_type = base_type(type_deref(original_type));
  4042. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4043. if (array_type->kind == Type_SimdVector) {
  4044. Type *elem_type = array_type->SimdVector.elem;
  4045. return alloc_type_simd_vector(new_count, elem_type);
  4046. }
  4047. Type *elem_type = array_type->Array.elem;
  4048. Type *swizzle_array_type = nullptr;
  4049. Type *bth = base_type(type_deref(type_hint));
  4050. if (bth != nullptr && bth->kind == Type_Array &&
  4051. bth->Array.count == new_count &&
  4052. are_types_identical(bth->Array.elem, elem_type)) {
  4053. swizzle_array_type = type_hint;
  4054. } else {
  4055. i64 max_count = array_type->Array.count;
  4056. if (new_count == max_count) {
  4057. swizzle_array_type = original_type;
  4058. } else {
  4059. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4060. }
  4061. }
  4062. return swizzle_array_type;
  4063. }
  4064. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4065. bool is_declared = entity != nullptr;
  4066. if (is_declared) {
  4067. if (entity->kind == Entity_Builtin) {
  4068. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4069. // This means that we should just ignore the found result through it
  4070. *allow_builtin = entity->scope == import_scope ||
  4071. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4072. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4073. is_declared = false;
  4074. }
  4075. }
  4076. return is_declared;
  4077. }
  4078. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4079. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4080. if (node->kind == Ast_Ident) {
  4081. String name = node->Ident.token.string;
  4082. return scope_lookup(c->scope, name);
  4083. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4084. ast_node(se, SelectorExpr, node);
  4085. if (se->token.kind == Token_ArrowRight) {
  4086. return nullptr;
  4087. }
  4088. Ast *op_expr = se->expr;
  4089. Ast *selector = unparen_expr(se->selector);
  4090. if (selector == nullptr) {
  4091. return nullptr;
  4092. }
  4093. if (selector->kind != Ast_Ident) {
  4094. return nullptr;
  4095. }
  4096. Entity *entity = nullptr;
  4097. Entity *expr_entity = nullptr;
  4098. bool check_op_expr = true;
  4099. if (op_expr->kind == Ast_Ident) {
  4100. String op_name = op_expr->Ident.token.string;
  4101. Entity *e = scope_lookup(c->scope, op_name);
  4102. if (e == nullptr) {
  4103. return nullptr;
  4104. }
  4105. add_entity_use(c, op_expr, e);
  4106. expr_entity = e;
  4107. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4108. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4109. // It pretty much needs to be in this order and this way
  4110. // If you can clean this up, please do but be really careful
  4111. String import_name = op_name;
  4112. Scope *import_scope = e->ImportName.scope;
  4113. String entity_name = selector->Ident.token.string;
  4114. check_op_expr = false;
  4115. entity = scope_lookup_current(import_scope, entity_name);
  4116. bool allow_builtin = false;
  4117. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4118. return nullptr;
  4119. }
  4120. check_entity_decl(c, entity, nullptr, nullptr);
  4121. if (entity->kind == Entity_ProcGroup) {
  4122. return entity;
  4123. }
  4124. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4125. }
  4126. }
  4127. Operand operand = {};
  4128. if (check_op_expr) {
  4129. check_expr_base(c, &operand, op_expr, nullptr);
  4130. if (operand.mode == Addressing_Invalid) {
  4131. return nullptr;
  4132. }
  4133. }
  4134. if (entity == nullptr && selector->kind == Ast_Ident) {
  4135. String field_name = selector->Ident.token.string;
  4136. if (is_type_dynamic_array(type_deref(operand.type))) {
  4137. init_mem_allocator(c->checker);
  4138. }
  4139. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4140. entity = sel.entity;
  4141. }
  4142. if (entity != nullptr) {
  4143. return entity;
  4144. }
  4145. }
  4146. return nullptr;
  4147. }
  4148. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4149. ast_node(se, SelectorExpr, node);
  4150. bool check_op_expr = true;
  4151. Entity *expr_entity = nullptr;
  4152. Entity *entity = nullptr;
  4153. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4154. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4155. error(node, "Illegal use of -> selector shorthand outside of a call");
  4156. operand->mode = Addressing_Invalid;
  4157. operand->expr = node;
  4158. return nullptr;
  4159. }
  4160. operand->expr = node;
  4161. Ast *op_expr = se->expr;
  4162. Ast *selector = unparen_expr(se->selector);
  4163. if (selector == nullptr) {
  4164. operand->mode = Addressing_Invalid;
  4165. operand->expr = node;
  4166. return nullptr;
  4167. }
  4168. if (selector->kind != Ast_Ident) {
  4169. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4170. operand->mode = Addressing_Invalid;
  4171. operand->expr = node;
  4172. return nullptr;
  4173. }
  4174. if (op_expr->kind == Ast_Ident) {
  4175. String op_name = op_expr->Ident.token.string;
  4176. Entity *e = scope_lookup(c->scope, op_name);
  4177. add_entity_use(c, op_expr, e);
  4178. expr_entity = e;
  4179. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4180. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4181. // It pretty much needs to be in this order and this way
  4182. // If you can clean this up, please do but be really careful
  4183. String import_name = op_name;
  4184. Scope *import_scope = e->ImportName.scope;
  4185. String entity_name = selector->Ident.token.string;
  4186. check_op_expr = false;
  4187. entity = scope_lookup_current(import_scope, entity_name);
  4188. bool allow_builtin = false;
  4189. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4190. ERROR_BLOCK();
  4191. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4192. operand->mode = Addressing_Invalid;
  4193. operand->expr = node;
  4194. check_did_you_mean_scope(entity_name, import_scope);
  4195. return nullptr;
  4196. }
  4197. check_entity_decl(c, entity, nullptr, nullptr);
  4198. if (entity->kind == Entity_ProcGroup) {
  4199. operand->mode = Addressing_ProcGroup;
  4200. operand->proc_group = entity;
  4201. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4202. return entity;
  4203. }
  4204. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4205. if (!is_entity_exported(entity, allow_builtin)) {
  4206. gbString sel_str = expr_to_string(selector);
  4207. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4208. gb_string_free(sel_str);
  4209. // NOTE(bill): make the state valid still, even if it's "invalid"
  4210. // operand->mode = Addressing_Invalid;
  4211. // operand->expr = node;
  4212. // return nullptr;
  4213. }
  4214. if (entity->kind == Entity_ProcGroup) {
  4215. Array<Entity *> procs = entity->ProcGroup.entities;
  4216. bool skip = false;
  4217. for (Entity *p : procs) {
  4218. Type *t = base_type(p->type);
  4219. if (t == t_invalid) {
  4220. continue;
  4221. }
  4222. Operand x = {};
  4223. x.mode = Addressing_Value;
  4224. x.type = t;
  4225. if (type_hint != nullptr) {
  4226. if (check_is_assignable_to(c, &x, type_hint)) {
  4227. entity = p;
  4228. skip = true;
  4229. break;
  4230. }
  4231. }
  4232. }
  4233. if (!skip) {
  4234. GB_ASSERT(entity != nullptr);
  4235. operand->mode = Addressing_ProcGroup;
  4236. operand->type = t_invalid;
  4237. operand->expr = node;
  4238. operand->proc_group = entity;
  4239. return entity;
  4240. }
  4241. }
  4242. }
  4243. }
  4244. if (check_op_expr) {
  4245. check_expr_base(c, operand, op_expr, nullptr);
  4246. if (operand->mode == Addressing_Invalid) {
  4247. operand->mode = Addressing_Invalid;
  4248. operand->expr = node;
  4249. return nullptr;
  4250. }
  4251. }
  4252. if (entity == nullptr && selector->kind == Ast_Ident) {
  4253. String field_name = selector->Ident.token.string;
  4254. Type *t = type_deref(operand->type);
  4255. if (t == nullptr) {
  4256. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4257. } else if (is_type_dynamic_array(t)) {
  4258. init_mem_allocator(c->checker);
  4259. }
  4260. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4261. entity = sel.entity;
  4262. // NOTE(bill): Add type info needed for fields like 'names'
  4263. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4264. add_type_info_type(c, operand->type);
  4265. }
  4266. if (is_type_enum(operand->type)) {
  4267. add_type_info_type(c, operand->type);
  4268. }
  4269. }
  4270. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  4271. String field_name = selector->Ident.token.string;
  4272. if (1 < field_name.len && field_name.len <= 4) {
  4273. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4274. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4275. bool found_xyzw = false;
  4276. bool found_rgba = false;
  4277. for (isize i = 0; i < field_name.len; i++) {
  4278. bool valid = false;
  4279. for (isize j = 0; j < 4; j++) {
  4280. if (field_name.text[i] == swizzles_xyzw[j]) {
  4281. found_xyzw = true;
  4282. valid = true;
  4283. break;
  4284. }
  4285. if (field_name.text[i] == swizzles_rgba[j]) {
  4286. found_rgba = true;
  4287. valid = true;
  4288. break;
  4289. }
  4290. }
  4291. if (!valid) {
  4292. goto end_of_array_selector_swizzle;
  4293. }
  4294. }
  4295. u8 *swizzles = nullptr;
  4296. u8 index_count = cast(u8)field_name.len;
  4297. if (found_xyzw && found_rgba) {
  4298. gbString op_str = expr_to_string(op_expr);
  4299. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4300. gb_string_free(op_str);
  4301. operand->mode = Addressing_Invalid;
  4302. operand->expr = node;
  4303. return nullptr;
  4304. }
  4305. u8 indices = 0;
  4306. if (found_xyzw) {
  4307. swizzles = swizzles_xyzw;
  4308. } else if (found_rgba) {
  4309. swizzles = swizzles_rgba;
  4310. }
  4311. for (isize i = 0; i < field_name.len; i++) {
  4312. for (isize j = 0; j < 4; j++) {
  4313. if (field_name.text[i] == swizzles[j]) {
  4314. indices |= cast(u8)(j)<<(i*2);
  4315. break;
  4316. }
  4317. }
  4318. }
  4319. Type *original_type = operand->type;
  4320. Type *array_type = base_type(type_deref(original_type));
  4321. GB_ASSERT(array_type->kind == Type_Array);
  4322. i64 array_count = array_type->Array.count;
  4323. for (u8 i = 0; i < index_count; i++) {
  4324. u8 idx = indices>>(i*2) & 3;
  4325. if (idx >= array_count) {
  4326. char c = 0;
  4327. if (found_xyzw) {
  4328. c = swizzles_xyzw[idx];
  4329. } else if (found_rgba) {
  4330. c = swizzles_rgba[idx];
  4331. } else {
  4332. GB_PANIC("unknown swizzle kind");
  4333. }
  4334. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4335. break;
  4336. }
  4337. }
  4338. se->swizzle_count = index_count;
  4339. se->swizzle_indices = indices;
  4340. AddressingMode prev_mode = operand->mode;
  4341. operand->mode = Addressing_SwizzleValue;
  4342. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4343. operand->expr = node;
  4344. switch (prev_mode) {
  4345. case Addressing_Variable:
  4346. case Addressing_SoaVariable:
  4347. case Addressing_SwizzleVariable:
  4348. operand->mode = Addressing_SwizzleVariable;
  4349. break;
  4350. }
  4351. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4352. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4353. return swizzle_entity;
  4354. }
  4355. end_of_array_selector_swizzle:;
  4356. }
  4357. if (entity == nullptr) {
  4358. gbString op_str = expr_to_string(op_expr);
  4359. gbString type_str = type_to_string_shorthand(operand->type);
  4360. gbString sel_str = expr_to_string(selector);
  4361. if (operand->mode == Addressing_Type) {
  4362. if (is_type_polymorphic(operand->type, true)) {
  4363. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4364. } else {
  4365. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4366. }
  4367. } else {
  4368. ERROR_BLOCK();
  4369. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4370. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4371. String const &name = selector->Ident.token.string;
  4372. Type *bt = base_type(operand->type);
  4373. if (operand->type->kind == Type_Named &&
  4374. operand->type->Named.type_name &&
  4375. operand->type->Named.type_name->kind == Entity_TypeName &&
  4376. operand->type->Named.type_name->TypeName.objc_metadata) {
  4377. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4378. } else if (bt->kind == Type_Struct) {
  4379. check_did_you_mean_type(name, bt->Struct.fields);
  4380. } else if (bt->kind == Type_Enum) {
  4381. check_did_you_mean_type(name, bt->Enum.fields);
  4382. }
  4383. }
  4384. }
  4385. gb_string_free(sel_str);
  4386. gb_string_free(type_str);
  4387. gb_string_free(op_str);
  4388. operand->mode = Addressing_Invalid;
  4389. operand->expr = node;
  4390. return nullptr;
  4391. }
  4392. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4393. bool success = false;
  4394. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4395. if (success) {
  4396. operand->mode = Addressing_Constant;
  4397. operand->expr = node;
  4398. operand->value = field_value;
  4399. operand->type = entity->type;
  4400. add_entity_use(c, selector, entity);
  4401. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4402. return entity;
  4403. }
  4404. gbString op_str = expr_to_string(op_expr);
  4405. gbString type_str = type_to_string_shorthand(operand->type);
  4406. gbString sel_str = expr_to_string(selector);
  4407. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4408. gb_string_free(sel_str);
  4409. gb_string_free(type_str);
  4410. gb_string_free(op_str);
  4411. operand->mode = Addressing_Invalid;
  4412. operand->expr = node;
  4413. return nullptr;
  4414. }
  4415. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4416. bool success = false;
  4417. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4418. if (success) {
  4419. operand->mode = Addressing_Constant;
  4420. operand->expr = node;
  4421. operand->value = field_value;
  4422. operand->type = entity->type;
  4423. add_entity_use(c, selector, entity);
  4424. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4425. return entity;
  4426. }
  4427. gbString op_str = expr_to_string(op_expr);
  4428. gbString type_str = type_to_string_shorthand(operand->type);
  4429. gbString sel_str = expr_to_string(selector);
  4430. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4431. gb_string_free(sel_str);
  4432. gb_string_free(type_str);
  4433. gb_string_free(op_str);
  4434. operand->mode = Addressing_Invalid;
  4435. operand->expr = node;
  4436. return nullptr;
  4437. }
  4438. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4439. gbString op_str = expr_to_string(op_expr);
  4440. gbString type_str = type_to_string_shorthand(operand->type);
  4441. gbString sel_str = expr_to_string(selector);
  4442. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4443. gb_string_free(sel_str);
  4444. gb_string_free(type_str);
  4445. gb_string_free(op_str);
  4446. operand->mode = Addressing_Invalid;
  4447. operand->expr = node;
  4448. return nullptr;
  4449. }
  4450. add_entity_use(c, selector, entity);
  4451. operand->type = entity->type;
  4452. operand->expr = node;
  4453. switch (entity->kind) {
  4454. case Entity_Constant:
  4455. operand->value = entity->Constant.value;
  4456. operand->mode = Addressing_Constant;
  4457. if (operand->value.kind == ExactValue_Procedure) {
  4458. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4459. if (proc != nullptr) {
  4460. operand->mode = Addressing_Value;
  4461. operand->type = proc->type;
  4462. }
  4463. }
  4464. break;
  4465. case Entity_Variable:
  4466. if (sel.indirect) {
  4467. operand->mode = Addressing_Variable;
  4468. } else if (operand->mode == Addressing_Context) {
  4469. // Do nothing
  4470. } else if (operand->mode == Addressing_MapIndex) {
  4471. operand->mode = Addressing_Value;
  4472. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4473. operand->mode = Addressing_SoaVariable;
  4474. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4475. operand->mode = Addressing_Value;
  4476. } else if (operand->mode == Addressing_SoaVariable) {
  4477. operand->mode = Addressing_Variable;
  4478. } else if (operand->mode != Addressing_Value) {
  4479. operand->mode = Addressing_Variable;
  4480. } else {
  4481. operand->mode = Addressing_Value;
  4482. }
  4483. break;
  4484. case Entity_TypeName:
  4485. operand->mode = Addressing_Type;
  4486. break;
  4487. case Entity_Procedure:
  4488. operand->mode = Addressing_Value;
  4489. operand->value = exact_value_procedure(node);
  4490. break;
  4491. case Entity_Builtin:
  4492. operand->mode = Addressing_Builtin;
  4493. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4494. break;
  4495. case Entity_ProcGroup:
  4496. operand->mode = Addressing_ProcGroup;
  4497. operand->proc_group = entity;
  4498. break;
  4499. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4500. case Entity_Nil:
  4501. operand->mode = Addressing_Value;
  4502. break;
  4503. }
  4504. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4505. return entity;
  4506. }
  4507. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4508. ptr = base_type(ptr);
  4509. if (is_type_pointer(ptr)) {
  4510. if (is_type_rawptr(ptr)) {
  4511. return false;
  4512. }
  4513. if (elem) *elem = ptr->Pointer.elem;
  4514. return true;
  4515. }
  4516. return false;
  4517. }
  4518. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4519. elem = core_type(elem);
  4520. if (is_type_internally_pointer_like(elem)) {
  4521. return true;
  4522. }
  4523. if (elem->kind == Type_BitSet) {
  4524. elem = bit_set_to_int(elem);
  4525. }
  4526. if (elem->kind != Type_Basic) {
  4527. return false;
  4528. }
  4529. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4530. }
  4531. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4532. switch (node->kind) {
  4533. case_ast_node(i, Ident, node);
  4534. String name = i->token.string;
  4535. if (nested) {
  4536. Entity *e = scope_lookup_current(s, name);
  4537. if (e != nullptr) {
  4538. if (out_scope) *out_scope = e->scope;
  4539. return true;
  4540. }
  4541. } else {
  4542. Entity *e = scope_lookup(s, name);
  4543. if (e != nullptr) {
  4544. if (out_scope) *out_scope = e->scope;
  4545. return true;
  4546. }
  4547. }
  4548. case_end;
  4549. case_ast_node(se, SelectorExpr, node);
  4550. Ast *lhs = se->expr;
  4551. Ast *rhs = se->selector;
  4552. Scope *lhs_scope = nullptr;
  4553. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4554. return check_identifier_exists(lhs_scope, rhs, true);
  4555. }
  4556. case_end;
  4557. }
  4558. return false;
  4559. }
  4560. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4561. if (o.type && is_type_no_copy(o.type)) {
  4562. Ast *expr = unparen_expr(o.expr);
  4563. if (expr && o.mode != Addressing_Constant) {
  4564. if (expr->kind == Ast_CallExpr) {
  4565. // Okay
  4566. } else {
  4567. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4568. return true;
  4569. }
  4570. }
  4571. }
  4572. return false;
  4573. }
  4574. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4575. bool optional_ok = false;
  4576. isize tuple_index = 0;
  4577. for (Ast *rhs_expr : rhs) {
  4578. CheckerContext c_ = *ctx;
  4579. CheckerContext *c = &c_;
  4580. Operand o = {};
  4581. Type *type_hint = nullptr;
  4582. if (tuple_index < lhs.count) {
  4583. type_hint = lhs[tuple_index].type;
  4584. }
  4585. check_expr_base(c, &o, rhs_expr, type_hint);
  4586. if (o.mode == Addressing_NoValue) {
  4587. error_operand_no_value(&o);
  4588. o.mode = Addressing_Invalid;
  4589. }
  4590. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4591. if (lhs.count == 2 && rhs.count == 1 &&
  4592. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4593. Ast *expr = unparen_expr(o.expr);
  4594. Operand val0 = o;
  4595. Operand val1 = o;
  4596. val0.mode = Addressing_Value;
  4597. val1.mode = Addressing_Value;
  4598. val1.type = t_untyped_bool;
  4599. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4600. if (expr->kind == Ast_TypeAssertion &&
  4601. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4602. // NOTE(bill): Used only for optimizations in the backend
  4603. if (is_blank_ident(lhs[0].expr)) {
  4604. expr->TypeAssertion.ignores[0] = true;
  4605. }
  4606. if (is_blank_ident(lhs[1].expr)) {
  4607. expr->TypeAssertion.ignores[1] = true;
  4608. }
  4609. }
  4610. array_add(operands, val0);
  4611. array_add(operands, val1);
  4612. optional_ok = true;
  4613. tuple_index += 2;
  4614. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4615. Type *tuple = o.type;
  4616. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4617. Ast *expr = unparen_expr(o.expr);
  4618. if (expr->kind == Ast_CallExpr) {
  4619. expr->CallExpr.optional_ok_one = true;
  4620. }
  4621. Operand val = o;
  4622. val.type = tuple->Tuple.variables[0]->type;
  4623. val.mode = Addressing_Value;
  4624. array_add(operands, val);
  4625. tuple_index += tuple->Tuple.variables.count;
  4626. } else {
  4627. array_add(operands, o);
  4628. tuple_index += 1;
  4629. }
  4630. } else {
  4631. TypeTuple *tuple = &o.type->Tuple;
  4632. for (Entity *e : tuple->variables) {
  4633. o.type = e->type;
  4634. array_add(operands, o);
  4635. check_no_copy_assignment(o, str_lit("assignment"));
  4636. }
  4637. tuple_index += tuple->variables.count;
  4638. }
  4639. }
  4640. return optional_ok;
  4641. }
  4642. typedef u32 UnpackFlags;
  4643. enum UnpackFlag : u32 {
  4644. UnpackFlag_None = 0,
  4645. UnpackFlag_AllowOk = 1<<0,
  4646. UnpackFlag_IsVariadic = 1<<1,
  4647. UnpackFlag_AllowUndef = 1<<2,
  4648. };
  4649. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4650. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4651. if (lhs == nullptr || c->decl == nullptr) {
  4652. return tuple_count;
  4653. }
  4654. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4655. Entity *e = lhs[tuple_index + j];
  4656. if (e == nullptr) {
  4657. continue;
  4658. }
  4659. DeclInfo *decl = decl_info_of_entity(e);
  4660. if (decl == nullptr) {
  4661. continue;
  4662. }
  4663. rw_mutex_shared_lock(&decl->deps_mutex);
  4664. rw_mutex_lock(&c->decl->deps_mutex);
  4665. for (Entity *dep : decl->deps) {
  4666. ptr_set_add(&c->decl->deps, dep);
  4667. }
  4668. rw_mutex_unlock(&c->decl->deps_mutex);
  4669. rw_mutex_shared_unlock(&decl->deps_mutex);
  4670. }
  4671. return tuple_count;
  4672. };
  4673. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4674. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4675. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4676. bool optional_ok = false;
  4677. isize tuple_index = 0;
  4678. for (Ast *rhs : rhs_arguments) {
  4679. if (rhs->kind == Ast_FieldValue) {
  4680. error(rhs, "Invalid use of 'field = value'");
  4681. rhs = rhs->FieldValue.value;
  4682. }
  4683. CheckerContext c_ = *ctx;
  4684. CheckerContext *c = &c_;
  4685. Operand o = {};
  4686. Type *type_hint = nullptr;
  4687. if (lhs != nullptr && tuple_index < lhs_count) {
  4688. // NOTE(bill): override DeclInfo for dependency
  4689. Entity *e = lhs[tuple_index];
  4690. if (e != nullptr) {
  4691. type_hint = e->type;
  4692. if (e->flags & EntityFlag_Ellipsis) {
  4693. GB_ASSERT(is_type_slice(e->type));
  4694. GB_ASSERT(e->type->kind == Type_Slice);
  4695. type_hint = e->type->Slice.elem;
  4696. }
  4697. }
  4698. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4699. // NOTE(bill): override DeclInfo for dependency
  4700. Entity *e = lhs[lhs_count-1];
  4701. if (e != nullptr) {
  4702. type_hint = e->type;
  4703. if (e->flags & EntityFlag_Ellipsis) {
  4704. GB_ASSERT(is_type_slice(e->type));
  4705. GB_ASSERT(e->type->kind == Type_Slice);
  4706. type_hint = e->type->Slice.elem;
  4707. }
  4708. }
  4709. }
  4710. Ast *rhs_expr = unparen_expr(rhs);
  4711. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4712. // NOTE(bill): Just handle this very specific logic here
  4713. o.type = t_untyped_uninit;
  4714. o.mode = Addressing_Value;
  4715. o.expr = rhs;
  4716. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4717. } else {
  4718. check_expr_base(c, &o, rhs, type_hint);
  4719. }
  4720. if (o.mode == Addressing_NoValue) {
  4721. error_operand_no_value(&o);
  4722. o.mode = Addressing_Invalid;
  4723. }
  4724. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4725. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4726. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4727. Ast *expr = unparen_expr(o.expr);
  4728. Operand val0 = o;
  4729. Operand val1 = o;
  4730. val0.mode = Addressing_Value;
  4731. val1.mode = Addressing_Value;
  4732. val1.type = t_untyped_bool;
  4733. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4734. if (expr->kind == Ast_TypeAssertion &&
  4735. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4736. // NOTE(bill): Used only for optimizations in the backend
  4737. if (is_blank_ident(lhs[0]->token)) {
  4738. expr->TypeAssertion.ignores[0] = true;
  4739. }
  4740. if (is_blank_ident(lhs[1]->token)) {
  4741. expr->TypeAssertion.ignores[1] = true;
  4742. }
  4743. }
  4744. array_add(operands, val0);
  4745. array_add(operands, val1);
  4746. optional_ok = true;
  4747. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4748. } else {
  4749. array_add(operands, o);
  4750. tuple_index += 1;
  4751. }
  4752. } else {
  4753. TypeTuple *tuple = &o.type->Tuple;
  4754. for (Entity *e : tuple->variables) {
  4755. o.type = e->type;
  4756. array_add(operands, o);
  4757. }
  4758. isize count = tuple->variables.count;
  4759. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4760. }
  4761. }
  4762. return optional_ok;
  4763. }
  4764. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4765. GB_ASSERT(pt != nullptr);
  4766. GB_ASSERT(pt->kind == Type_Proc);
  4767. isize param_count = 0;
  4768. isize param_count_excluding_defaults = 0;
  4769. bool variadic = pt->Proc.variadic;
  4770. TypeTuple *param_tuple = nullptr;
  4771. if (pt->Proc.params != nullptr) {
  4772. param_tuple = &pt->Proc.params->Tuple;
  4773. param_count = param_tuple->variables.count;
  4774. if (variadic) {
  4775. for (isize i = param_count-1; i >= 0; i--) {
  4776. Entity *e = param_tuple->variables[i];
  4777. if (e->kind == Entity_TypeName) {
  4778. break;
  4779. }
  4780. if (e->kind == Entity_Variable) {
  4781. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4782. param_count--;
  4783. continue;
  4784. }
  4785. }
  4786. break;
  4787. }
  4788. param_count--;
  4789. }
  4790. }
  4791. param_count_excluding_defaults = param_count;
  4792. if (param_tuple != nullptr) {
  4793. for (isize i = param_count-1; i >= 0; i--) {
  4794. Entity *e = param_tuple->variables[i];
  4795. if (e->kind == Entity_TypeName) {
  4796. break;
  4797. }
  4798. if (e->kind == Entity_Variable) {
  4799. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4800. param_count_excluding_defaults--;
  4801. continue;
  4802. }
  4803. }
  4804. break;
  4805. }
  4806. }
  4807. if (param_count_) *param_count_ = param_count;
  4808. return param_count_excluding_defaults;
  4809. }
  4810. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4811. isize param_count = pt->param_count;
  4812. for (isize i = 0; i < param_count; i++) {
  4813. Entity *e = pt->params->Tuple.variables[i];
  4814. String name = e->token.string;
  4815. if (is_blank_ident(name)) {
  4816. continue;
  4817. }
  4818. if (name == parameter_name) {
  4819. return i;
  4820. }
  4821. }
  4822. return -1;
  4823. }
  4824. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4825. type = base_type(type);
  4826. GB_ASSERT(type->kind == Type_Proc);
  4827. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4828. }
  4829. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  4830. Entity *entity, Type *proc_type,
  4831. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  4832. CallArgumentErrorMode show_error_mode,
  4833. CallArgumentData *data) {
  4834. TEMPORARY_ALLOCATOR_GUARD();
  4835. CallArgumentError err = CallArgumentError_None;
  4836. ast_node(ce, CallExpr, call);
  4837. GB_ASSERT(is_type_proc(proc_type));
  4838. proc_type = base_type(proc_type);
  4839. TypeProc *pt = &proc_type->Proc;
  4840. isize param_count = 0;
  4841. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4842. bool variadic = pt->variadic;
  4843. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4844. i64 score = 0;
  4845. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  4846. Type *final_proc_type = proc_type;
  4847. Entity *gen_entity = nullptr;
  4848. if (vari_expand && !variadic) {
  4849. if (show_error) {
  4850. error(ce->ellipsis,
  4851. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4852. LIT(ce->proc->Ident.token.string));
  4853. }
  4854. err = CallArgumentError_NonVariadicExpand;
  4855. } else if (vari_expand && pt->c_vararg) {
  4856. if (show_error) {
  4857. error(ce->ellipsis,
  4858. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4859. LIT(ce->proc->Ident.token.string));
  4860. }
  4861. err = CallArgumentError_NonVariadicExpand;
  4862. }
  4863. GB_ASSERT(ce->split_args);
  4864. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  4865. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  4866. defer ({
  4867. for (Operand const &o : ordered_operands) {
  4868. if (o.expr != nullptr) {
  4869. call->viral_state_flags |= o.expr->viral_state_flags;
  4870. }
  4871. }
  4872. });
  4873. isize positional_operand_count = positional_operands.count;
  4874. if (variadic) {
  4875. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  4876. } else if (positional_operand_count > pt->param_count) {
  4877. err = CallArgumentError_TooManyArguments;
  4878. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4879. if (show_error) {
  4880. gbString proc_str = expr_to_string(ce->proc);
  4881. defer (gb_string_free(proc_str));
  4882. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  4883. }
  4884. return err;
  4885. }
  4886. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  4887. for (isize i = 0; i < positional_operand_count; i++) {
  4888. ordered_operands[i] = positional_operands[i];
  4889. visited[i] = true;
  4890. }
  4891. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  4892. bool named_variadic_param = false;
  4893. if (named_operands.count != 0) {
  4894. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  4895. for_array(i, ce->split_args->named) {
  4896. Ast *arg = ce->split_args->named[i];
  4897. Operand operand = named_operands[i];
  4898. ast_node(fv, FieldValue, arg);
  4899. if (fv->field->kind != Ast_Ident) {
  4900. if (show_error) {
  4901. gbString expr_str = expr_to_string(fv->field);
  4902. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4903. gb_string_free(expr_str);
  4904. }
  4905. err = CallArgumentError_InvalidFieldValue;
  4906. continue;
  4907. }
  4908. String name = fv->field->Ident.token.string;
  4909. isize param_index = lookup_procedure_parameter(pt, name);
  4910. if (param_index < 0) {
  4911. if (show_error) {
  4912. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4913. }
  4914. err = CallArgumentError_ParameterNotFound;
  4915. continue;
  4916. }
  4917. if (pt->variadic && param_index == pt->variadic_index) {
  4918. named_variadic_param = true;
  4919. }
  4920. if (visited[param_index]) {
  4921. if (show_error) {
  4922. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4923. }
  4924. err = CallArgumentError_DuplicateParameter;
  4925. continue;
  4926. }
  4927. visited[param_index] = true;
  4928. ordered_operands[param_index] = operand;
  4929. }
  4930. }
  4931. isize dummy_argument_count = 0;
  4932. bool actually_variadic = false;
  4933. if (variadic) {
  4934. if (visited[pt->variadic_index] &&
  4935. positional_operand_count < positional_operands.count) {
  4936. if (show_error) {
  4937. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  4938. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  4939. }
  4940. err = CallArgumentError_DuplicateParameter;
  4941. } else if (!visited[pt->variadic_index]) {
  4942. visited[pt->variadic_index] = true;
  4943. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  4944. if (vari_expand) {
  4945. GB_ASSERT(variadic_operands.count != 0);
  4946. *variadic_operand = variadic_operands[0];
  4947. variadic_operand->type = default_type(variadic_operand->type);
  4948. actually_variadic = true;
  4949. } else {
  4950. AstFile *f = call->file();
  4951. // HACK(bill): this is an awful hack
  4952. Operand o = {};
  4953. o.mode = Addressing_Value;
  4954. o.expr = ast_ident(f, make_token_ident("nil"));
  4955. o.expr->Ident.token.pos = ast_token(call).pos;
  4956. if (variadic_operands.count != 0) {
  4957. actually_variadic = true;
  4958. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  4959. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  4960. o.type = vt->type;
  4961. } else {
  4962. dummy_argument_count += 1;
  4963. o.type = t_untyped_nil;
  4964. }
  4965. *variadic_operand = o;
  4966. }
  4967. }
  4968. }
  4969. for (Operand const &o : ordered_operands) {
  4970. if (o.mode != Addressing_Invalid) {
  4971. check_no_copy_assignment(o, str_lit("procedure call expression"));
  4972. }
  4973. }
  4974. for (isize i = 0; i < pt->param_count; i++) {
  4975. if (!visited[i]) {
  4976. Entity *e = pt->params->Tuple.variables[i];
  4977. if (e->kind == Entity_Variable) {
  4978. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4979. ordered_operands[i].mode = Addressing_Value;
  4980. ordered_operands[i].type = e->type;
  4981. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  4982. dummy_argument_count += 1;
  4983. score += assign_score_function(1);
  4984. continue;
  4985. }
  4986. }
  4987. if (show_error) {
  4988. if (e->kind == Entity_TypeName) {
  4989. error(call, "Type parameter '%.*s' is missing in procedure call",
  4990. LIT(e->token.string));
  4991. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4992. // Ignore
  4993. } else {
  4994. gbString str = type_to_string(e->type);
  4995. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4996. LIT(e->token.string), str);
  4997. gb_string_free(str);
  4998. }
  4999. }
  5000. err = CallArgumentError_ParameterMissing;
  5001. }
  5002. }
  5003. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5004. i64 s = 0;
  5005. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic)) {
  5006. bool ok = false;
  5007. if (e && e->flags & EntityFlag_AnyInt) {
  5008. if (is_type_integer(param_type)) {
  5009. ok = check_is_castable_to(c, o, param_type);
  5010. }
  5011. }
  5012. if (ok) {
  5013. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5014. } else {
  5015. if (show_error) {
  5016. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5017. Type *src = base_type(o->type);
  5018. Type *dst = base_type(param_type);
  5019. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  5020. gbString a = expr_to_string(o->expr);
  5021. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  5022. gb_string_free(a);
  5023. }
  5024. }
  5025. err = CallArgumentError_WrongTypes;
  5026. }
  5027. } else if (show_error) {
  5028. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5029. }
  5030. if (e && e->flags & EntityFlag_ConstInput) {
  5031. if (o->mode != Addressing_Constant) {
  5032. if (show_error) {
  5033. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5034. }
  5035. err = CallArgumentError_NoneConstantParameter;
  5036. }
  5037. }
  5038. if (!err && is_type_any(param_type)) {
  5039. add_type_info_type(c, o->type);
  5040. }
  5041. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5042. add_type_info_type(c, o->type);
  5043. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5044. } else if (show_error && is_type_untyped(o->type)) {
  5045. update_untyped_expr_type(c, o->expr, param_type, true);
  5046. }
  5047. return s;
  5048. };
  5049. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5050. err = CallArgumentError_None;
  5051. if (variadic) {
  5052. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5053. Type *t = pt->params->Tuple.variables[0]->type;
  5054. if (is_type_polymorphic(t)) {
  5055. if (show_error) {
  5056. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5057. }
  5058. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5059. }
  5060. }
  5061. } else {
  5062. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5063. PolyProcData poly_proc_data = {};
  5064. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5065. gen_entity = poly_proc_data.gen_entity;
  5066. Type *gept = base_type(gen_entity->type);
  5067. GB_ASSERT(is_type_proc(gept));
  5068. final_proc_type = gen_entity->type;
  5069. pt = &gept->Proc;
  5070. } else {
  5071. err = CallArgumentError_WrongTypes;
  5072. }
  5073. }
  5074. for (isize i = 0; i < pt->param_count; i++) {
  5075. Operand *o = &ordered_operands[i];
  5076. if (o->mode == Addressing_Invalid) {
  5077. continue;
  5078. }
  5079. Entity *e = pt->params->Tuple.variables[i];
  5080. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5081. if (e->kind == Entity_TypeName) {
  5082. GB_ASSERT(pt->is_polymorphic);
  5083. if (o->mode != Addressing_Type) {
  5084. if (show_error) {
  5085. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5086. }
  5087. err = CallArgumentError_WrongTypes;
  5088. }
  5089. if (are_types_identical(e->type, o->type)) {
  5090. score += assign_score_function(1);
  5091. } else {
  5092. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5093. }
  5094. continue;
  5095. }
  5096. if (param_is_variadic) {
  5097. continue;
  5098. }
  5099. score += eval_param_and_score(c, o, e->type, err, param_is_variadic, e, show_error);
  5100. }
  5101. }
  5102. if (variadic) {
  5103. Type *slice = pt->params->Tuple.variables[pt->variadic_index]->type;
  5104. GB_ASSERT(is_type_slice(slice));
  5105. Type *elem = base_type(slice)->Slice.elem;
  5106. Type *t = elem;
  5107. if (is_type_polymorphic(t)) {
  5108. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5109. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5110. }
  5111. for_array(operand_index, variadic_operands) {
  5112. Operand *o = &variadic_operands[operand_index];
  5113. if (vari_expand) {
  5114. t = slice;
  5115. if (operand_index > 0) {
  5116. if (show_error) {
  5117. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5118. }
  5119. if (data) {
  5120. data->score = score;
  5121. data->result_type = final_proc_type->Proc.results;
  5122. data->gen_entity = gen_entity;
  5123. }
  5124. return CallArgumentError_MultipleVariadicExpand;
  5125. }
  5126. }
  5127. score += eval_param_and_score(c, o, t, err, true, nullptr, show_error);
  5128. }
  5129. }
  5130. if (data) {
  5131. data->score = score;
  5132. data->result_type = final_proc_type->Proc.results;
  5133. data->gen_entity = gen_entity;
  5134. Ast *proc_lit = nullptr;
  5135. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5136. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5137. if (vp && vp->kind == Ast_ProcLit) {
  5138. proc_lit = vp;
  5139. }
  5140. }
  5141. if (proc_lit == nullptr) {
  5142. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5143. }
  5144. }
  5145. return err;
  5146. }
  5147. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5148. GB_ASSERT(ce != nullptr);
  5149. if (ce->args.count == 0) {
  5150. return false;
  5151. }
  5152. return ce->args[0]->kind == Ast_FieldValue;
  5153. }
  5154. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5155. Entity **lhs = nullptr;
  5156. isize lhs_count = -1;
  5157. if (proc_type == nullptr) {
  5158. return nullptr;
  5159. }
  5160. GB_ASSERT(is_type_proc(proc_type));
  5161. TypeProc *pt = &base_type(proc_type)->Proc;
  5162. *is_variadic = pt->variadic;
  5163. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5164. if (pt->params != nullptr) {
  5165. lhs = pt->params->Tuple.variables.data;
  5166. lhs_count = pt->params->Tuple.variables.count;
  5167. }
  5168. } else {
  5169. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5170. if (pt->params == nullptr) {
  5171. lhs_count = 0;
  5172. } else {
  5173. lhs_count = pt->params->Tuple.variables.count;
  5174. }
  5175. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5176. for (isize i = 0; i < lhs_count; i++) {
  5177. Entity *e = pt->params->Tuple.variables[i];
  5178. if (!is_type_polymorphic(e->type)) {
  5179. lhs[i] = e;
  5180. }
  5181. }
  5182. }
  5183. if (lhs_count_) *lhs_count_ = lhs_count;
  5184. return lhs;
  5185. }
  5186. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5187. if (clauses != nullptr) {
  5188. for (Ast *clause : *clauses) {
  5189. Operand o = {};
  5190. check_expr(ctx, &o, clause);
  5191. if (o.mode != Addressing_Constant) {
  5192. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5193. if (print_err && call_expr) error(call_expr, "at caller location");
  5194. return false;
  5195. } else if (o.value.kind != ExactValue_Bool) {
  5196. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5197. if (print_err && call_expr) error(call_expr, "at caller location");
  5198. return false;
  5199. } else if (!o.value.value_bool) {
  5200. if (print_err) {
  5201. ERROR_BLOCK();
  5202. gbString str = expr_to_string(clause);
  5203. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5204. gb_string_free(str);
  5205. if (scope != nullptr) {
  5206. isize print_count = 0;
  5207. for (auto const &entry : scope->elements) {
  5208. Entity *e = entry.value;
  5209. switch (e->kind) {
  5210. case Entity_TypeName: {
  5211. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5212. gbString str = type_to_string(e->type);
  5213. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5214. gb_string_free(str);
  5215. print_count += 1;
  5216. break;
  5217. }
  5218. case Entity_Constant: {
  5219. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5220. gbString str = exact_value_to_string(e->Constant.value);
  5221. if (is_type_untyped(e->type)) {
  5222. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5223. } else {
  5224. gbString t = type_to_string(e->type);
  5225. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5226. gb_string_free(t);
  5227. }
  5228. gb_string_free(str);
  5229. print_count += 1;
  5230. break;
  5231. }
  5232. }
  5233. }
  5234. }
  5235. if (call_expr) error(call_expr, "at caller location");
  5236. }
  5237. return false;
  5238. }
  5239. }
  5240. }
  5241. return true;
  5242. }
  5243. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5244. bool success = true;
  5245. type = base_type(type);
  5246. if (named_args.count > 0) {
  5247. TypeProc *pt = nullptr;
  5248. if (is_type_proc(type)) {
  5249. pt = &type->Proc;
  5250. }
  5251. for_array(i, named_args) {
  5252. Ast *arg = named_args[i];
  5253. if (arg->kind != Ast_FieldValue) {
  5254. if (show_error) {
  5255. error(arg, "Expected a 'field = value'");
  5256. }
  5257. return false;
  5258. }
  5259. ast_node(fv, FieldValue, arg);
  5260. if (fv->field->kind != Ast_Ident) {
  5261. if (show_error) {
  5262. gbString expr_str = expr_to_string(fv->field);
  5263. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5264. gb_string_free(expr_str);
  5265. }
  5266. success = false;
  5267. continue;
  5268. }
  5269. String key = fv->field->Ident.token.string;
  5270. Ast *value = fv->value;
  5271. Type *type_hint = nullptr;
  5272. if (pt) {
  5273. isize param_index = lookup_procedure_parameter(pt, key);
  5274. if (param_index < 0) {
  5275. if (show_error) {
  5276. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5277. }
  5278. success = false;
  5279. continue;
  5280. }
  5281. Entity *e = pt->params->Tuple.variables[param_index];
  5282. if (!is_type_polymorphic(e->type)) {
  5283. type_hint = e->type;
  5284. }
  5285. }
  5286. Operand o = {};
  5287. check_expr_with_type_hint(c, &o, value, type_hint);
  5288. if (o.mode == Addressing_Invalid) {
  5289. success = false;
  5290. }
  5291. array_add(named_operands, o);
  5292. }
  5293. }
  5294. return success;
  5295. }
  5296. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5297. Entity *e, Type *proc_type,
  5298. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5299. CallArgumentErrorMode show_error_mode,
  5300. CallArgumentData *data) {
  5301. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5302. Ast *ident = operand->expr;
  5303. while (ident->kind == Ast_SelectorExpr) {
  5304. Ast *s = ident->SelectorExpr.selector;
  5305. ident = s;
  5306. }
  5307. if (e == nullptr) {
  5308. e = entity_of_node(ident);
  5309. if (e != nullptr) {
  5310. proc_type = e->type;
  5311. }
  5312. }
  5313. GB_ASSERT(proc_type != nullptr);
  5314. proc_type = base_type(proc_type);
  5315. GB_ASSERT(proc_type->kind == Type_Proc);
  5316. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5317. if (return_on_failure && err != CallArgumentError_None) {
  5318. return false;
  5319. }
  5320. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5321. if (!return_on_failure && entity_to_use != nullptr) {
  5322. add_entity_use(c, ident, entity_to_use);
  5323. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5324. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5325. }
  5326. if (data->gen_entity != nullptr) {
  5327. Entity *e = data->gen_entity;
  5328. DeclInfo *decl = data->gen_entity->decl_info;
  5329. CheckerContext ctx = *c;
  5330. ctx.scope = decl->scope;
  5331. ctx.decl = decl;
  5332. ctx.proc_name = e->token.string;
  5333. ctx.curr_proc_decl = decl;
  5334. ctx.curr_proc_sig = e->type;
  5335. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5336. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5337. if (return_on_failure) {
  5338. if (!ok) {
  5339. return false;
  5340. }
  5341. } else {
  5342. decl->where_clauses_evaluated = true;
  5343. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5344. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5345. }
  5346. if (is_type_proc(data->gen_entity->type)) {
  5347. Type *t = base_type(entity_to_use->type);
  5348. data->result_type = t->Proc.results;
  5349. }
  5350. }
  5351. }
  5352. return true;
  5353. }
  5354. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5355. ast_node(ce, CallExpr, call);
  5356. GB_ASSERT(ce->split_args != nullptr);
  5357. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5358. Slice<Ast *> const &named_args = ce->split_args->named;
  5359. CallArgumentData data = {};
  5360. data.result_type = t_invalid;
  5361. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5362. auto procs = proc_group_entities_cloned(c, *operand);
  5363. if (procs.count > 1) {
  5364. isize max_arg_count = positional_args.count + named_args.count;
  5365. for (Ast *arg : positional_args) {
  5366. // NOTE(bill): The only thing that may have multiple values
  5367. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5368. arg = strip_or_return_expr(arg);
  5369. if (arg && arg->kind == Ast_CallExpr) {
  5370. max_arg_count = ISIZE_MAX;
  5371. break;
  5372. }
  5373. }
  5374. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5375. // NOTE(bill): The only thing that may have multiple values
  5376. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5377. if (arg->kind == Ast_FieldValue) {
  5378. arg = strip_or_return_expr(arg->FieldValue.value);
  5379. if (arg && arg->kind == Ast_CallExpr) {
  5380. max_arg_count = ISIZE_MAX;
  5381. break;
  5382. }
  5383. }
  5384. }
  5385. // ignore named arguments first
  5386. for (Ast *arg : named_args) {
  5387. if (arg->kind != Ast_FieldValue) {
  5388. continue;
  5389. }
  5390. ast_node(fv, FieldValue, arg);
  5391. if (fv->field->kind != Ast_Ident) {
  5392. continue;
  5393. }
  5394. String key = fv->field->Ident.token.string;
  5395. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5396. Type *t = procs[proc_index]->type;
  5397. if (is_type_proc(t)) {
  5398. isize param_index = lookup_procedure_parameter(t, key);
  5399. if (param_index < 0) {
  5400. array_unordered_remove(&procs, proc_index);
  5401. }
  5402. }
  5403. }
  5404. }
  5405. if (procs.count == 0) {
  5406. // if any of the named arguments are wrong, the `procs` will be empty
  5407. // just start from scratch
  5408. array_free(&procs);
  5409. procs = proc_group_entities_cloned(c, *operand);
  5410. }
  5411. // filter by positional argument length
  5412. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5413. Entity *proc = procs[proc_index];
  5414. Type *pt = base_type(proc->type);
  5415. if (!(pt != nullptr && is_type_proc(pt))) {
  5416. proc_index++;
  5417. continue;
  5418. }
  5419. isize param_count = 0;
  5420. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5421. if (param_count_excluding_defaults > max_arg_count) {
  5422. array_unordered_remove(&procs, proc_index);
  5423. continue;
  5424. }
  5425. proc_index++;
  5426. }
  5427. }
  5428. Entity **lhs = nullptr;
  5429. isize lhs_count = -1;
  5430. bool is_variadic = false;
  5431. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5432. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5433. defer (array_free(&positional_operands));
  5434. defer (array_free(&named_operands));
  5435. if (procs.count == 1) {
  5436. Entity *e = procs[0];
  5437. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5438. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5439. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5440. check_call_arguments_single(c, call, operand,
  5441. e, e->type,
  5442. positional_operands, named_operands,
  5443. CallArgumentErrorMode::ShowErrors,
  5444. &data);
  5445. }
  5446. return data;
  5447. }
  5448. {
  5449. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5450. // where the same positional parameter has the same type value (and ellipsis)
  5451. isize proc_arg_count = -1;
  5452. for (Entity *p : procs) {
  5453. Type *pt = base_type(p->type);
  5454. if (pt != nullptr && is_type_proc(pt)) {
  5455. if (proc_arg_count < 0) {
  5456. proc_arg_count = pt->Proc.param_count;
  5457. } else {
  5458. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5459. }
  5460. }
  5461. }
  5462. if (proc_arg_count >= 0) {
  5463. lhs_count = proc_arg_count;
  5464. if (lhs_count > 0) {
  5465. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5466. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5467. Entity *e = nullptr;
  5468. for (Entity *p : procs) {
  5469. Type *pt = base_type(p->type);
  5470. if (!(pt != nullptr && is_type_proc(pt))) {
  5471. continue;
  5472. }
  5473. if (e == nullptr) {
  5474. e = pt->Proc.params->Tuple.variables[param_index];
  5475. } else {
  5476. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5477. if (e == f) {
  5478. continue;
  5479. }
  5480. if (are_types_identical(e->type, f->type)) {
  5481. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5482. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5483. if (ee == fe) {
  5484. continue;
  5485. }
  5486. }
  5487. // NOTE(bill): Entities are not close enough to be used
  5488. e = nullptr;
  5489. break;
  5490. }
  5491. }
  5492. lhs[param_index] = e;
  5493. }
  5494. }
  5495. }
  5496. }
  5497. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5498. for_array(i, named_args) {
  5499. Ast *arg = named_args[i];
  5500. if (arg->kind != Ast_FieldValue) {
  5501. error(arg, "Expected a 'field = value'");
  5502. return data;
  5503. }
  5504. ast_node(fv, FieldValue, arg);
  5505. if (fv->field->kind != Ast_Ident) {
  5506. gbString expr_str = expr_to_string(fv->field);
  5507. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5508. gb_string_free(expr_str);
  5509. return data;
  5510. }
  5511. String key = fv->field->Ident.token.string;
  5512. Ast *value = fv->value;
  5513. Type *type_hint = nullptr;
  5514. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5515. Entity *e = lhs[lhs_idx];
  5516. if (e != nullptr && e->token.string == key &&
  5517. !is_type_polymorphic(e->type)) {
  5518. type_hint = e->type;
  5519. break;
  5520. }
  5521. }
  5522. Operand o = {};
  5523. check_expr_with_type_hint(c, &o, value, type_hint);
  5524. array_add(&named_operands, o);
  5525. }
  5526. gb_free(heap_allocator(), lhs);
  5527. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5528. defer (array_free(&valids));
  5529. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5530. defer (array_free(&proc_entities));
  5531. for (Entity *proc : procs) {
  5532. array_add(&proc_entities, proc);
  5533. }
  5534. gbString expr_name = expr_to_string(operand->expr);
  5535. defer (gb_string_free(expr_name));
  5536. for_array(i, procs) {
  5537. Entity *p = procs[i];
  5538. Type *pt = base_type(p->type);
  5539. if (pt != nullptr && is_type_proc(pt)) {
  5540. CallArgumentData data = {};
  5541. CheckerContext ctx = *c;
  5542. ctx.no_polymorphic_errors = true;
  5543. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5544. ctx.hide_polymorphic_errors = true;
  5545. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5546. p, pt,
  5547. positional_operands, named_operands,
  5548. CallArgumentErrorMode::NoErrors,
  5549. &data);
  5550. if (!is_a_candidate) {
  5551. continue;
  5552. }
  5553. isize index = i;
  5554. ValidIndexAndScore item = {};
  5555. item.score = data.score;
  5556. if (data.gen_entity != nullptr) {
  5557. array_add(&proc_entities, data.gen_entity);
  5558. index = proc_entities.count-1;
  5559. // prefer non-polymorphic procedures over polymorphic
  5560. item.score += assign_score_function(1);
  5561. }
  5562. item.index = index;
  5563. array_add(&valids, item);
  5564. }
  5565. }
  5566. if (valids.count > 1) {
  5567. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  5568. i64 best_score = valids[0].score;
  5569. Entity *best_entity = proc_entities[valids[0].index];
  5570. GB_ASSERT(best_entity != nullptr);
  5571. for (isize i = 1; i < valids.count; i++) {
  5572. if (best_score > valids[i].score) {
  5573. valids.count = i;
  5574. break;
  5575. }
  5576. if (best_entity == proc_entities[valids[i].index]) {
  5577. valids.count = i;
  5578. break;
  5579. }
  5580. }
  5581. }
  5582. auto print_argument_types = [&]() {
  5583. error_line("\tGiven argument types: (");
  5584. isize i = 0;
  5585. for (Operand const &o : positional_operands) {
  5586. if (i++ > 0) error_line(", ");
  5587. gbString type = type_to_string(o.type);
  5588. defer (gb_string_free(type));
  5589. error_line("%s", type);
  5590. }
  5591. for (Operand const &o : named_operands) {
  5592. if (i++ > 0) error_line(", ");
  5593. gbString type = type_to_string(o.type);
  5594. defer (gb_string_free(type));
  5595. if (i < ce->split_args->named.count) {
  5596. Ast *named_field = ce->split_args->named[i];
  5597. ast_node(fv, FieldValue, named_field);
  5598. gbString field = expr_to_string(fv->field);
  5599. defer (gb_string_free(field));
  5600. error_line("%s = %s", field, type);
  5601. } else {
  5602. error_line("%s", type);
  5603. }
  5604. }
  5605. error_line(")\n");
  5606. };
  5607. if (valids.count == 0) {
  5608. ERROR_BLOCK();
  5609. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5610. if (positional_operands.count == 0 && named_operands.count == 0) {
  5611. error_line("\tNo given arguments\n");
  5612. } else {
  5613. print_argument_types();
  5614. }
  5615. if (procs.count == 0) {
  5616. procs = proc_group_entities_cloned(c, *operand);
  5617. }
  5618. if (procs.count > 0) {
  5619. error_line("Did you mean to use one of the following:\n");
  5620. }
  5621. isize max_name_length = 0;
  5622. isize max_type_length = 0;
  5623. for (Entity *proc : procs) {
  5624. Type *t = base_type(proc->type);
  5625. if (t == t_invalid) continue;
  5626. String prefix = {};
  5627. String prefix_sep = {};
  5628. if (proc->pkg) {
  5629. prefix = proc->pkg->name;
  5630. prefix_sep = str_lit(".");
  5631. }
  5632. String name = proc->token.string;
  5633. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5634. gbString pt;
  5635. if (t->Proc.node != nullptr) {
  5636. pt = expr_to_string(t->Proc.node);
  5637. } else {
  5638. pt = type_to_string(t);
  5639. }
  5640. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5641. gb_string_free(pt);
  5642. }
  5643. isize max_spaces = gb_max(max_name_length, max_type_length);
  5644. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5645. for (isize i = 0; i < max_spaces; i++) {
  5646. spaces[i] = ' ';
  5647. }
  5648. spaces[max_spaces] = 0;
  5649. for (Entity *proc : procs) {
  5650. TokenPos pos = proc->token.pos;
  5651. Type *t = base_type(proc->type);
  5652. if (t == t_invalid) continue;
  5653. GB_ASSERT(t->kind == Type_Proc);
  5654. gbString pt;
  5655. defer (gb_string_free(pt));
  5656. if (t->Proc.node != nullptr) {
  5657. pt = expr_to_string(t->Proc.node);
  5658. } else {
  5659. pt = type_to_string(t);
  5660. }
  5661. String prefix = {};
  5662. String prefix_sep = {};
  5663. if (proc->pkg) {
  5664. prefix = proc->pkg->name;
  5665. prefix_sep = str_lit(".");
  5666. }
  5667. String name = proc->token.string;
  5668. isize len = prefix.len + prefix_sep.len + name.len;
  5669. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5670. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5671. char const *sep = "::";
  5672. if (proc->kind == Entity_Variable) {
  5673. sep = ":=";
  5674. }
  5675. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5676. LIT(prefix), LIT(prefix_sep), LIT(name),
  5677. name_padding, spaces,
  5678. sep,
  5679. pt,
  5680. type_padding, spaces,
  5681. token_pos_to_string(pos)
  5682. );
  5683. }
  5684. if (procs.count > 0) {
  5685. error_line("\n");
  5686. }
  5687. data.result_type = t_invalid;
  5688. } else if (valids.count > 1) {
  5689. ERROR_BLOCK();
  5690. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5691. print_argument_types();
  5692. for (auto const &valid : valids) {
  5693. Entity *proc = proc_entities[valid.index];
  5694. GB_ASSERT(proc != nullptr);
  5695. TokenPos pos = proc->token.pos;
  5696. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5697. gbString pt = nullptr;
  5698. defer (gb_string_free(pt));
  5699. if (t->Proc.node != nullptr) {
  5700. pt = expr_to_string(t->Proc.node);
  5701. } else {
  5702. pt = type_to_string(t);
  5703. }
  5704. String name = proc->token.string;
  5705. char const *sep = "::";
  5706. if (proc->kind == Entity_Variable) {
  5707. sep = ":=";
  5708. }
  5709. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5710. if (proc->decl_info->proc_lit != nullptr) {
  5711. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5712. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5713. if (pl->where_token.kind != Token_Invalid) {
  5714. error_line("\n\t\twhere ");
  5715. for_array(j, pl->where_clauses) {
  5716. Ast *clause = pl->where_clauses[j];
  5717. if (j != 0) {
  5718. error_line("\t\t ");
  5719. }
  5720. gbString str = expr_to_string(clause);
  5721. error_line("%s", str);
  5722. gb_string_free(str);
  5723. if (j != pl->where_clauses.count-1) {
  5724. error_line(",");
  5725. }
  5726. }
  5727. error_line("\n\t");
  5728. }
  5729. }
  5730. error_line("at %s\n", token_pos_to_string(pos));
  5731. }
  5732. data.result_type = t_invalid;
  5733. } else {
  5734. GB_ASSERT(valids.count == 1);
  5735. Ast *ident = operand->expr;
  5736. while (ident->kind == Ast_SelectorExpr) {
  5737. Ast *s = ident->SelectorExpr.selector;
  5738. ident = s;
  5739. }
  5740. Entity *e = proc_entities[valids[0].index];
  5741. GB_ASSERT(e != nullptr);
  5742. Array<Operand> named_operands = {};
  5743. check_call_arguments_single(c, call, operand,
  5744. e, e->type,
  5745. positional_operands, named_operands,
  5746. CallArgumentErrorMode::ShowErrors,
  5747. &data);
  5748. return data;
  5749. }
  5750. return data;
  5751. }
  5752. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5753. Type *proc_type = nullptr;
  5754. CallArgumentData data = {};
  5755. data.result_type = t_invalid;
  5756. proc_type = base_type(operand->type);
  5757. TypeProc *pt = nullptr;
  5758. if (proc_type) {
  5759. pt = &proc_type->Proc;
  5760. }
  5761. TEMPORARY_ALLOCATOR_GUARD();
  5762. ast_node(ce, CallExpr, call);
  5763. bool any_failure = false;
  5764. // Split positional and named args into separate arrays/slices
  5765. Slice<Ast *> positional_args = {};
  5766. Slice<Ast *> named_args = {};
  5767. if (ce->split_args == nullptr) {
  5768. positional_args = ce->args;
  5769. for (isize i = 0; i < ce->args.count; i++) {
  5770. Ast *arg = ce->args.data[i];
  5771. if (arg->kind == Ast_FieldValue) {
  5772. positional_args.count = i;
  5773. break;
  5774. }
  5775. }
  5776. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5777. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5778. split_args->positional = positional_args;
  5779. split_args->named = named_args;
  5780. ce->split_args = split_args;
  5781. } else {
  5782. positional_args = ce->split_args->positional;
  5783. named_args = ce->split_args->named;
  5784. }
  5785. if (operand->mode == Addressing_ProcGroup) {
  5786. return check_call_arguments_proc_group(c, operand, call);
  5787. }
  5788. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5789. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5790. defer (array_free(&positional_operands));
  5791. defer (array_free(&named_operands));
  5792. if (positional_args.count > 0) {
  5793. isize lhs_count = -1;
  5794. bool is_variadic = false;
  5795. Entity **lhs = nullptr;
  5796. if (pt != nullptr) {
  5797. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5798. }
  5799. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5800. }
  5801. if (named_args.count > 0) {
  5802. for_array(i, named_args) {
  5803. Ast *arg = named_args[i];
  5804. if (arg->kind != Ast_FieldValue) {
  5805. error(arg, "Expected a 'field = value'");
  5806. return data;
  5807. }
  5808. ast_node(fv, FieldValue, arg);
  5809. if (fv->field->kind != Ast_Ident) {
  5810. gbString expr_str = expr_to_string(fv->field);
  5811. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5812. any_failure = true;
  5813. gb_string_free(expr_str);
  5814. continue;
  5815. }
  5816. String key = fv->field->Ident.token.string;
  5817. Ast *value = fv->value;
  5818. isize param_index = lookup_procedure_parameter(pt, key);
  5819. Type *type_hint = nullptr;
  5820. if (param_index >= 0) {
  5821. Entity *e = pt->params->Tuple.variables[param_index];
  5822. type_hint = e->type;
  5823. }
  5824. Operand o = {};
  5825. check_expr_with_type_hint(c, &o, value, type_hint);
  5826. if (o.mode == Addressing_Invalid) {
  5827. any_failure = true;
  5828. }
  5829. array_add(&named_operands, o);
  5830. }
  5831. }
  5832. if (!any_failure) {
  5833. check_call_arguments_single(c, call, operand,
  5834. nullptr, proc_type,
  5835. positional_operands, named_operands,
  5836. CallArgumentErrorMode::ShowErrors,
  5837. &data);
  5838. } else if (pt) {
  5839. data.result_type = pt->results;
  5840. }
  5841. return data;
  5842. }
  5843. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5844. if (!is_type_polymorphic_record(t)) {
  5845. return -1;
  5846. }
  5847. TypeTuple *params = get_record_polymorphic_params(t);
  5848. if (params == nullptr) {
  5849. return -1;
  5850. }
  5851. for_array(i, params->variables) {
  5852. Entity *e = params->variables[i];
  5853. String name = e->token.string;
  5854. if (is_blank_ident(name)) {
  5855. continue;
  5856. }
  5857. if (name == parameter_name) {
  5858. return i;
  5859. }
  5860. }
  5861. return -1;
  5862. }
  5863. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5864. ast_node(ce, CallExpr, call);
  5865. Type *original_type = operand->type;
  5866. GB_ASSERT(is_type_polymorphic_record(original_type));
  5867. bool show_error = true;
  5868. Array<Operand> operands = {};
  5869. defer (array_free(&operands));
  5870. bool named_fields = false;
  5871. {
  5872. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5873. auto prev_type_path = c->type_path;
  5874. c->type_path = new_checker_type_path();
  5875. defer ({
  5876. destroy_checker_type_path(c->type_path);
  5877. c->type_path = prev_type_path;
  5878. });
  5879. if (is_call_expr_field_value(ce)) {
  5880. named_fields = true;
  5881. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5882. for_array(i, ce->args) {
  5883. Ast *arg = ce->args[i];
  5884. ast_node(fv, FieldValue, arg);
  5885. if (fv->field->kind == Ast_Ident) {
  5886. String name = fv->field->Ident.token.string;
  5887. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5888. if (index >= 0) {
  5889. TypeTuple *params = get_record_polymorphic_params(original_type);
  5890. Entity *e = params->variables[i];
  5891. if (e->kind == Entity_Constant) {
  5892. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5893. continue;
  5894. }
  5895. }
  5896. }
  5897. check_expr_or_type(c, &operands[i], fv->value);
  5898. }
  5899. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5900. if (vari_expand) {
  5901. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5902. }
  5903. } else {
  5904. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5905. Entity **lhs = nullptr;
  5906. isize lhs_count = -1;
  5907. TypeTuple *params = get_record_polymorphic_params(original_type);
  5908. if (params != nullptr) {
  5909. lhs = params->variables.data;
  5910. lhs_count = params->variables.count;
  5911. }
  5912. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  5913. }
  5914. }
  5915. CallArgumentError err = CallArgumentError_None;
  5916. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5917. isize param_count = tuple->variables.count;
  5918. isize minimum_param_count = param_count;
  5919. for (; minimum_param_count > 0; minimum_param_count--) {
  5920. Entity *e = tuple->variables[minimum_param_count-1];
  5921. if (e->kind != Entity_Constant) {
  5922. break;
  5923. }
  5924. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5925. break;
  5926. }
  5927. }
  5928. Array<Operand> ordered_operands = operands;
  5929. if (!named_fields) {
  5930. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5931. array_copy(&ordered_operands, operands, 0);
  5932. } else {
  5933. TEMPORARY_ALLOCATOR_GUARD();
  5934. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5935. // LEAK(bill)
  5936. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5937. for_array(i, ce->args) {
  5938. Ast *arg = ce->args[i];
  5939. ast_node(fv, FieldValue, arg);
  5940. if (fv->field->kind != Ast_Ident) {
  5941. if (show_error) {
  5942. gbString expr_str = expr_to_string(fv->field);
  5943. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5944. gb_string_free(expr_str);
  5945. }
  5946. err = CallArgumentError_InvalidFieldValue;
  5947. continue;
  5948. }
  5949. String name = fv->field->Ident.token.string;
  5950. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5951. if (index < 0) {
  5952. if (show_error) {
  5953. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5954. }
  5955. err = CallArgumentError_ParameterNotFound;
  5956. continue;
  5957. }
  5958. if (visited[index]) {
  5959. if (show_error) {
  5960. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5961. }
  5962. err = CallArgumentError_DuplicateParameter;
  5963. continue;
  5964. }
  5965. visited[index] = true;
  5966. ordered_operands[index] = operands[i];
  5967. }
  5968. for (isize i = 0; i < param_count; i++) {
  5969. if (!visited[i]) {
  5970. Entity *e = tuple->variables[i];
  5971. if (is_blank_ident(e->token)) {
  5972. continue;
  5973. }
  5974. if (show_error) {
  5975. if (e->kind == Entity_TypeName) {
  5976. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5977. LIT(e->token.string));
  5978. } else {
  5979. gbString str = type_to_string(e->type);
  5980. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5981. LIT(e->token.string), str);
  5982. gb_string_free(str);
  5983. }
  5984. }
  5985. err = CallArgumentError_ParameterMissing;
  5986. }
  5987. }
  5988. }
  5989. if (err != 0) {
  5990. operand->mode = Addressing_Invalid;
  5991. return err;
  5992. }
  5993. while (ordered_operands.count > 0) {
  5994. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5995. break;
  5996. }
  5997. array_pop(&ordered_operands);
  5998. }
  5999. if (minimum_param_count != param_count) {
  6000. if (param_count < ordered_operands.count) {
  6001. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6002. err = CallArgumentError_TooManyArguments;
  6003. } else if (minimum_param_count > ordered_operands.count) {
  6004. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6005. err = CallArgumentError_TooFewArguments;
  6006. }
  6007. } else {
  6008. if (param_count < ordered_operands.count) {
  6009. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6010. err = CallArgumentError_TooManyArguments;
  6011. } else if (param_count > ordered_operands.count) {
  6012. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6013. err = CallArgumentError_TooFewArguments;
  6014. }
  6015. }
  6016. if (err != 0) {
  6017. return err;
  6018. }
  6019. if (minimum_param_count != param_count) {
  6020. array_resize(&ordered_operands, param_count);
  6021. isize missing_count = 0;
  6022. // NOTE(bill): Replace missing operands with the default values (if possible)
  6023. for_array(i, ordered_operands) {
  6024. Operand *o = &ordered_operands[i];
  6025. if (o->expr == nullptr) {
  6026. Entity *e = tuple->variables[i];
  6027. if (e->kind == Entity_Constant) {
  6028. missing_count += 1;
  6029. o->mode = Addressing_Constant;
  6030. o->type = default_type(e->type);
  6031. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6032. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6033. o->value = e->Constant.param_value.value;
  6034. }
  6035. } else if (e->kind == Entity_TypeName) {
  6036. missing_count += 1;
  6037. o->mode = Addressing_Type;
  6038. o->type = e->type;
  6039. o->expr = e->identifier;
  6040. }
  6041. }
  6042. }
  6043. }
  6044. isize oo_count = gb_min(param_count, ordered_operands.count);
  6045. i64 score = 0;
  6046. for (isize i = 0; i < oo_count; i++) {
  6047. Entity *e = tuple->variables[i];
  6048. Operand *o = &ordered_operands[i];
  6049. if (o->mode == Addressing_Invalid) {
  6050. continue;
  6051. }
  6052. if (e->kind == Entity_TypeName) {
  6053. if (o->mode != Addressing_Type) {
  6054. if (show_error) {
  6055. gbString expr = expr_to_string(o->expr);
  6056. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6057. gb_string_free(expr);
  6058. }
  6059. err = CallArgumentError_WrongTypes;
  6060. }
  6061. if (are_types_identical(e->type, o->type)) {
  6062. score += assign_score_function(1);
  6063. } else {
  6064. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6065. }
  6066. } else {
  6067. i64 s = 0;
  6068. if (o->type->kind == Type_Generic) {
  6069. // Polymorphic name!
  6070. score += assign_score_function(1);
  6071. continue;
  6072. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6073. if (show_error) {
  6074. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6075. }
  6076. err = CallArgumentError_WrongTypes;
  6077. }
  6078. o->type = e->type;
  6079. if (o->mode != Addressing_Constant) {
  6080. bool valid = false;
  6081. if (is_type_proc(o->type)) {
  6082. Entity *proc_entity = entity_from_expr(o->expr);
  6083. valid = proc_entity != nullptr;
  6084. }
  6085. if (!valid) {
  6086. if (show_error) {
  6087. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6088. }
  6089. err = CallArgumentError_NoneConstantParameter;
  6090. }
  6091. }
  6092. score += s;
  6093. }
  6094. // NOTE(bill): Add type info the parameters
  6095. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6096. // add_type_info_type(c, o->type);
  6097. }
  6098. if (show_error && err) {
  6099. return err;
  6100. }
  6101. {
  6102. bool failure = false;
  6103. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  6104. if (found_entity) {
  6105. operand->mode = Addressing_Type;
  6106. operand->type = found_entity->type;
  6107. return err;
  6108. }
  6109. CheckerContext ctx = *c;
  6110. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6111. ctx.scope = polymorphic_record_parent_scope(original_type);
  6112. GB_ASSERT(ctx.scope != nullptr);
  6113. Type *bt = base_type(original_type);
  6114. String generated_name = make_string_c(expr_to_string(call));
  6115. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6116. if (bt->kind == Type_Struct) {
  6117. Ast *node = clone_ast(bt->Struct.node);
  6118. Type *struct_type = alloc_type_struct();
  6119. struct_type->Struct.node = node;
  6120. struct_type->Struct.polymorphic_parent = original_type;
  6121. set_base_type(named_type, struct_type);
  6122. check_open_scope(&ctx, node);
  6123. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6124. check_close_scope(&ctx);
  6125. } else if (bt->kind == Type_Union) {
  6126. Ast *node = clone_ast(bt->Union.node);
  6127. Type *union_type = alloc_type_union();
  6128. union_type->Union.node = node;
  6129. union_type->Union.polymorphic_parent = original_type;
  6130. set_base_type(named_type, union_type);
  6131. check_open_scope(&ctx, node);
  6132. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6133. check_close_scope(&ctx);
  6134. } else {
  6135. GB_PANIC("Unsupported parametric polymorphic record type");
  6136. }
  6137. bt = base_type(named_type);
  6138. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6139. GB_ASSERT(original_type->kind == Type_Named);
  6140. Entity *e = original_type->Named.type_name;
  6141. GB_ASSERT(e->kind == Entity_TypeName);
  6142. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6143. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6144. Type *params = nullptr;
  6145. switch (bt->kind) {
  6146. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6147. case Type_Union: params = bt->Union.polymorphic_params; break;
  6148. }
  6149. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6150. Entity *v = params->Tuple.variables[i];
  6151. String name = v->token.string;
  6152. if (i > 0) {
  6153. s = gb_string_append_fmt(s, ", ");
  6154. }
  6155. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6156. if (v->kind == Entity_TypeName) {
  6157. if (v->type->kind != Type_Generic) {
  6158. s = gb_string_append_fmt(s, "=");
  6159. s = write_type_to_string(s, v->type, false);
  6160. }
  6161. } else if (v->kind == Entity_Constant) {
  6162. s = gb_string_append_fmt(s, "=");
  6163. s = write_exact_value_to_string(s, v->Constant.value);
  6164. }
  6165. }
  6166. s = gb_string_append_fmt(s, ")");
  6167. String new_name = make_string_c(s);
  6168. named_type->Named.name = new_name;
  6169. if (named_type->Named.type_name) {
  6170. named_type->Named.type_name->token.string = new_name;
  6171. }
  6172. }
  6173. operand->mode = Addressing_Type;
  6174. operand->type = named_type;
  6175. }
  6176. return err;
  6177. }
  6178. // returns true on success
  6179. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6180. bool success = true;
  6181. if (args.count > 0) {
  6182. if (allow_mixed) {
  6183. bool was_named = false;
  6184. for (Ast *arg : args) {
  6185. if (was_named && arg->kind != Ast_FieldValue) {
  6186. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6187. success = false;
  6188. break;
  6189. }
  6190. was_named = was_named || arg->kind == Ast_FieldValue;
  6191. }
  6192. } else {
  6193. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6194. for (Ast *arg : args) {
  6195. bool mix = false;
  6196. if (first_is_field_value) {
  6197. mix = arg->kind != Ast_FieldValue;
  6198. } else {
  6199. mix = arg->kind == Ast_FieldValue;
  6200. }
  6201. if (mix) {
  6202. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6203. success = false;
  6204. }
  6205. }
  6206. }
  6207. }
  6208. return success;
  6209. }
  6210. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6211. operand->mode = Addressing_Invalid; \
  6212. operand->expr = call; \
  6213. return Expr_Stmt; \
  6214. }
  6215. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6216. if (proc != nullptr &&
  6217. proc->kind == Ast_BasicDirective) {
  6218. ast_node(bd, BasicDirective, proc);
  6219. String name = bd->name.string;
  6220. if (
  6221. name == "location" ||
  6222. name == "assert" ||
  6223. name == "panic" ||
  6224. name == "defined" ||
  6225. name == "config" ||
  6226. name == "load" ||
  6227. name == "load_directory" ||
  6228. name == "load_hash"
  6229. ) {
  6230. operand->mode = Addressing_Builtin;
  6231. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6232. operand->expr = proc;
  6233. operand->type = t_invalid;
  6234. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6235. } else {
  6236. error(proc, "Unknown directive: #%.*s", LIT(name));
  6237. operand->expr = proc;
  6238. operand->type = t_invalid;
  6239. operand->mode = Addressing_Invalid;
  6240. return Expr_Expr;
  6241. }
  6242. if (inlining != ProcInlining_none) {
  6243. error(call, "Inlining operators are not allowed on built-in procedures");
  6244. }
  6245. } else {
  6246. if (proc != nullptr) {
  6247. check_expr_or_type(c, operand, proc);
  6248. } else {
  6249. GB_ASSERT(operand->expr != nullptr);
  6250. }
  6251. }
  6252. if (operand->mode == Addressing_Invalid) {
  6253. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6254. for (Ast *arg : args) {
  6255. if (arg->kind == Ast_FieldValue) {
  6256. arg = arg->FieldValue.value;
  6257. }
  6258. check_expr_base(c, operand, arg, nullptr);
  6259. }
  6260. operand->mode = Addressing_Invalid;
  6261. operand->expr = call;
  6262. return Expr_Stmt;
  6263. }
  6264. if (operand->mode == Addressing_Type) {
  6265. Type *t = operand->type;
  6266. if (is_type_polymorphic_record(t)) {
  6267. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6268. if (!is_type_named(t)) {
  6269. gbString s = expr_to_string(operand->expr);
  6270. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6271. gb_string_free(s);
  6272. operand->mode = Addressing_Invalid;
  6273. operand->type = t_invalid;;
  6274. return Expr_Expr;
  6275. }
  6276. auto err = check_polymorphic_record_type(c, operand, call);
  6277. if (err == 0) {
  6278. Ast *ident = operand->expr;
  6279. while (ident->kind == Ast_SelectorExpr) {
  6280. Ast *s = ident->SelectorExpr.selector;
  6281. ident = s;
  6282. }
  6283. Type *ot = operand->type;
  6284. GB_ASSERT(ot->kind == Type_Named);
  6285. Entity *e = ot->Named.type_name;
  6286. add_entity_use(c, ident, e);
  6287. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6288. } else {
  6289. operand->mode = Addressing_Invalid;
  6290. operand->type = t_invalid;
  6291. }
  6292. } else {
  6293. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6294. operand->mode = Addressing_Invalid;
  6295. isize arg_count = args.count;
  6296. switch (arg_count) {
  6297. case 0:
  6298. {
  6299. gbString str = type_to_string(t);
  6300. error(call, "Missing argument in conversion to '%s'", str);
  6301. gb_string_free(str);
  6302. } break;
  6303. default:
  6304. {
  6305. gbString str = type_to_string(t);
  6306. error(call, "Too many arguments in conversion to '%s'", str);
  6307. gb_string_free(str);
  6308. } break;
  6309. case 1: {
  6310. Ast *arg = args[0];
  6311. if (arg->kind == Ast_FieldValue) {
  6312. error(call, "'field = value' cannot be used in a type conversion");
  6313. arg = arg->FieldValue.value;
  6314. // NOTE(bill): Carry on the cast regardless
  6315. }
  6316. check_expr_with_type_hint(c, operand, arg, t);
  6317. if (operand->mode != Addressing_Invalid) {
  6318. if (is_type_polymorphic(t)) {
  6319. error(call, "A polymorphic type cannot be used in a type conversion");
  6320. } else {
  6321. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6322. // as it assumes it is determining the type
  6323. check_cast(c, operand, t);
  6324. }
  6325. }
  6326. operand->type = t;
  6327. operand->expr = call;
  6328. if (operand->mode != Addressing_Invalid) {
  6329. update_untyped_expr_type(c, arg, t, false);
  6330. }
  6331. break;
  6332. }
  6333. }
  6334. }
  6335. return Expr_Expr;
  6336. }
  6337. if (operand->mode == Addressing_Builtin) {
  6338. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6339. i32 id = operand->builtin_id;
  6340. Entity *e = entity_of_node(operand->expr);
  6341. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6342. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6343. }
  6344. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6345. operand->mode = Addressing_Invalid;
  6346. operand->type = t_invalid;
  6347. }
  6348. operand->expr = call;
  6349. return builtin_procs[id].kind;
  6350. }
  6351. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6352. Entity *initial_entity = entity_of_node(operand->expr);
  6353. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6354. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6355. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6356. if (c->decl) {
  6357. c->decl->defer_used += 1;
  6358. }
  6359. }
  6360. add_entity_use(c, operand->expr, initial_entity);
  6361. if (initial_entity->Procedure.entry_point_only) {
  6362. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6363. // Okay
  6364. } else {
  6365. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6366. }
  6367. }
  6368. }
  6369. if (operand->mode != Addressing_ProcGroup) {
  6370. Type *proc_type = base_type(operand->type);
  6371. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6372. bool valid_mode = is_operand_value(*operand);
  6373. if (!valid_type || !valid_mode) {
  6374. Ast *e = operand->expr;
  6375. gbString str = expr_to_string(e);
  6376. gbString type_str = type_to_string(operand->type);
  6377. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6378. gb_string_free(type_str);
  6379. gb_string_free(str);
  6380. operand->mode = Addressing_Invalid;
  6381. operand->expr = call;
  6382. return Expr_Stmt;
  6383. }
  6384. }
  6385. CallArgumentData data = check_call_arguments(c, operand, call);
  6386. Type *result_type = data.result_type;
  6387. gb_zero_item(operand);
  6388. operand->expr = call;
  6389. if (result_type == t_invalid) {
  6390. operand->mode = Addressing_Invalid;
  6391. operand->type = t_invalid;
  6392. return Expr_Stmt;
  6393. }
  6394. Type *pt = base_type(operand->type);
  6395. if (pt == nullptr) {
  6396. pt = t_invalid;
  6397. }
  6398. if (pt == t_invalid) {
  6399. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6400. pt = type_of_expr(operand->expr->CallExpr.proc);
  6401. }
  6402. if (pt == t_invalid && data.gen_entity) {
  6403. pt = data.gen_entity->type;
  6404. }
  6405. }
  6406. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6407. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6408. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6409. }
  6410. }
  6411. if (result_type == nullptr) {
  6412. operand->mode = Addressing_NoValue;
  6413. } else {
  6414. GB_ASSERT(is_type_tuple(result_type));
  6415. isize count = result_type->Tuple.variables.count;
  6416. switch (count) {
  6417. case 0:
  6418. operand->mode = Addressing_NoValue;
  6419. break;
  6420. case 1:
  6421. operand->mode = Addressing_Value;
  6422. operand->type = result_type->Tuple.variables[0]->type;
  6423. break;
  6424. default:
  6425. operand->mode = Addressing_Value;
  6426. operand->type = result_type;
  6427. break;
  6428. }
  6429. }
  6430. switch (inlining) {
  6431. case ProcInlining_inline:
  6432. if (proc != nullptr) {
  6433. Entity *e = entity_from_expr(proc);
  6434. if (e != nullptr && e->kind == Entity_Procedure) {
  6435. DeclInfo *decl = e->decl_info;
  6436. if (decl->proc_lit) {
  6437. ast_node(pl, ProcLit, decl->proc_lit);
  6438. if (pl->inlining == ProcInlining_no_inline) {
  6439. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6440. }
  6441. }
  6442. }
  6443. }
  6444. break;
  6445. case ProcInlining_no_inline:
  6446. break;
  6447. }
  6448. operand->expr = call;
  6449. {
  6450. Type *type = nullptr;
  6451. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6452. type = type_of_expr(operand->expr->CallExpr.proc);
  6453. }
  6454. if (type == nullptr) {
  6455. type = pt;
  6456. }
  6457. type = base_type(type);
  6458. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6459. operand->mode = Addressing_OptionalOk;
  6460. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6461. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6462. operand->expr->CallExpr.optional_ok_one = true;
  6463. }
  6464. }
  6465. }
  6466. return Expr_Expr;
  6467. }
  6468. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6469. check_expr_base(c, o, e, t);
  6470. check_not_tuple(c, o);
  6471. char const *err_str = nullptr;
  6472. switch (o->mode) {
  6473. case Addressing_NoValue:
  6474. err_str = "used as a value";
  6475. break;
  6476. case Addressing_Type:
  6477. if (t == nullptr || !is_type_typeid(t)) {
  6478. err_str = "is not an expression but a type, in this context it is ambiguous";
  6479. }
  6480. break;
  6481. case Addressing_Builtin:
  6482. err_str = "must be called";
  6483. break;
  6484. }
  6485. if (err_str != nullptr) {
  6486. gbString str = expr_to_string(e);
  6487. error(e, "'%s' %s", str, err_str);
  6488. gb_string_free(str);
  6489. o->mode = Addressing_Invalid;
  6490. }
  6491. }
  6492. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6493. switch (t->kind) {
  6494. case Type_Basic:
  6495. if (t->Basic.kind == Basic_string) {
  6496. if (o->mode == Addressing_Constant) {
  6497. *max_count = o->value.value_string.len;
  6498. }
  6499. if (o->mode != Addressing_Constant) {
  6500. o->mode = Addressing_Value;
  6501. }
  6502. o->type = t_u8;
  6503. return true;
  6504. } else if (t->Basic.kind == Basic_UntypedString) {
  6505. if (o->mode == Addressing_Constant) {
  6506. *max_count = o->value.value_string.len;
  6507. o->type = t_u8;
  6508. return true;
  6509. }
  6510. return false;
  6511. }
  6512. break;
  6513. case Type_MultiPointer:
  6514. o->type = t->MultiPointer.elem;
  6515. if (o->mode != Addressing_Constant) {
  6516. o->mode = Addressing_Variable;
  6517. }
  6518. return true;
  6519. case Type_Array:
  6520. *max_count = t->Array.count;
  6521. if (indirection) {
  6522. o->mode = Addressing_Variable;
  6523. } else if (o->mode != Addressing_Variable &&
  6524. o->mode != Addressing_Constant) {
  6525. o->mode = Addressing_Value;
  6526. }
  6527. o->type = t->Array.elem;
  6528. return true;
  6529. case Type_EnumeratedArray:
  6530. *max_count = t->EnumeratedArray.count;
  6531. if (indirection) {
  6532. o->mode = Addressing_Variable;
  6533. } else if (o->mode != Addressing_Variable &&
  6534. o->mode != Addressing_Constant) {
  6535. o->mode = Addressing_Value;
  6536. }
  6537. o->type = t->EnumeratedArray.elem;
  6538. return true;
  6539. case Type_Matrix:
  6540. *max_count = t->Matrix.column_count;
  6541. if (indirection) {
  6542. o->mode = Addressing_Variable;
  6543. } else if (o->mode != Addressing_Variable) {
  6544. o->mode = Addressing_Value;
  6545. }
  6546. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6547. return true;
  6548. case Type_Slice:
  6549. o->type = t->Slice.elem;
  6550. if (o->mode != Addressing_Constant) {
  6551. o->mode = Addressing_Variable;
  6552. }
  6553. return true;
  6554. case Type_RelativeMultiPointer:
  6555. {
  6556. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6557. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6558. o->type = pointer_type->MultiPointer.elem;
  6559. if (o->mode != Addressing_Constant) {
  6560. o->mode = Addressing_Variable;
  6561. }
  6562. }
  6563. return true;
  6564. case Type_DynamicArray:
  6565. o->type = t->DynamicArray.elem;
  6566. if (o->mode != Addressing_Constant) {
  6567. o->mode = Addressing_Variable;
  6568. }
  6569. return true;
  6570. case Type_Struct:
  6571. if (t->Struct.soa_kind != StructSoa_None) {
  6572. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6573. *max_count = t->Struct.soa_count;
  6574. }
  6575. o->type = t->Struct.soa_elem;
  6576. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  6577. o->mode = Addressing_SoaVariable;
  6578. } else {
  6579. o->mode = Addressing_Value;
  6580. }
  6581. return true;
  6582. }
  6583. return false;
  6584. }
  6585. if (is_type_pointer(original_type) && indirection) {
  6586. Type *ptr = base_type(original_type);
  6587. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6588. o->type = ptr->Pointer.elem;
  6589. o->mode = Addressing_Value;
  6590. return true;
  6591. }
  6592. }
  6593. return false;
  6594. }
  6595. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6596. if (is_type_untyped_uninit(x)) {
  6597. return true;
  6598. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6599. return true;
  6600. } else if (is_type_untyped_uninit(y)) {
  6601. return true;
  6602. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6603. return true;
  6604. }
  6605. return are_types_identical(x, y);
  6606. }
  6607. gb_internal bool check_range(CheckerContext *c, Ast *node, bool is_for_loop, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  6608. if (!is_ast_range(node)) {
  6609. return false;
  6610. }
  6611. ast_node(ie, BinaryExpr, node);
  6612. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6613. if (x->mode == Addressing_Invalid) {
  6614. return false;
  6615. }
  6616. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6617. if (y->mode == Addressing_Invalid) {
  6618. return false;
  6619. }
  6620. convert_to_typed(c, x, y->type);
  6621. if (x->mode == Addressing_Invalid) {
  6622. return false;
  6623. }
  6624. convert_to_typed(c, y, x->type);
  6625. if (y->mode == Addressing_Invalid) {
  6626. return false;
  6627. }
  6628. convert_to_typed(c, x, default_type(y->type));
  6629. if (x->mode == Addressing_Invalid) {
  6630. return false;
  6631. }
  6632. convert_to_typed(c, y, default_type(x->type));
  6633. if (y->mode == Addressing_Invalid) {
  6634. return false;
  6635. }
  6636. if (!are_types_identical(x->type, y->type)) {
  6637. if (x->type != t_invalid &&
  6638. y->type != t_invalid) {
  6639. gbString xt = type_to_string(x->type);
  6640. gbString yt = type_to_string(y->type);
  6641. gbString expr_str = expr_to_string(x->expr);
  6642. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6643. gb_string_free(expr_str);
  6644. gb_string_free(yt);
  6645. gb_string_free(xt);
  6646. }
  6647. return false;
  6648. }
  6649. Type *type = x->type;
  6650. if (is_for_loop) {
  6651. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6652. error(ie->op, "Only numerical types are allowed within interval expressions");
  6653. return false;
  6654. }
  6655. } else {
  6656. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6657. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6658. return false;
  6659. }
  6660. }
  6661. if (x->mode == Addressing_Constant &&
  6662. y->mode == Addressing_Constant) {
  6663. ExactValue a = x->value;
  6664. ExactValue b = y->value;
  6665. GB_ASSERT(are_types_identical(x->type, y->type));
  6666. TokenKind op = Token_Lt;
  6667. switch (ie->op.kind) {
  6668. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6669. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6670. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6671. default: error(ie->op, "Invalid range operator"); break;
  6672. }
  6673. bool ok = compare_exact_values(op, a, b);
  6674. if (!ok) {
  6675. // TODO(bill): Better error message
  6676. error(ie->op, "Invalid interval range");
  6677. return false;
  6678. }
  6679. ExactValue inline_for_depth = exact_value_sub(b, a);
  6680. if (ie->op.kind != Token_RangeHalf) {
  6681. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6682. }
  6683. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6684. } else if (inline_for_depth_ != nullptr) {
  6685. error(ie->op, "Interval expressions must be constant");
  6686. return false;
  6687. }
  6688. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6689. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6690. return true;
  6691. }
  6692. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6693. if (is_operand_nil(*o)) {
  6694. return true;
  6695. }
  6696. Ast *expr = unparen_expr(o->expr);
  6697. if (expr != nullptr) {
  6698. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6699. if (e != nullptr && e->kind == Entity_Procedure) {
  6700. return true;
  6701. }
  6702. if (expr->kind == Ast_ProcLit) {
  6703. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6704. return true;
  6705. }
  6706. }
  6707. return o->mode == Addressing_Constant;
  6708. }
  6709. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6710. if (is_type_enum(th)) {
  6711. Type *enum_type = base_type(th);
  6712. GB_ASSERT(enum_type->kind == Type_Enum);
  6713. String name = ise->selector->Ident.token.string;
  6714. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6715. if (e == nullptr) {
  6716. return false;
  6717. }
  6718. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6719. GB_ASSERT(e->kind == Entity_Constant);
  6720. o->value = e->Constant.value;
  6721. o->mode = Addressing_Constant;
  6722. o->type = e->type;
  6723. return true;
  6724. }
  6725. if (is_type_union(th)) {
  6726. TEMPORARY_ALLOCATOR_GUARD();
  6727. Type *union_type = base_type(th);
  6728. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6729. for (Type *vt : union_type->Union.variants) {
  6730. Operand x = {};
  6731. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6732. array_add(&operands, x);
  6733. }
  6734. }
  6735. if (operands.count == 1) {
  6736. *o = operands[0];
  6737. return true;
  6738. }
  6739. }
  6740. return false;
  6741. }
  6742. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6743. ast_node(ise, ImplicitSelectorExpr, node);
  6744. o->type = t_invalid;
  6745. o->expr = node;
  6746. o->mode = Addressing_Invalid;
  6747. Type *th = type_hint;
  6748. if (th == nullptr) {
  6749. gbString str = expr_to_string(node);
  6750. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6751. gb_string_free(str);
  6752. return Expr_Expr;
  6753. }
  6754. o->type = th;
  6755. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6756. if (!ok) {
  6757. String name = ise->selector->Ident.token.string;
  6758. if (is_type_enum(th)) {
  6759. ERROR_BLOCK();
  6760. Type *bt = base_type(th);
  6761. GB_ASSERT(bt->kind == Type_Enum);
  6762. gbString typ = type_to_string(th);
  6763. defer (gb_string_free(typ));
  6764. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6765. check_did_you_mean_type(name, bt->Enum.fields);
  6766. } else {
  6767. gbString typ = type_to_string(th);
  6768. gbString str = expr_to_string(node);
  6769. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6770. gb_string_free(str);
  6771. gb_string_free(typ);
  6772. }
  6773. }
  6774. o->expr = node;
  6775. return Expr_Expr;
  6776. }
  6777. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  6778. switch (x->mode) {
  6779. case Addressing_MapIndex:
  6780. case Addressing_OptionalOk:
  6781. case Addressing_OptionalOkPtr:
  6782. if (val_type_) *val_type_ = x->type;
  6783. break;
  6784. default:
  6785. if (ok_type_) *ok_type_ = x->type;
  6786. return;
  6787. }
  6788. Ast *expr = unparen_expr(x->expr);
  6789. if (expr->kind == Ast_CallExpr) {
  6790. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6791. if (is_type_proc(pt)) {
  6792. Type *tuple = pt->Proc.results;
  6793. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6794. if (pt->Proc.result_count >= 2) {
  6795. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6796. }
  6797. expr->CallExpr.optional_ok_one = false;
  6798. x->type = tuple;
  6799. return;
  6800. }
  6801. }
  6802. Type *tuple = make_optional_ok_type(x->type);
  6803. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6804. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6805. x->type = tuple;
  6806. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6807. }
  6808. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6809. ast_node(ie, MatrixIndexExpr, node);
  6810. check_expr(c, o, ie->expr);
  6811. node->viral_state_flags |= ie->expr->viral_state_flags;
  6812. if (o->mode == Addressing_Invalid) {
  6813. o->expr = node;
  6814. return;
  6815. }
  6816. Type *t = base_type(type_deref(o->type));
  6817. bool is_ptr = is_type_pointer(o->type);
  6818. bool is_const = o->mode == Addressing_Constant;
  6819. if (t->kind != Type_Matrix) {
  6820. gbString str = expr_to_string(o->expr);
  6821. gbString type_str = type_to_string(o->type);
  6822. defer (gb_string_free(str));
  6823. defer (gb_string_free(type_str));
  6824. if (is_const) {
  6825. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6826. } else {
  6827. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6828. }
  6829. o->mode = Addressing_Invalid;
  6830. o->expr = node;
  6831. return;
  6832. }
  6833. o->type = t->Matrix.elem;
  6834. if (is_ptr) {
  6835. o->mode = Addressing_Variable;
  6836. } else if (o->mode != Addressing_Variable) {
  6837. o->mode = Addressing_Value;
  6838. }
  6839. if (ie->row_index == nullptr) {
  6840. gbString str = expr_to_string(o->expr);
  6841. error(o->expr, "Missing row index for '%s'", str);
  6842. gb_string_free(str);
  6843. o->mode = Addressing_Invalid;
  6844. o->expr = node;
  6845. return;
  6846. }
  6847. if (ie->column_index == nullptr) {
  6848. gbString str = expr_to_string(o->expr);
  6849. error(o->expr, "Missing column index for '%s'", str);
  6850. gb_string_free(str);
  6851. o->mode = Addressing_Invalid;
  6852. o->expr = node;
  6853. return;
  6854. }
  6855. i64 row_count = t->Matrix.row_count;
  6856. i64 column_count = t->Matrix.column_count;
  6857. i64 row_index = 0;
  6858. i64 column_index = 0;
  6859. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6860. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6861. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  6862. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  6863. }
  6864. gb_unused(row_ok);
  6865. gb_unused(column_ok);
  6866. }
  6867. struct TypeAndToken {
  6868. Type *type;
  6869. Token token;
  6870. };
  6871. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  6872. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  6873. if (operand.mode != Addressing_Constant) {
  6874. return;
  6875. }
  6876. if (operand.value.kind == ExactValue_Invalid) {
  6877. return;
  6878. }
  6879. uintptr key = hash_exact_value(operand.value);
  6880. TypeAndToken *found = map_get(seen, key);
  6881. if (found != nullptr) {
  6882. TEMPORARY_ALLOCATOR_GUARD();
  6883. isize count = multi_map_count(seen, key);
  6884. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  6885. multi_map_get_all(seen, key, taps);
  6886. for (isize i = 0; i < count; i++) {
  6887. TypeAndToken tap = taps[i];
  6888. Operand to = {};
  6889. to.mode = Addressing_Value;
  6890. to.type = tap.type;
  6891. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  6892. continue;
  6893. }
  6894. TokenPos pos = tap.token.pos;
  6895. if (use_expr) {
  6896. gbString expr_str = expr_to_string(operand.expr);
  6897. error(operand.expr,
  6898. "Duplicate case '%s'\n"
  6899. "\tprevious case at %s",
  6900. expr_str,
  6901. token_pos_to_string(pos));
  6902. gb_string_free(expr_str);
  6903. } else {
  6904. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  6905. }
  6906. return;
  6907. }
  6908. }
  6909. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  6910. multi_map_insert(seen, key, tap);
  6911. }
  6912. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  6913. if (is_type_enum(x.type)) {
  6914. // TODO(bill): Fix this logic so it's fast!!!
  6915. i64 v0 = exact_value_to_i64(lhs.value);
  6916. i64 v1 = exact_value_to_i64(rhs.value);
  6917. Operand v = {};
  6918. v.mode = Addressing_Constant;
  6919. v.type = x.type;
  6920. v.expr = x.expr;
  6921. Type *bt = base_type(x.type);
  6922. GB_ASSERT(bt->kind == Type_Enum);
  6923. for (i64 vi = v0; vi <= v1; vi++) {
  6924. if (upper_op != Token_LtEq && vi == v1) {
  6925. break;
  6926. }
  6927. v.value = exact_value_i64(vi);
  6928. add_constant_switch_case(ctx, seen, v);
  6929. }
  6930. } else {
  6931. add_constant_switch_case(ctx, seen, lhs);
  6932. if (upper_op == Token_LtEq) {
  6933. add_constant_switch_case(ctx, seen, rhs);
  6934. }
  6935. }
  6936. }
  6937. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  6938. add_constant_switch_case(ctx, seen, x);
  6939. }
  6940. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6941. ast_node(bd, BasicDirective, node);
  6942. ExprKind kind = Expr_Expr;
  6943. o->mode = Addressing_Constant;
  6944. String name = bd->name.string;
  6945. if (name == "file") {
  6946. o->type = t_untyped_string;
  6947. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6948. } else if (name == "line") {
  6949. o->type = t_untyped_integer;
  6950. o->value = exact_value_i64(bd->token.pos.line);
  6951. } else if (name == "procedure") {
  6952. if (c->curr_proc_decl == nullptr) {
  6953. error(node, "#procedure may only be used within procedures");
  6954. o->type = t_untyped_string;
  6955. o->value = exact_value_string(str_lit(""));
  6956. } else {
  6957. o->type = t_untyped_string;
  6958. o->value = exact_value_string(c->proc_name);
  6959. }
  6960. } else if (name == "caller_location") {
  6961. init_core_source_code_location(c->checker);
  6962. error(node, "#caller_location may only be used as a default argument parameter");
  6963. o->type = t_source_code_location;
  6964. o->mode = Addressing_Value;
  6965. } else {
  6966. if (name == "location") {
  6967. init_core_source_code_location(c->checker);
  6968. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  6969. o->type = t_source_code_location;
  6970. o->mode = Addressing_Value;
  6971. } else if (
  6972. name == "assert" ||
  6973. name == "defined" ||
  6974. name == "config" ||
  6975. name == "load" ||
  6976. name == "load_hash" ||
  6977. name == "load_directory" ||
  6978. name == "load_or"
  6979. ) {
  6980. error(node, "'#%.*s' must be used as a call", LIT(name));
  6981. o->type = t_invalid;
  6982. o->mode = Addressing_Invalid;
  6983. } else {
  6984. error(node, "Unknown directive: #%.*s", LIT(name));
  6985. o->type = t_invalid;
  6986. o->mode = Addressing_Invalid;
  6987. }
  6988. }
  6989. return kind;
  6990. }
  6991. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6992. ExprKind kind = Expr_Expr;
  6993. Operand cond = {Addressing_Invalid};
  6994. ast_node(te, TernaryIfExpr, node);
  6995. check_expr(c, &cond, te->cond);
  6996. node->viral_state_flags |= te->cond->viral_state_flags;
  6997. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6998. error(te->cond, "Non-boolean condition in ternary if expression");
  6999. }
  7000. Operand x = {Addressing_Invalid};
  7001. Operand y = {Addressing_Invalid};
  7002. check_expr_or_type(c, &x, te->x, type_hint);
  7003. node->viral_state_flags |= te->x->viral_state_flags;
  7004. if (te->y != nullptr) {
  7005. Type *th = type_hint;
  7006. if (type_hint == nullptr && is_type_typed(x.type)) {
  7007. th = x.type;
  7008. }
  7009. check_expr_or_type(c, &y, te->y, th);
  7010. node->viral_state_flags |= te->y->viral_state_flags;
  7011. } else {
  7012. error(node, "A ternary expression must have an else clause");
  7013. return kind;
  7014. }
  7015. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7016. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7017. gbString type_string = expr_to_string(type_expr);
  7018. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7019. gb_string_free(type_string);
  7020. return kind;
  7021. }
  7022. if (x.type == nullptr || x.type == t_invalid ||
  7023. y.type == nullptr || y.type == t_invalid) {
  7024. return kind;
  7025. }
  7026. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7027. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7028. if (x.mode == Addressing_Invalid) {
  7029. return kind;
  7030. }
  7031. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7032. if (y.mode == Addressing_Invalid) {
  7033. x.mode = Addressing_Invalid;
  7034. return kind;
  7035. }
  7036. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7037. // x: union{f32} = f32(123) if cond else nil
  7038. if (type_hint && !is_type_any(type_hint)) {
  7039. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7040. check_cast(c, &x, type_hint);
  7041. check_cast(c, &y, type_hint);
  7042. }
  7043. }
  7044. if (!ternary_compare_types(x.type, y.type)) {
  7045. gbString its = type_to_string(x.type);
  7046. gbString ets = type_to_string(y.type);
  7047. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7048. gb_string_free(ets);
  7049. gb_string_free(its);
  7050. return kind;
  7051. }
  7052. o->type = x.type;
  7053. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7054. o->type = y.type;
  7055. }
  7056. o->mode = Addressing_Value;
  7057. o->expr = node;
  7058. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7059. if (check_cast_internal(c, &x, type_hint) &&
  7060. check_cast_internal(c, &y, type_hint)) {
  7061. convert_to_typed(c, o, type_hint);
  7062. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7063. o->type = type_hint;
  7064. }
  7065. }
  7066. return kind;
  7067. }
  7068. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7069. ExprKind kind = Expr_Expr;
  7070. Operand cond = {};
  7071. ast_node(te, TernaryWhenExpr, node);
  7072. check_expr(c, &cond, te->cond);
  7073. node->viral_state_flags |= te->cond->viral_state_flags;
  7074. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7075. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7076. return kind;
  7077. }
  7078. if (cond.value.value_bool) {
  7079. check_expr_or_type(c, o, te->x, type_hint);
  7080. node->viral_state_flags |= te->x->viral_state_flags;
  7081. } else {
  7082. if (te->y != nullptr) {
  7083. check_expr_or_type(c, o, te->y, type_hint);
  7084. node->viral_state_flags |= te->y->viral_state_flags;
  7085. } else {
  7086. error(node, "A ternary when expression must have an else clause");
  7087. return kind;
  7088. }
  7089. }
  7090. return kind;
  7091. }
  7092. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7093. ast_node(oe, OrElseExpr, node);
  7094. String name = oe->token.string;
  7095. Ast *arg = oe->x;
  7096. Ast *default_value = oe->y;
  7097. Operand x = {};
  7098. Operand y = {};
  7099. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7100. if (is_load_directive_call(arg)) {
  7101. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7102. // Allow for chaining of '#load(path) or_else #load(path)'
  7103. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7104. bool y_is_diverging = false;
  7105. check_expr_base(c, &y, default_value, x.type);
  7106. switch (y.mode) {
  7107. case Addressing_NoValue:
  7108. if (is_diverging_expr(y.expr)) {
  7109. // Allow
  7110. y.mode = Addressing_Value;
  7111. y_is_diverging = true;
  7112. } else {
  7113. error_operand_no_value(&y);
  7114. y.mode = Addressing_Invalid;
  7115. }
  7116. break;
  7117. case Addressing_Type:
  7118. error_operand_not_expression(&y);
  7119. y.mode = Addressing_Invalid;
  7120. break;
  7121. }
  7122. if (y.mode == Addressing_Invalid) {
  7123. o->mode = Addressing_Value;
  7124. o->type = t_invalid;
  7125. o->expr = node;
  7126. return Expr_Expr;
  7127. }
  7128. if (!y_is_diverging) {
  7129. check_assignment(c, &y, x.type, name);
  7130. if (y.mode != Addressing_Constant) {
  7131. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7132. }
  7133. }
  7134. }
  7135. if (res == LoadDirective_Success) {
  7136. *o = x;
  7137. } else {
  7138. *o = y;
  7139. }
  7140. o->expr = node;
  7141. return Expr_Expr;
  7142. }
  7143. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7144. if (x.mode == Addressing_Invalid) {
  7145. o->mode = Addressing_Value;
  7146. o->type = t_invalid;
  7147. o->expr = node;
  7148. return Expr_Expr;
  7149. }
  7150. bool y_is_diverging = false;
  7151. check_expr_base(c, &y, default_value, x.type);
  7152. switch (y.mode) {
  7153. case Addressing_NoValue:
  7154. if (is_diverging_expr(y.expr)) {
  7155. // Allow
  7156. y.mode = Addressing_Value;
  7157. y_is_diverging = true;
  7158. } else {
  7159. error_operand_no_value(&y);
  7160. y.mode = Addressing_Invalid;
  7161. }
  7162. break;
  7163. case Addressing_Type:
  7164. error_operand_not_expression(&y);
  7165. y.mode = Addressing_Invalid;
  7166. break;
  7167. }
  7168. if (y.mode == Addressing_Invalid) {
  7169. o->mode = Addressing_Value;
  7170. o->type = t_invalid;
  7171. o->expr = node;
  7172. return Expr_Expr;
  7173. }
  7174. Type *left_type = nullptr;
  7175. Type *right_type = nullptr;
  7176. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7177. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7178. if (left_type != nullptr) {
  7179. if (!y_is_diverging) {
  7180. check_assignment(c, &y, left_type, name);
  7181. }
  7182. } else {
  7183. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7184. }
  7185. if (left_type == nullptr) {
  7186. left_type = t_invalid;
  7187. }
  7188. o->mode = Addressing_Value;
  7189. o->type = left_type;
  7190. o->expr = node;
  7191. return Expr_Expr;
  7192. }
  7193. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7194. ast_node(re, OrReturnExpr, node);
  7195. String name = re->token.string;
  7196. Operand x = {};
  7197. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7198. if (x.mode == Addressing_Invalid) {
  7199. o->mode = Addressing_Value;
  7200. o->type = t_invalid;
  7201. o->expr = node;
  7202. return Expr_Expr;
  7203. }
  7204. Type *left_type = nullptr;
  7205. Type *right_type = nullptr;
  7206. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7207. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7208. if (right_type == nullptr) {
  7209. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7210. } else {
  7211. Type *proc_type = base_type(c->curr_proc_sig);
  7212. GB_ASSERT(proc_type->kind == Type_Proc);
  7213. Type *result_type = proc_type->Proc.results;
  7214. if (result_type == nullptr) {
  7215. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7216. } else {
  7217. GB_ASSERT(result_type->kind == Type_Tuple);
  7218. auto const &vars = result_type->Tuple.variables;
  7219. Type *end_type = vars[vars.count-1]->type;
  7220. if (vars.count > 1) {
  7221. if (!proc_type->Proc.has_named_results) {
  7222. error(node, "'%.*s' within a procedure with more than 1 return value requires that the return values are named, allowing for early return", LIT(name));
  7223. }
  7224. }
  7225. Operand rhs = {};
  7226. rhs.type = right_type;
  7227. rhs.mode = Addressing_Value;
  7228. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7229. // NOTE(bill): allow implicit conversion between boolean types
  7230. // within 'or_return' to improve the experience using third-party code
  7231. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7232. // TODO(bill): better error message
  7233. gbString a = type_to_string(right_type);
  7234. gbString b = type_to_string(end_type);
  7235. gbString ret_type = type_to_string(result_type);
  7236. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7237. if (vars.count == 1) {
  7238. error_line("\tProcedure return value type: %s\n", ret_type);
  7239. } else {
  7240. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7241. }
  7242. gb_string_free(ret_type);
  7243. gb_string_free(b);
  7244. gb_string_free(a);
  7245. }
  7246. }
  7247. }
  7248. o->expr = node;
  7249. o->type = left_type;
  7250. if (left_type != nullptr) {
  7251. o->mode = Addressing_Value;
  7252. } else {
  7253. o->mode = Addressing_NoValue;
  7254. }
  7255. if (c->curr_proc_sig == nullptr) {
  7256. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7257. }
  7258. if (c->in_defer) {
  7259. error(node, "'or_return' cannot be used within a defer statement");
  7260. }
  7261. return Expr_Expr;
  7262. }
  7263. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7264. ast_node(be, OrBranchExpr, node);
  7265. String name = be->token.string;
  7266. Operand x = {};
  7267. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7268. if (x.mode == Addressing_Invalid) {
  7269. o->mode = Addressing_Value;
  7270. o->type = t_invalid;
  7271. o->expr = node;
  7272. return Expr_Expr;
  7273. }
  7274. Type *left_type = nullptr;
  7275. Type *right_type = nullptr;
  7276. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7277. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7278. if (right_type == nullptr) {
  7279. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7280. } else {
  7281. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7282. // okay
  7283. } else {
  7284. gbString s = type_to_string(right_type);
  7285. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7286. gb_string_free(s);
  7287. }
  7288. }
  7289. o->expr = node;
  7290. o->type = left_type;
  7291. if (left_type != nullptr) {
  7292. o->mode = Addressing_Value;
  7293. } else {
  7294. o->mode = Addressing_NoValue;
  7295. }
  7296. if (c->curr_proc_sig == nullptr) {
  7297. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7298. }
  7299. Ast *label = be->label;
  7300. switch (be->token.kind) {
  7301. case Token_or_break:
  7302. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7303. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7304. }
  7305. break;
  7306. case Token_or_continue:
  7307. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7308. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7309. }
  7310. break;
  7311. }
  7312. if (label != nullptr) {
  7313. if (label->kind != Ast_Ident) {
  7314. error(label, "A branch statement's label name must be an identifier");
  7315. return Expr_Expr;
  7316. }
  7317. Ast *ident = label;
  7318. String name = ident->Ident.token.string;
  7319. Operand o = {};
  7320. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7321. if (e == nullptr) {
  7322. error(ident, "Undeclared label name: %.*s", LIT(name));
  7323. return Expr_Expr;
  7324. }
  7325. add_entity_use(c, ident, e);
  7326. if (e->kind != Entity_Label) {
  7327. error(ident, "'%.*s' is not a label", LIT(name));
  7328. return Expr_Expr;
  7329. }
  7330. Ast *parent = e->Label.parent;
  7331. GB_ASSERT(parent != nullptr);
  7332. switch (parent->kind) {
  7333. case Ast_BlockStmt:
  7334. case Ast_IfStmt:
  7335. case Ast_SwitchStmt:
  7336. if (be->token.kind != Token_or_break) {
  7337. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7338. }
  7339. break;
  7340. case Ast_RangeStmt:
  7341. case Ast_ForStmt:
  7342. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7343. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7344. }
  7345. break;
  7346. }
  7347. }
  7348. return Expr_Expr;
  7349. }
  7350. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7351. Type *bt = base_type(type);
  7352. StringSet fields_visited = {};
  7353. defer (string_set_destroy(&fields_visited));
  7354. StringMap<String> fields_visited_through_raw_union = {};
  7355. defer (string_map_destroy(&fields_visited_through_raw_union));
  7356. for (Ast *elem : elems) {
  7357. if (elem->kind != Ast_FieldValue) {
  7358. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7359. continue;
  7360. }
  7361. ast_node(fv, FieldValue, elem);
  7362. if (fv->field->kind != Ast_Ident) {
  7363. gbString expr_str = expr_to_string(fv->field);
  7364. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7365. gb_string_free(expr_str);
  7366. continue;
  7367. }
  7368. String name = fv->field->Ident.token.string;
  7369. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7370. bool is_unknown = sel.entity == nullptr;
  7371. if (is_unknown) {
  7372. error(fv->field, "Unknown field '%.*s' in structure literal", LIT(name));
  7373. continue;
  7374. }
  7375. Entity *field = bt->Struct.fields[sel.index[0]];
  7376. add_entity_use(c, fv->field, field);
  7377. if (string_set_update(&fields_visited, name)) {
  7378. if (sel.index.count > 1) {
  7379. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7380. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7381. } else {
  7382. error(fv->field, "Duplicate or reused field '%.*s' in structure literal", LIT(sel.entity->token.string));
  7383. }
  7384. } else {
  7385. error(fv->field, "Duplicate field '%.*s' in structure literal", LIT(field->token.string));
  7386. }
  7387. continue;
  7388. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7389. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7390. continue;
  7391. }
  7392. if (sel.indirect) {
  7393. error(fv->field, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a structure literal", cast(int)sel.index.count-1, LIT(name));
  7394. continue;
  7395. }
  7396. if (sel.index.count > 1) {
  7397. if (is_constant) {
  7398. Type *ft = type;
  7399. for (i32 index : sel.index) {
  7400. Type *bt = base_type(ft);
  7401. switch (bt->kind) {
  7402. case Type_Struct:
  7403. if (bt->Struct.is_raw_union) {
  7404. is_constant = false;
  7405. break;
  7406. }
  7407. ft = bt->Struct.fields[index]->type;
  7408. break;
  7409. case Type_Array:
  7410. ft = bt->Array.elem;
  7411. break;
  7412. default:
  7413. GB_PANIC("invalid type: %s", type_to_string(ft));
  7414. break;
  7415. }
  7416. }
  7417. if (is_constant &&
  7418. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7419. is_constant = false;
  7420. }
  7421. }
  7422. Type *nested_ft = bt;
  7423. for (i32 index : sel.index) {
  7424. Type *bt = base_type(nested_ft);
  7425. switch (bt->kind) {
  7426. case Type_Struct:
  7427. if (bt->Struct.is_raw_union) {
  7428. for (Entity *re : bt->Struct.fields) {
  7429. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7430. }
  7431. }
  7432. nested_ft = bt->Struct.fields[index]->type;
  7433. break;
  7434. case Type_Array:
  7435. nested_ft = bt->Array.elem;
  7436. break;
  7437. default:
  7438. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7439. break;
  7440. }
  7441. }
  7442. field = sel.entity;
  7443. }
  7444. Operand o = {};
  7445. check_expr_or_type(c, &o, fv->value, field->type);
  7446. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7447. is_constant = false;
  7448. }
  7449. if (is_constant) {
  7450. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7451. }
  7452. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7453. }
  7454. }
  7455. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7456. ExprKind kind = Expr_Expr;
  7457. ast_node(cl, CompoundLit, node);
  7458. Type *type = type_hint;
  7459. if (type != nullptr && is_type_untyped(type)) {
  7460. type = nullptr;
  7461. }
  7462. bool is_to_be_determined_array_count = false;
  7463. bool is_constant = true;
  7464. if (cl->type != nullptr) {
  7465. type = nullptr;
  7466. // [?]Type
  7467. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  7468. Ast *count = cl->type->ArrayType.count;
  7469. if (count->kind == Ast_UnaryExpr &&
  7470. count->UnaryExpr.op.kind == Token_Question) {
  7471. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  7472. is_to_be_determined_array_count = true;
  7473. }
  7474. if (cl->elems.count > 0) {
  7475. if (cl->type->ArrayType.tag != nullptr) {
  7476. Ast *tag = cl->type->ArrayType.tag;
  7477. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7478. String name = tag->BasicDirective.name.string;
  7479. if (name == "soa") {
  7480. error(node, "#soa arrays are not supported for compound literals");
  7481. return kind;
  7482. }
  7483. }
  7484. }
  7485. }
  7486. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  7487. if (cl->elems.count > 0) {
  7488. Ast *tag = cl->type->DynamicArrayType.tag;
  7489. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7490. String name = tag->BasicDirective.name.string;
  7491. if (name == "soa") {
  7492. error(node, "#soa arrays are not supported for compound literals");
  7493. return kind;
  7494. }
  7495. }
  7496. }
  7497. if (type == nullptr) {
  7498. type = check_type(c, cl->type);
  7499. }
  7500. }
  7501. if (type == nullptr) {
  7502. error(node, "Missing type in compound literal");
  7503. return kind;
  7504. }
  7505. Type *t = base_type(type);
  7506. if (is_type_polymorphic(t)) {
  7507. gbString str = type_to_string(type);
  7508. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7509. o->expr = node;
  7510. o->type = type;
  7511. gb_string_free(str);
  7512. return kind;
  7513. }
  7514. switch (t->kind) {
  7515. case Type_Struct: {
  7516. if (cl->elems.count == 0) {
  7517. break; // NOTE(bill): No need to init
  7518. }
  7519. if (t->Struct.is_raw_union) {
  7520. if (cl->elems.count > 0) {
  7521. // NOTE: unions cannot be constant
  7522. is_constant = false;
  7523. if (cl->elems[0]->kind != Ast_FieldValue) {
  7524. gbString type_str = type_to_string(type);
  7525. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7526. gb_string_free(type_str);
  7527. } else {
  7528. if (cl->elems.count != 1) {
  7529. gbString type_str = type_to_string(type);
  7530. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain up to 1 'field = value' element, got %td", type_str, cl->elems.count);
  7531. gb_string_free(type_str);
  7532. } else {
  7533. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7534. }
  7535. }
  7536. }
  7537. break;
  7538. }
  7539. isize field_count = t->Struct.fields.count;
  7540. isize min_field_count = t->Struct.fields.count;
  7541. for (isize i = min_field_count-1; i >= 0; i--) {
  7542. Entity *e = t->Struct.fields[i];
  7543. GB_ASSERT(e->kind == Entity_Variable);
  7544. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7545. min_field_count--;
  7546. } else {
  7547. break;
  7548. }
  7549. }
  7550. if (cl->elems[0]->kind == Ast_FieldValue) {
  7551. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7552. } else {
  7553. bool seen_field_value = false;
  7554. for_array(index, cl->elems) {
  7555. Entity *field = nullptr;
  7556. Ast *elem = cl->elems[index];
  7557. if (elem->kind == Ast_FieldValue) {
  7558. seen_field_value = true;
  7559. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7560. continue;
  7561. } else if (seen_field_value) {
  7562. error(elem, "Value elements cannot be used after a 'field = value'");
  7563. continue;
  7564. }
  7565. if (index >= field_count) {
  7566. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7567. break;
  7568. }
  7569. if (field == nullptr) {
  7570. field = t->Struct.fields[index];
  7571. }
  7572. Operand o = {};
  7573. check_expr_or_type(c, &o, elem, field->type);
  7574. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7575. is_constant = false;
  7576. }
  7577. if (is_constant) {
  7578. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7579. }
  7580. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7581. }
  7582. if (cl->elems.count < field_count) {
  7583. if (min_field_count < field_count) {
  7584. if (cl->elems.count < min_field_count) {
  7585. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7586. }
  7587. } else {
  7588. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7589. }
  7590. }
  7591. }
  7592. break;
  7593. }
  7594. case Type_Slice:
  7595. case Type_Array:
  7596. case Type_DynamicArray:
  7597. case Type_SimdVector:
  7598. case Type_Matrix:
  7599. {
  7600. Type *elem_type = nullptr;
  7601. String context_name = {};
  7602. i64 max_type_count = -1;
  7603. if (t->kind == Type_Slice) {
  7604. elem_type = t->Slice.elem;
  7605. context_name = str_lit("slice literal");
  7606. } else if (t->kind == Type_Array) {
  7607. elem_type = t->Array.elem;
  7608. context_name = str_lit("array literal");
  7609. if (!is_to_be_determined_array_count) {
  7610. max_type_count = t->Array.count;
  7611. }
  7612. } else if (t->kind == Type_DynamicArray) {
  7613. elem_type = t->DynamicArray.elem;
  7614. context_name = str_lit("dynamic array literal");
  7615. is_constant = false;
  7616. if (!build_context.no_dynamic_literals) {
  7617. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7618. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7619. }
  7620. } else if (t->kind == Type_SimdVector) {
  7621. elem_type = t->SimdVector.elem;
  7622. context_name = str_lit("simd vector literal");
  7623. max_type_count = t->SimdVector.count;
  7624. } else if (t->kind == Type_Matrix) {
  7625. elem_type = t->Matrix.elem;
  7626. context_name = str_lit("matrix literal");
  7627. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7628. } else {
  7629. GB_PANIC("unreachable");
  7630. }
  7631. i64 max = 0;
  7632. Type *bet = base_type(elem_type);
  7633. if (!elem_type_can_be_constant(bet)) {
  7634. is_constant = false;
  7635. }
  7636. if (bet == t_invalid) {
  7637. break;
  7638. }
  7639. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7640. RangeCache rc = range_cache_make(heap_allocator());
  7641. defer (range_cache_destroy(&rc));
  7642. for (Ast *elem : cl->elems) {
  7643. if (elem->kind != Ast_FieldValue) {
  7644. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7645. continue;
  7646. }
  7647. ast_node(fv, FieldValue, elem);
  7648. if (is_ast_range(fv->field)) {
  7649. Token op = fv->field->BinaryExpr.op;
  7650. Operand x = {};
  7651. Operand y = {};
  7652. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7653. if (!ok) {
  7654. continue;
  7655. }
  7656. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7657. error(x.expr, "Expected a constant integer as an array field");
  7658. continue;
  7659. }
  7660. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7661. error(y.expr, "Expected a constant integer as an array field");
  7662. continue;
  7663. }
  7664. i64 lo = exact_value_to_i64(x.value);
  7665. i64 hi = exact_value_to_i64(y.value);
  7666. i64 max_index = hi;
  7667. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7668. hi -= 1;
  7669. } else { // .. (inclusive)
  7670. max_index += 1;
  7671. }
  7672. bool new_range = range_cache_add_range(&rc, lo, hi);
  7673. if (!new_range) {
  7674. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7675. continue;
  7676. }
  7677. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7678. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7679. continue;
  7680. }
  7681. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7682. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7683. continue;
  7684. }
  7685. if (max < hi) {
  7686. max = max_index;
  7687. }
  7688. Operand operand = {};
  7689. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7690. check_assignment(c, &operand, elem_type, context_name);
  7691. is_constant = is_constant && operand.mode == Addressing_Constant;
  7692. } else {
  7693. Operand op_index = {};
  7694. check_expr(c, &op_index, fv->field);
  7695. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7696. error(elem, "Expected a constant integer as an array field");
  7697. continue;
  7698. }
  7699. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7700. i64 index = exact_value_to_i64(op_index.value);
  7701. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7702. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7703. continue;
  7704. }
  7705. bool new_index = range_cache_add_index(&rc, index);
  7706. if (!new_index) {
  7707. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7708. continue;
  7709. }
  7710. if (max < index+1) {
  7711. max = index+1;
  7712. }
  7713. Operand operand = {};
  7714. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7715. check_assignment(c, &operand, elem_type, context_name);
  7716. is_constant = is_constant && operand.mode == Addressing_Constant;
  7717. }
  7718. }
  7719. cl->max_count = max;
  7720. } else {
  7721. isize index = 0;
  7722. for (; index < cl->elems.count; index++) {
  7723. Ast *e = cl->elems[index];
  7724. if (e == nullptr) {
  7725. error(node, "Invalid literal element");
  7726. continue;
  7727. }
  7728. if (e->kind == Ast_FieldValue) {
  7729. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7730. continue;
  7731. }
  7732. if (0 <= max_type_count && max_type_count <= index) {
  7733. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7734. }
  7735. Operand operand = {};
  7736. check_expr_with_type_hint(c, &operand, e, elem_type);
  7737. check_assignment(c, &operand, elem_type, context_name);
  7738. is_constant = is_constant && operand.mode == Addressing_Constant;
  7739. }
  7740. if (max < index) {
  7741. max = index;
  7742. }
  7743. }
  7744. if (t->kind == Type_Array) {
  7745. if (is_to_be_determined_array_count) {
  7746. t->Array.count = max;
  7747. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7748. if (0 < max && max < t->Array.count) {
  7749. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7750. }
  7751. }
  7752. }
  7753. if (t->kind == Type_SimdVector) {
  7754. if (!is_constant) {
  7755. // error(node, "Expected all constant elements for a simd vector");
  7756. }
  7757. }
  7758. if (t->kind == Type_DynamicArray) {
  7759. if (build_context.no_dynamic_literals && cl->elems.count) {
  7760. error(node, "Compound literals of dynamic types have been disabled");
  7761. }
  7762. }
  7763. if (t->kind == Type_Matrix) {
  7764. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7765. if (0 < max && max < max_type_count) {
  7766. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7767. }
  7768. }
  7769. }
  7770. break;
  7771. }
  7772. case Type_EnumeratedArray:
  7773. {
  7774. Type *elem_type = t->EnumeratedArray.elem;
  7775. Type *index_type = t->EnumeratedArray.index;
  7776. String context_name = str_lit("enumerated array literal");
  7777. i64 max_type_count = t->EnumeratedArray.count;
  7778. gbString index_type_str = type_to_string(index_type);
  7779. defer (gb_string_free(index_type_str));
  7780. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7781. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7782. String total_lo_string = {};
  7783. String total_hi_string = {};
  7784. GB_ASSERT(is_type_enum(index_type));
  7785. {
  7786. Type *bt = base_type(index_type);
  7787. GB_ASSERT(bt->kind == Type_Enum);
  7788. for (Entity *f : bt->Enum.fields) {
  7789. if (f->kind != Entity_Constant) {
  7790. continue;
  7791. }
  7792. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7793. total_lo_string = f->token.string;
  7794. }
  7795. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7796. total_hi_string = f->token.string;
  7797. }
  7798. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. i64 max = 0;
  7804. Type *bet = base_type(elem_type);
  7805. if (!elem_type_can_be_constant(bet)) {
  7806. is_constant = false;
  7807. }
  7808. if (bet == t_invalid) {
  7809. break;
  7810. }
  7811. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  7812. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  7813. defer (map_destroy(&seen));
  7814. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7815. RangeCache rc = range_cache_make(heap_allocator());
  7816. defer (range_cache_destroy(&rc));
  7817. for (Ast *elem : cl->elems) {
  7818. if (elem->kind != Ast_FieldValue) {
  7819. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7820. continue;
  7821. }
  7822. ast_node(fv, FieldValue, elem);
  7823. if (is_ast_range(fv->field)) {
  7824. Token op = fv->field->BinaryExpr.op;
  7825. Operand x = {};
  7826. Operand y = {};
  7827. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  7828. if (!ok) {
  7829. continue;
  7830. }
  7831. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7832. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7833. continue;
  7834. }
  7835. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7836. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7837. continue;
  7838. }
  7839. i64 lo = exact_value_to_i64(x.value);
  7840. i64 hi = exact_value_to_i64(y.value);
  7841. i64 max_index = hi;
  7842. if (op.kind == Token_RangeHalf) {
  7843. hi -= 1;
  7844. }
  7845. bool new_range = range_cache_add_range(&rc, lo, hi);
  7846. if (!new_range) {
  7847. gbString lo_str = expr_to_string(x.expr);
  7848. gbString hi_str = expr_to_string(y.expr);
  7849. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  7850. gb_string_free(hi_str);
  7851. gb_string_free(lo_str);
  7852. continue;
  7853. }
  7854. // NOTE(bill): These are sanity checks for invalid enum values
  7855. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  7856. gbString lo_str = expr_to_string(x.expr);
  7857. error(elem, "Index %s is out of bounds (%.*s .. %.*s) for %.*s", lo_str, LIT(total_lo_string), LIT(total_hi_string), LIT(context_name));
  7858. gb_string_free(lo_str);
  7859. continue;
  7860. }
  7861. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  7862. gbString hi_str = expr_to_string(y.expr);
  7863. error(elem, "Index %s is out of bounds (%.*s .. %.*s) for %.*s", hi_str, LIT(total_lo_string), LIT(total_hi_string), LIT(context_name));
  7864. gb_string_free(hi_str);
  7865. continue;
  7866. }
  7867. if (max < hi) {
  7868. max = max_index;
  7869. }
  7870. Operand operand = {};
  7871. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7872. check_assignment(c, &operand, elem_type, context_name);
  7873. is_constant = is_constant && operand.mode == Addressing_Constant;
  7874. TokenKind upper_op = Token_LtEq;
  7875. if (op.kind == Token_RangeHalf) {
  7876. upper_op = Token_Lt;
  7877. }
  7878. add_to_seen_map(c, &seen, upper_op, x, x, y);
  7879. } else {
  7880. Operand op_index = {};
  7881. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  7882. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  7883. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7884. continue;
  7885. }
  7886. i64 index = exact_value_to_i64(op_index.value);
  7887. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  7888. gbString idx_str = expr_to_string(op_index.expr);
  7889. error(elem, "Index %s is out of bounds (%.*s .. %.*s) for %.*s", idx_str, LIT(total_lo_string), LIT(total_hi_string), LIT(context_name));
  7890. gb_string_free(idx_str);
  7891. continue;
  7892. }
  7893. bool new_index = range_cache_add_index(&rc, index);
  7894. if (!new_index) {
  7895. gbString idx_str = expr_to_string(op_index.expr);
  7896. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  7897. gb_string_free(idx_str);
  7898. continue;
  7899. }
  7900. if (max < index+1) {
  7901. max = index+1;
  7902. }
  7903. Operand operand = {};
  7904. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7905. check_assignment(c, &operand, elem_type, context_name);
  7906. is_constant = is_constant && operand.mode == Addressing_Constant;
  7907. add_to_seen_map(c, &seen, op_index);
  7908. }
  7909. }
  7910. cl->max_count = max;
  7911. } else {
  7912. isize index = 0;
  7913. for (; index < cl->elems.count; index++) {
  7914. Ast *e = cl->elems[index];
  7915. if (e == nullptr) {
  7916. error(node, "Invalid literal element");
  7917. continue;
  7918. }
  7919. if (e->kind == Ast_FieldValue) {
  7920. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7921. continue;
  7922. }
  7923. if (0 <= max_type_count && max_type_count <= index) {
  7924. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7925. }
  7926. Operand operand = {};
  7927. check_expr_with_type_hint(c, &operand, e, elem_type);
  7928. check_assignment(c, &operand, elem_type, context_name);
  7929. is_constant = is_constant && operand.mode == Addressing_Constant;
  7930. }
  7931. if (max < index) {
  7932. max = index;
  7933. }
  7934. }
  7935. bool was_error = false;
  7936. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7937. if (0 < max && max < t->EnumeratedArray.count) {
  7938. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  7939. was_error = true;
  7940. } else {
  7941. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  7942. was_error = true;
  7943. }
  7944. }
  7945. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  7946. if (cl->elems.count > 0 && !was_error && !is_partial) {
  7947. TEMPORARY_ALLOCATOR_GUARD();
  7948. Type *et = base_type(index_type);
  7949. GB_ASSERT(et->kind == Type_Enum);
  7950. auto fields = et->Enum.fields;
  7951. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  7952. for (Entity *f : fields) {
  7953. if (f->kind != Entity_Constant) {
  7954. continue;
  7955. }
  7956. ExactValue v = f->Constant.value;
  7957. auto found = map_get(&seen, hash_exact_value(v));
  7958. if (!found) {
  7959. array_add(&unhandled, f);
  7960. }
  7961. }
  7962. if (unhandled.count > 0) {
  7963. ERROR_BLOCK();
  7964. if (unhandled.count == 1) {
  7965. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  7966. } else {
  7967. error(node, "Unhandled enumerated array cases:");
  7968. for_array(i, unhandled) {
  7969. Entity *f = unhandled[i];
  7970. error_line("\t%.*s\n", LIT(f->token.string));
  7971. }
  7972. }
  7973. if (!build_context.terse_errors) {
  7974. error_line("\n");
  7975. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  7976. }
  7977. }
  7978. }
  7979. break;
  7980. }
  7981. case Type_Basic: {
  7982. if (!is_type_any(t)) {
  7983. if (cl->elems.count != 0) {
  7984. gbString s = type_to_string(t);
  7985. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  7986. gb_string_free(s);
  7987. is_constant = false;
  7988. }
  7989. break;
  7990. }
  7991. if (cl->elems.count == 0) {
  7992. break; // NOTE(bill): No need to init
  7993. }
  7994. { // Checker values
  7995. Type *field_types[2] = {t_rawptr, t_typeid};
  7996. isize field_count = 2;
  7997. if (cl->elems[0]->kind == Ast_FieldValue) {
  7998. bool fields_visited[2] = {};
  7999. for_array(i, cl->elems) {
  8000. Ast *elem = cl->elems[i];
  8001. if (elem->kind != Ast_FieldValue) {
  8002. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8003. continue;
  8004. }
  8005. ast_node(fv, FieldValue, elem);
  8006. if (fv->field->kind != Ast_Ident) {
  8007. gbString expr_str = expr_to_string(fv->field);
  8008. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8009. gb_string_free(expr_str);
  8010. continue;
  8011. }
  8012. String name = fv->field->Ident.token.string;
  8013. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8014. if (sel.entity == nullptr) {
  8015. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8016. continue;
  8017. }
  8018. isize index = sel.index[0];
  8019. if (fields_visited[index]) {
  8020. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8021. continue;
  8022. }
  8023. fields_visited[index] = true;
  8024. check_expr(c, o, fv->value);
  8025. // NOTE(bill): 'any' literals can never be constant
  8026. is_constant = false;
  8027. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8028. }
  8029. } else {
  8030. for_array(index, cl->elems) {
  8031. Ast *elem = cl->elems[index];
  8032. if (elem->kind == Ast_FieldValue) {
  8033. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8034. continue;
  8035. }
  8036. check_expr(c, o, elem);
  8037. if (index >= field_count) {
  8038. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8039. break;
  8040. }
  8041. // NOTE(bill): 'any' literals can never be constant
  8042. is_constant = false;
  8043. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8044. }
  8045. if (cl->elems.count < field_count) {
  8046. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8047. }
  8048. }
  8049. }
  8050. break;
  8051. }
  8052. case Type_Map: {
  8053. if (cl->elems.count == 0) {
  8054. break;
  8055. }
  8056. is_constant = false;
  8057. { // Checker values
  8058. bool key_is_typeid = is_type_typeid(t->Map.key);
  8059. bool value_is_typeid = is_type_typeid(t->Map.value);
  8060. for (Ast *elem : cl->elems) {
  8061. if (elem->kind != Ast_FieldValue) {
  8062. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8063. continue;
  8064. }
  8065. ast_node(fv, FieldValue, elem);
  8066. if (key_is_typeid) {
  8067. check_expr_or_type(c, o, fv->field, t->Map.key);
  8068. } else {
  8069. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8070. }
  8071. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8072. if (o->mode == Addressing_Invalid) {
  8073. continue;
  8074. }
  8075. if (value_is_typeid) {
  8076. check_expr_or_type(c, o, fv->value, t->Map.value);
  8077. } else {
  8078. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8079. }
  8080. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8081. }
  8082. }
  8083. if (build_context.no_dynamic_literals && cl->elems.count) {
  8084. error(node, "Compound literals of dynamic types have been disabled");
  8085. } else {
  8086. add_map_reserve_dependencies(c);
  8087. add_map_set_dependencies(c);
  8088. }
  8089. break;
  8090. }
  8091. case Type_BitSet: {
  8092. if (cl->elems.count == 0) {
  8093. break; // NOTE(bill): No need to init
  8094. }
  8095. Type *et = base_type(t->BitSet.elem);
  8096. isize field_count = 0;
  8097. if (et->kind == Type_Enum) {
  8098. field_count = et->Enum.fields.count;
  8099. }
  8100. if (cl->elems[0]->kind == Ast_FieldValue) {
  8101. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8102. is_constant = false;
  8103. } else {
  8104. for (Ast *elem : cl->elems) {
  8105. if (elem->kind == Ast_FieldValue) {
  8106. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8107. continue;
  8108. }
  8109. check_expr_with_type_hint(c, o, elem, et);
  8110. if (is_constant) {
  8111. is_constant = o->mode == Addressing_Constant;
  8112. }
  8113. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8114. if (o->mode == Addressing_Constant) {
  8115. i64 lower = t->BitSet.lower;
  8116. i64 upper = t->BitSet.upper;
  8117. i64 v = exact_value_to_i64(o->value);
  8118. if (lower <= v && v <= upper) {
  8119. // okay
  8120. } else {
  8121. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8122. continue;
  8123. }
  8124. }
  8125. }
  8126. }
  8127. break;
  8128. }
  8129. default: {
  8130. if (cl->elems.count == 0) {
  8131. break; // NOTE(bill): No need to init
  8132. }
  8133. gbString str = type_to_string(type);
  8134. error(node, "Invalid compound literal type '%s'", str);
  8135. gb_string_free(str);
  8136. return kind;
  8137. }
  8138. }
  8139. if (is_constant) {
  8140. o->mode = Addressing_Constant;
  8141. if (is_type_bit_set(type)) {
  8142. // NOTE(bill): Encode as an integer
  8143. Type *bt = base_type(type);
  8144. BigInt bits = {};
  8145. BigInt one = {};
  8146. big_int_from_u64(&one, 1);
  8147. for (Ast *e : cl->elems) {
  8148. GB_ASSERT(e->kind != Ast_FieldValue);
  8149. TypeAndValue tav = e->tav;
  8150. if (tav.mode != Addressing_Constant) {
  8151. continue;
  8152. }
  8153. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8154. i64 v = big_int_to_i64(&tav.value.value_integer);
  8155. i64 lower = bt->BitSet.lower;
  8156. u64 index = cast(u64)(v-lower);
  8157. BigInt bit = {};
  8158. big_int_from_u64(&bit, index);
  8159. big_int_shl(&bit, &one, &bit);
  8160. big_int_or(&bits, &bits, &bit);
  8161. }
  8162. o->value.kind = ExactValue_Integer;
  8163. o->value.value_integer = bits;
  8164. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8165. ExactValue value = exact_value_compound(node);
  8166. Type *bt = core_type(type);
  8167. if (bt->kind == Type_Basic) {
  8168. if (bt->Basic.flags & BasicFlag_Boolean) {
  8169. value = exact_value_bool(false);
  8170. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8171. value = exact_value_i64(0);
  8172. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8173. value = exact_value_i64(0);
  8174. } else if (bt->Basic.flags & BasicFlag_Float) {
  8175. value = exact_value_float(0);
  8176. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8177. value = exact_value_complex(0, 0);
  8178. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8179. value = exact_value_quaternion(0, 0, 0, 0);
  8180. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8181. value = exact_value_pointer(0);
  8182. } else if (bt->Basic.flags & BasicFlag_String) {
  8183. String empty_string = {};
  8184. value = exact_value_string(empty_string);
  8185. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8186. value = exact_value_i64(0);
  8187. }
  8188. }
  8189. o->value = value;
  8190. } else {
  8191. o->value = exact_value_compound(node);
  8192. }
  8193. } else {
  8194. o->mode = Addressing_Value;
  8195. }
  8196. o->type = type;
  8197. return kind;
  8198. }
  8199. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8200. ExprKind kind = Expr_Expr;
  8201. ast_node(ta, TypeAssertion, node);
  8202. check_expr(c, o, ta->expr);
  8203. node->viral_state_flags |= ta->expr->viral_state_flags;
  8204. if (o->mode == Addressing_Invalid) {
  8205. o->expr = node;
  8206. return kind;
  8207. }
  8208. if (o->mode == Addressing_Constant) {
  8209. gbString expr_str = expr_to_string(o->expr);
  8210. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8211. gb_string_free(expr_str);
  8212. o->mode = Addressing_Invalid;
  8213. o->expr = node;
  8214. return kind;
  8215. }
  8216. if (is_type_untyped(o->type)) {
  8217. gbString expr_str = expr_to_string(o->expr);
  8218. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8219. gb_string_free(expr_str);
  8220. o->mode = Addressing_Invalid;
  8221. o->expr = node;
  8222. return kind;
  8223. }
  8224. Type *src = type_deref(o->type);
  8225. Type *bsrc = base_type(src);
  8226. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8227. if (!is_type_union(src)) {
  8228. gbString str = type_to_string(o->type);
  8229. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8230. gb_string_free(str);
  8231. o->mode = Addressing_Invalid;
  8232. o->expr = node;
  8233. return kind;
  8234. }
  8235. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8236. bool allowed = false;
  8237. for (Type *vt : bsrc->Union.variants) {
  8238. if (are_types_identical(vt, type_hint)) {
  8239. allowed = true;
  8240. add_type_info_type(c, vt);
  8241. break;
  8242. }
  8243. }
  8244. if (allowed) {
  8245. add_type_info_type(c, o->type);
  8246. o->type = type_hint;
  8247. o->mode = Addressing_OptionalOk;
  8248. return kind;
  8249. }
  8250. }
  8251. if (bsrc->Union.variants.count != 1) {
  8252. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8253. o->mode = Addressing_Invalid;
  8254. o->expr = node;
  8255. return kind;
  8256. }
  8257. add_type_info_type(c, o->type);
  8258. add_type_info_type(c, bsrc->Union.variants[0]);
  8259. o->type = bsrc->Union.variants[0];
  8260. o->mode = Addressing_OptionalOk;
  8261. } else {
  8262. Type *t = check_type(c, ta->type);
  8263. Type *dst = t;
  8264. if (is_type_union(src)) {
  8265. bool ok = false;
  8266. for (Type *vt : bsrc->Union.variants) {
  8267. if (are_types_identical(vt, dst)) {
  8268. ok = true;
  8269. break;
  8270. }
  8271. }
  8272. if (!ok) {
  8273. gbString expr_str = expr_to_string(o->expr);
  8274. gbString dst_type_str = type_to_string(t);
  8275. defer (gb_string_free(expr_str));
  8276. defer (gb_string_free(dst_type_str));
  8277. if (bsrc->Union.variants.count == 0) {
  8278. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8279. } else {
  8280. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8281. }
  8282. o->mode = Addressing_Invalid;
  8283. o->expr = node;
  8284. return kind;
  8285. }
  8286. add_type_info_type(c, o->type);
  8287. add_type_info_type(c, t);
  8288. o->type = t;
  8289. o->mode = Addressing_OptionalOk;
  8290. } else if (is_type_any(src)) {
  8291. o->type = t;
  8292. o->mode = Addressing_OptionalOk;
  8293. add_type_info_type(c, o->type);
  8294. add_type_info_type(c, t);
  8295. } else {
  8296. gbString str = type_to_string(o->type);
  8297. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8298. gb_string_free(str);
  8299. o->mode = Addressing_Invalid;
  8300. o->expr = node;
  8301. return kind;
  8302. }
  8303. }
  8304. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8305. add_package_dependency(c, "runtime", "type_assertion_check");
  8306. add_package_dependency(c, "runtime", "type_assertion_check2");
  8307. }
  8308. return kind;
  8309. }
  8310. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8311. ast_node(se, SelectorCallExpr, node);
  8312. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8313. // COM APIs is a great example of where this kind of thing is extremely useful
  8314. // General idea:
  8315. //
  8316. // x->y(123) == x.y(x, 123)
  8317. //
  8318. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8319. // Just regenerating a new AST aids things
  8320. //
  8321. // TODO(bill): Is this a good hack or not?
  8322. //
  8323. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8324. if (se->modified_call) {
  8325. // Prevent double evaluation
  8326. o->expr = node;
  8327. o->type = node->tav.type;
  8328. o->value = node->tav.value;
  8329. o->mode = node->tav.mode;
  8330. return Expr_Expr;
  8331. }
  8332. bool allow_arrow_right_selector_expr;
  8333. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8334. c->allow_arrow_right_selector_expr = true;
  8335. Operand x = {};
  8336. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8337. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8338. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8339. o->mode = Addressing_Invalid;
  8340. o->type = t_invalid;
  8341. o->expr = node;
  8342. return kind;
  8343. }
  8344. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8345. gbString type_str = type_to_string(x.type);
  8346. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8347. gb_string_free(type_str);
  8348. o->mode = Addressing_Invalid;
  8349. o->type = t_invalid;
  8350. o->expr = node;
  8351. return Expr_Stmt;
  8352. }
  8353. ast_node(ce, CallExpr, se->call);
  8354. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8355. Ast *first_arg = x.expr->SelectorExpr.expr;
  8356. GB_ASSERT(first_arg != nullptr);
  8357. Entity *e = entity_of_node(se->expr);
  8358. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8359. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8360. }
  8361. if (e->kind != Entity_ProcGroup) {
  8362. Type *pt = base_type(x.type);
  8363. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8364. Type *first_type = nullptr;
  8365. String first_arg_name = {};
  8366. if (pt->Proc.param_count > 0) {
  8367. Entity *f = pt->Proc.params->Tuple.variables[0];
  8368. first_type = f->type;
  8369. first_arg_name = f->token.string;
  8370. }
  8371. if (first_arg_name.len == 0) {
  8372. first_arg_name = str_lit("_");
  8373. }
  8374. if (first_type == nullptr) {
  8375. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8376. o->mode = Addressing_Invalid;
  8377. o->type = t_invalid;
  8378. o->expr = node;
  8379. return Expr_Stmt;
  8380. }
  8381. Operand y = {};
  8382. y.mode = first_arg->tav.mode;
  8383. y.type = first_arg->tav.type;
  8384. y.value = first_arg->tav.value;
  8385. if (check_is_assignable_to(c, &y, first_type)) {
  8386. // Do nothing, it's valid
  8387. } else {
  8388. Operand z = y;
  8389. z.type = type_deref(y.type);
  8390. if (check_is_assignable_to(c, &z, first_type)) {
  8391. // NOTE(bill): AST GENERATION HACK!
  8392. Token op = {Token_Pointer};
  8393. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8394. } else if (y.mode == Addressing_Variable) {
  8395. Operand w = y;
  8396. w.type = alloc_type_pointer(y.type);
  8397. if (check_is_assignable_to(c, &w, first_type)) {
  8398. // NOTE(bill): AST GENERATION HACK!
  8399. Token op = {Token_And};
  8400. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8401. }
  8402. }
  8403. }
  8404. if (ce->args.count > 0) {
  8405. bool fail = false;
  8406. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8407. for (Ast *arg : ce->args) {
  8408. bool mix = false;
  8409. if (first_is_field_value) {
  8410. mix = arg->kind != Ast_FieldValue;
  8411. } else {
  8412. mix = arg->kind == Ast_FieldValue;
  8413. }
  8414. if (mix) {
  8415. fail = true;
  8416. break;
  8417. }
  8418. }
  8419. if (!fail && first_is_field_value) {
  8420. Token op = {Token_Eq};
  8421. AstFile *f = first_arg->file();
  8422. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8423. }
  8424. }
  8425. }
  8426. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8427. modified_args[0] = first_arg;
  8428. slice_copy(&modified_args, ce->args, 1);
  8429. ce->args = modified_args;
  8430. se->modified_call = true;
  8431. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8432. c->allow_arrow_right_selector_expr = true;
  8433. check_expr_base(c, o, se->call, type_hint);
  8434. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8435. o->expr = node;
  8436. return Expr_Expr;
  8437. }
  8438. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8439. ExprKind kind = Expr_Expr;
  8440. ast_node(ie, IndexExpr, node);
  8441. check_expr(c, o, ie->expr);
  8442. node->viral_state_flags |= ie->expr->viral_state_flags;
  8443. if (o->mode == Addressing_Invalid) {
  8444. o->expr = node;
  8445. return kind;
  8446. }
  8447. Type *t = base_type(type_deref(o->type));
  8448. bool is_ptr = is_type_pointer(o->type);
  8449. bool is_const = o->mode == Addressing_Constant;
  8450. if (is_type_map(t)) {
  8451. Operand key = {};
  8452. if (is_type_typeid(t->Map.key)) {
  8453. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8454. } else {
  8455. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8456. }
  8457. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8458. if (key.mode == Addressing_Invalid) {
  8459. o->mode = Addressing_Invalid;
  8460. o->expr = node;
  8461. return kind;
  8462. }
  8463. o->mode = Addressing_MapIndex;
  8464. o->type = t->Map.value;
  8465. o->expr = node;
  8466. add_map_get_dependencies(c);
  8467. add_map_set_dependencies(c);
  8468. return Expr_Expr;
  8469. }
  8470. i64 max_count = -1;
  8471. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8472. if (is_const) {
  8473. if (is_type_array(t)) {
  8474. // Okay
  8475. } else if (is_type_slice(t)) {
  8476. // Okay
  8477. } else if (is_type_enumerated_array(t)) {
  8478. // Okay
  8479. } else if (is_type_string(t)) {
  8480. // Okay
  8481. } else if (is_type_relative_multi_pointer(t)) {
  8482. // Okay
  8483. } else if (is_type_matrix(t)) {
  8484. // Okay
  8485. } else {
  8486. valid = false;
  8487. }
  8488. }
  8489. if (!valid) {
  8490. gbString str = expr_to_string(o->expr);
  8491. gbString type_str = type_to_string(o->type);
  8492. defer (gb_string_free(str));
  8493. defer (gb_string_free(type_str));
  8494. if (is_const) {
  8495. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8496. } else {
  8497. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8498. }
  8499. o->mode = Addressing_Invalid;
  8500. o->expr = node;
  8501. return kind;
  8502. }
  8503. if (ie->index == nullptr) {
  8504. gbString str = expr_to_string(o->expr);
  8505. error(o->expr, "Missing index for '%s'", str);
  8506. gb_string_free(str);
  8507. o->mode = Addressing_Invalid;
  8508. o->expr = node;
  8509. return kind;
  8510. }
  8511. Type *index_type_hint = nullptr;
  8512. if (is_type_enumerated_array(t)) {
  8513. Type *bt = base_type(t);
  8514. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8515. index_type_hint = bt->EnumeratedArray.index;
  8516. }
  8517. i64 index = 0;
  8518. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8519. if (is_const) {
  8520. if (index < 0) {
  8521. gbString str = expr_to_string(o->expr);
  8522. error(o->expr, "Cannot index a constant '%s'", str);
  8523. if (!build_context.terse_errors) {
  8524. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8525. }
  8526. gb_string_free(str);
  8527. o->mode = Addressing_Invalid;
  8528. o->expr = node;
  8529. return kind;
  8530. } else if (ok) {
  8531. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8532. o->mode = Addressing_Constant;
  8533. bool success = false;
  8534. bool finish = false;
  8535. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8536. if (!success) {
  8537. gbString str = expr_to_string(o->expr);
  8538. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8539. if (!build_context.terse_errors) {
  8540. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8541. }
  8542. gb_string_free(str);
  8543. o->mode = Addressing_Invalid;
  8544. o->expr = node;
  8545. return kind;
  8546. }
  8547. }
  8548. }
  8549. if (type_hint != nullptr && is_type_matrix(t)) {
  8550. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8551. // if a type hint exists
  8552. }
  8553. return kind;
  8554. }
  8555. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8556. ExprKind kind = Expr_Stmt;
  8557. ast_node(se, SliceExpr, node);
  8558. check_expr(c, o, se->expr);
  8559. node->viral_state_flags |= se->expr->viral_state_flags;
  8560. if (o->mode == Addressing_Invalid) {
  8561. o->mode = Addressing_Invalid;
  8562. o->expr = node;
  8563. return kind;
  8564. }
  8565. bool valid = false;
  8566. i64 max_count = -1;
  8567. Type *t = base_type(type_deref(o->type));
  8568. switch (t->kind) {
  8569. case Type_Basic:
  8570. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8571. valid = true;
  8572. if (o->mode == Addressing_Constant) {
  8573. max_count = o->value.value_string.len;
  8574. }
  8575. o->type = type_deref(o->type);
  8576. }
  8577. break;
  8578. case Type_Array:
  8579. valid = true;
  8580. max_count = t->Array.count;
  8581. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8582. gbString str = expr_to_string(node);
  8583. error(node, "Cannot slice array '%s', value is not addressable", str);
  8584. gb_string_free(str);
  8585. o->mode = Addressing_Invalid;
  8586. o->expr = node;
  8587. return kind;
  8588. }
  8589. o->type = alloc_type_slice(t->Array.elem);
  8590. break;
  8591. case Type_MultiPointer:
  8592. valid = true;
  8593. o->type = type_deref(o->type);
  8594. break;
  8595. case Type_Slice:
  8596. valid = true;
  8597. o->type = type_deref(o->type);
  8598. break;
  8599. case Type_DynamicArray:
  8600. valid = true;
  8601. o->type = alloc_type_slice(t->DynamicArray.elem);
  8602. break;
  8603. case Type_Struct:
  8604. if (is_type_soa_struct(t)) {
  8605. valid = true;
  8606. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8607. }
  8608. break;
  8609. case Type_RelativeMultiPointer:
  8610. valid = true;
  8611. o->type = type_deref(o->type);
  8612. break;
  8613. case Type_EnumeratedArray:
  8614. {
  8615. gbString str = expr_to_string(o->expr);
  8616. gbString type_str = type_to_string(o->type);
  8617. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8618. gb_string_free(type_str);
  8619. gb_string_free(str);
  8620. o->mode = Addressing_Invalid;
  8621. o->expr = node;
  8622. return kind;
  8623. }
  8624. break;
  8625. }
  8626. if (!valid) {
  8627. gbString str = expr_to_string(o->expr);
  8628. gbString type_str = type_to_string(o->type);
  8629. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8630. gb_string_free(type_str);
  8631. gb_string_free(str);
  8632. o->mode = Addressing_Invalid;
  8633. o->expr = node;
  8634. return kind;
  8635. }
  8636. if (se->low == nullptr && se->high != nullptr) {
  8637. // It is okay to continue as it will assume the 1st index is zero
  8638. }
  8639. i64 indices[2] = {};
  8640. Ast *nodes[2] = {se->low, se->high};
  8641. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8642. i64 index = max_count;
  8643. if (nodes[i] != nullptr) {
  8644. i64 capacity = -1;
  8645. if (max_count >= 0) {
  8646. capacity = max_count;
  8647. }
  8648. i64 j = 0;
  8649. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8650. index = j;
  8651. }
  8652. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8653. } else if (i == 0) {
  8654. index = 0;
  8655. }
  8656. indices[i] = index;
  8657. }
  8658. for (isize i = 0; i < gb_count_of(indices); i++) {
  8659. i64 a = indices[i];
  8660. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8661. i64 b = indices[j];
  8662. if (a > b && b >= 0) {
  8663. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8664. }
  8665. }
  8666. }
  8667. if (max_count < 0) {
  8668. if (o->mode == Addressing_Constant) {
  8669. gbString s = expr_to_string(se->expr);
  8670. error(se->expr, "Cannot slice constant value '%s'", s);
  8671. gb_string_free(s);
  8672. }
  8673. }
  8674. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8675. /*
  8676. x[:] -> [^]T
  8677. x[i:] -> [^]T
  8678. x[:n] -> []T
  8679. x[i:n] -> []T
  8680. */
  8681. o->type = alloc_type_slice(t->MultiPointer.elem);
  8682. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  8683. /*
  8684. x[:] -> [^]T
  8685. x[i:] -> [^]T
  8686. x[:n] -> []T
  8687. x[i:n] -> []T
  8688. */
  8689. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  8690. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  8691. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  8692. }
  8693. o->mode = Addressing_Value;
  8694. if (is_type_string(t) && max_count >= 0) {
  8695. bool all_constant = true;
  8696. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8697. if (nodes[i] != nullptr) {
  8698. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8699. if (tav.mode != Addressing_Constant) {
  8700. all_constant = false;
  8701. break;
  8702. }
  8703. }
  8704. }
  8705. if (!all_constant) {
  8706. gbString str = expr_to_string(o->expr);
  8707. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8708. if (!build_context.terse_errors) {
  8709. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8710. }
  8711. gb_string_free(str);
  8712. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8713. o->expr = node;
  8714. return kind;
  8715. }
  8716. String s = {};
  8717. if (o->value.kind == ExactValue_String) {
  8718. s = o->value.value_string;
  8719. }
  8720. o->mode = Addressing_Constant;
  8721. o->type = t;
  8722. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8723. }
  8724. return kind;
  8725. }
  8726. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8727. u32 prev_state_flags = c->state_flags;
  8728. defer (c->state_flags = prev_state_flags);
  8729. if (node->state_flags != 0) {
  8730. u32 in = node->state_flags;
  8731. u32 out = c->state_flags;
  8732. if (in & StateFlag_no_bounds_check) {
  8733. out |= StateFlag_no_bounds_check;
  8734. out &= ~StateFlag_bounds_check;
  8735. } else if (in & StateFlag_bounds_check) {
  8736. out |= StateFlag_bounds_check;
  8737. out &= ~StateFlag_no_bounds_check;
  8738. }
  8739. if (in & StateFlag_no_type_assert) {
  8740. out |= StateFlag_no_type_assert;
  8741. out &= ~StateFlag_type_assert;
  8742. } else if (in & StateFlag_type_assert) {
  8743. out |= StateFlag_type_assert;
  8744. out &= ~StateFlag_no_type_assert;
  8745. }
  8746. c->state_flags = out;
  8747. }
  8748. ExprKind kind = Expr_Stmt;
  8749. o->mode = Addressing_Invalid;
  8750. o->type = t_invalid;
  8751. o->value = {ExactValue_Invalid};
  8752. switch (node->kind) {
  8753. default:
  8754. return kind;
  8755. case_ast_node(be, BadExpr, node)
  8756. return kind;
  8757. case_end;
  8758. case_ast_node(i, Implicit, node)
  8759. switch (i->kind) {
  8760. case Token_context:
  8761. {
  8762. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8763. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8764. return kind;
  8765. }
  8766. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8767. c->scope->flags |= ScopeFlag_ContextDefined;
  8768. }
  8769. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8770. error(node, "'context' has not been defined within this scope");
  8771. // Continue with value
  8772. }
  8773. init_core_context(c->checker);
  8774. o->mode = Addressing_Context;
  8775. o->type = t_context;
  8776. }
  8777. break;
  8778. default:
  8779. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8780. return kind;
  8781. }
  8782. case_end;
  8783. case_ast_node(i, Ident, node);
  8784. check_ident(c, o, node, nullptr, type_hint, false);
  8785. case_end;
  8786. case_ast_node(u, Uninit, node);
  8787. o->mode = Addressing_Value;
  8788. o->type = t_untyped_uninit;
  8789. error(node, "Use of --- outside of variable declaration");
  8790. case_end;
  8791. case_ast_node(bl, BasicLit, node);
  8792. Type *t = t_invalid;
  8793. switch (node->tav.value.kind) {
  8794. case ExactValue_String: t = t_untyped_string; break;
  8795. case ExactValue_Float: t = t_untyped_float; break;
  8796. case ExactValue_Complex: t = t_untyped_complex; break;
  8797. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  8798. case ExactValue_Integer:
  8799. t = t_untyped_integer;
  8800. if (bl->token.kind == Token_Rune) {
  8801. t = t_untyped_rune;
  8802. }
  8803. break;
  8804. default:
  8805. GB_PANIC("Unhandled value type for basic literal");
  8806. break;
  8807. }
  8808. o->mode = Addressing_Constant;
  8809. o->type = t;
  8810. o->value = node->tav.value;
  8811. case_end;
  8812. case_ast_node(bd, BasicDirective, node);
  8813. kind = check_basic_directive_expr(c, o, node, type_hint);
  8814. case_end;
  8815. case_ast_node(pg, ProcGroup, node);
  8816. error(node, "Illegal use of a procedure group");
  8817. o->mode = Addressing_Invalid;
  8818. case_end;
  8819. case_ast_node(pl, ProcLit, node);
  8820. CheckerContext ctx = *c;
  8821. DeclInfo *decl = nullptr;
  8822. Type *type = alloc_type(Type_Proc);
  8823. check_open_scope(&ctx, pl->type);
  8824. {
  8825. decl = make_decl_info(ctx.scope, ctx.decl);
  8826. decl->proc_lit = node;
  8827. ctx.decl = decl;
  8828. defer (ctx.decl = ctx.decl->parent);
  8829. if (pl->tags != 0) {
  8830. error(node, "A procedure literal cannot have tags");
  8831. pl->tags = 0; // TODO(bill): Should I zero this?!
  8832. }
  8833. check_procedure_type(&ctx, type, pl->type);
  8834. if (!is_type_proc(type)) {
  8835. gbString str = expr_to_string(node);
  8836. error(node, "Invalid procedure literal '%s'", str);
  8837. gb_string_free(str);
  8838. check_close_scope(&ctx);
  8839. return kind;
  8840. }
  8841. if (pl->body == nullptr) {
  8842. error(node, "A procedure literal must have a body");
  8843. return kind;
  8844. }
  8845. pl->decl = decl;
  8846. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  8847. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  8848. array_add(&ctx.checker->nested_proc_lits, decl);
  8849. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  8850. }
  8851. check_close_scope(&ctx);
  8852. o->mode = Addressing_Value;
  8853. o->type = type;
  8854. case_end;
  8855. case_ast_node(te, TernaryIfExpr, node);
  8856. kind = check_ternary_if_expr(c, o, node, type_hint);
  8857. case_end;
  8858. case_ast_node(te, TernaryWhenExpr, node);
  8859. kind = check_ternary_when_expr(c, o, node, type_hint);
  8860. case_end;
  8861. case_ast_node(oe, OrElseExpr, node);
  8862. return check_or_else_expr(c, o, node, type_hint);
  8863. case_end;
  8864. case_ast_node(re, OrReturnExpr, node);
  8865. return check_or_return_expr(c, o, node, type_hint);
  8866. case_end;
  8867. case_ast_node(re, OrBranchExpr, node);
  8868. return check_or_branch_expr(c, o, node, type_hint);
  8869. case_end;
  8870. case_ast_node(cl, CompoundLit, node);
  8871. kind = check_compound_literal(c, o, node, type_hint);
  8872. case_end;
  8873. case_ast_node(pe, ParenExpr, node);
  8874. kind = check_expr_base(c, o, pe->expr, type_hint);
  8875. node->viral_state_flags |= pe->expr->viral_state_flags;
  8876. o->expr = node;
  8877. case_end;
  8878. case_ast_node(te, TagExpr, node);
  8879. String name = te->name.string;
  8880. error(node, "Unknown tag expression, #%.*s", LIT(name));
  8881. if (te->expr) {
  8882. kind = check_expr_base(c, o, te->expr, type_hint);
  8883. node->viral_state_flags |= te->expr->viral_state_flags;
  8884. }
  8885. o->expr = node;
  8886. case_end;
  8887. case_ast_node(ta, TypeAssertion, node);
  8888. kind = check_type_assertion(c, o, node, type_hint);
  8889. case_end;
  8890. case_ast_node(tc, TypeCast, node);
  8891. check_expr_or_type(c, o, tc->type);
  8892. if (o->mode != Addressing_Type) {
  8893. gbString str = expr_to_string(tc->type);
  8894. error(tc->type, "Expected a type, got %s", str);
  8895. gb_string_free(str);
  8896. o->mode = Addressing_Invalid;
  8897. }
  8898. if (o->mode == Addressing_Invalid) {
  8899. o->expr = node;
  8900. return kind;
  8901. }
  8902. Type *type = o->type;
  8903. check_expr_base(c, o, tc->expr, type);
  8904. node->viral_state_flags |= tc->expr->viral_state_flags;
  8905. if (o->mode != Addressing_Invalid) {
  8906. switch (tc->token.kind) {
  8907. case Token_transmute:
  8908. check_transmute(c, node, o, type);
  8909. break;
  8910. case Token_cast:
  8911. check_cast(c, o, type);
  8912. break;
  8913. default:
  8914. error(node, "Invalid AST: Invalid casting expression");
  8915. o->mode = Addressing_Invalid;
  8916. break;
  8917. }
  8918. }
  8919. return Expr_Expr;
  8920. case_end;
  8921. case_ast_node(ac, AutoCast, node);
  8922. check_expr_base(c, o, ac->expr, type_hint);
  8923. node->viral_state_flags |= ac->expr->viral_state_flags;
  8924. if (o->mode == Addressing_Invalid) {
  8925. o->expr = node;
  8926. return kind;
  8927. }
  8928. if (type_hint) {
  8929. check_cast(c, o, type_hint);
  8930. }
  8931. o->expr = node;
  8932. return Expr_Expr;
  8933. case_end;
  8934. case_ast_node(ue, UnaryExpr, node);
  8935. Type *th = type_hint;
  8936. if (ue->op.kind == Token_And) {
  8937. th = type_deref(th);
  8938. }
  8939. check_expr_base(c, o, ue->expr, th);
  8940. node->viral_state_flags |= ue->expr->viral_state_flags;
  8941. if (o->mode != Addressing_Invalid) {
  8942. check_unary_expr(c, o, ue->op, node);
  8943. }
  8944. o->expr = node;
  8945. return Expr_Expr;
  8946. case_end;
  8947. case_ast_node(be, BinaryExpr, node);
  8948. check_binary_expr(c, o, node, type_hint, true);
  8949. if (o->mode == Addressing_Invalid) {
  8950. o->expr = node;
  8951. return kind;
  8952. }
  8953. case_end;
  8954. case_ast_node(se, SelectorExpr, node);
  8955. check_selector(c, o, node, type_hint);
  8956. node->viral_state_flags |= se->expr->viral_state_flags;
  8957. case_end;
  8958. case_ast_node(se, SelectorCallExpr, node);
  8959. return check_selector_call_expr(c, o, node, type_hint);
  8960. case_end;
  8961. case_ast_node(ise, ImplicitSelectorExpr, node);
  8962. return check_implicit_selector_expr(c, o, node, type_hint);
  8963. case_end;
  8964. case_ast_node(ie, IndexExpr, node);
  8965. kind = check_index_expr(c, o, node, type_hint);
  8966. case_end;
  8967. case_ast_node(se, SliceExpr, node);
  8968. kind = check_slice_expr(c, o, node, type_hint);
  8969. case_end;
  8970. case_ast_node(mie, MatrixIndexExpr, node);
  8971. check_matrix_index_expr(c, o, node, type_hint);
  8972. o->expr = node;
  8973. return Expr_Expr;
  8974. case_end;
  8975. case_ast_node(ce, CallExpr, node);
  8976. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  8977. case_end;
  8978. case_ast_node(de, DerefExpr, node);
  8979. check_expr_or_type(c, o, de->expr);
  8980. node->viral_state_flags |= de->expr->viral_state_flags;
  8981. if (o->mode == Addressing_Invalid) {
  8982. o->mode = Addressing_Invalid;
  8983. o->expr = node;
  8984. return kind;
  8985. } else {
  8986. Type *t = base_type(o->type);
  8987. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  8988. o->mode = Addressing_Variable;
  8989. o->type = t->Pointer.elem;
  8990. } else if (t->kind == Type_SoaPointer) {
  8991. o->mode = Addressing_SoaVariable;
  8992. o->type = type_deref(t);
  8993. } else if (t->kind == Type_RelativePointer) {
  8994. if (o->mode != Addressing_Variable) {
  8995. gbString str = expr_to_string(o->expr);
  8996. gbString typ = type_to_string(o->type);
  8997. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  8998. gb_string_free(typ);
  8999. gb_string_free(str);
  9000. }
  9001. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9002. add_type_info_type(c, o->type);
  9003. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9004. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9005. o->mode = Addressing_Variable;
  9006. o->type = ptr_type->Pointer.elem;
  9007. } else {
  9008. gbString str = expr_to_string(o->expr);
  9009. gbString typ = type_to_string(o->type);
  9010. ERROR_BLOCK();
  9011. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9012. if (o->type && is_type_multi_pointer(o->type)) {
  9013. if (!build_context.terse_errors) {
  9014. error_line("\tDid you mean '%s[0]'?\n", str);
  9015. }
  9016. }
  9017. gb_string_free(typ);
  9018. gb_string_free(str);
  9019. o->mode = Addressing_Invalid;
  9020. o->expr = node;
  9021. return kind;
  9022. }
  9023. }
  9024. case_end;
  9025. case_ast_node(ia, InlineAsmExpr, node);
  9026. if (c->curr_proc_decl == nullptr) {
  9027. error(node, "Inline asm expressions are only allowed within a procedure body");
  9028. }
  9029. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9030. Type *return_type = nullptr;
  9031. for_array(i, ia->param_types) {
  9032. param_types[i] = check_type(c, ia->param_types[i]);
  9033. }
  9034. if (ia->return_type != nullptr) {
  9035. return_type = check_type(c, ia->return_type);
  9036. }
  9037. Operand x = {};
  9038. check_expr(c, &x, ia->asm_string);
  9039. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9040. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9041. }
  9042. check_expr(c, &x, ia->constraints_string);
  9043. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9044. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9045. }
  9046. Scope *scope = create_scope(c->info, c->scope);
  9047. scope->flags |= ScopeFlag_Proc;
  9048. Type *params = alloc_type_tuple();
  9049. Type *results = alloc_type_tuple();
  9050. if (param_types.count != 0) {
  9051. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9052. for_array(i, param_types) {
  9053. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9054. }
  9055. }
  9056. if (return_type != nullptr) {
  9057. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9058. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9059. }
  9060. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9061. o->type = pt;
  9062. o->mode = Addressing_Value;
  9063. o->expr = node;
  9064. return Expr_Expr;
  9065. case_end;
  9066. case Ast_TypeidType:
  9067. case Ast_PolyType:
  9068. case Ast_ProcType:
  9069. case Ast_PointerType:
  9070. case Ast_MultiPointerType:
  9071. case Ast_ArrayType:
  9072. case Ast_DynamicArrayType:
  9073. case Ast_StructType:
  9074. case Ast_UnionType:
  9075. case Ast_EnumType:
  9076. case Ast_MapType:
  9077. case Ast_BitSetType:
  9078. case Ast_MatrixType:
  9079. case Ast_RelativeType:
  9080. o->mode = Addressing_Type;
  9081. o->type = check_type(c, node);
  9082. break;
  9083. }
  9084. kind = Expr_Expr;
  9085. o->expr = node;
  9086. return kind;
  9087. }
  9088. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9089. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9090. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9091. o->type = t_invalid;
  9092. gbString xs = expr_to_string(o->expr);
  9093. if (o->mode == Addressing_Type) {
  9094. error(o->expr, "Invalid type usage '%s'", xs);
  9095. } else {
  9096. error(o->expr, "Invalid expression '%s'", xs);
  9097. }
  9098. gb_string_free(xs);
  9099. }
  9100. if (o->type != nullptr && is_type_untyped(o->type)) {
  9101. add_untyped(c, node, o->mode, o->type, o->value);
  9102. }
  9103. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9104. add_type_and_value(c, node, o->mode, o->type, o->value);
  9105. return kind;
  9106. }
  9107. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9108. check_expr_base(c, o, e, nullptr);
  9109. switch (o->mode) {
  9110. default:
  9111. return; // NOTE(bill): Valid
  9112. case Addressing_NoValue:
  9113. error_operand_no_value(o);
  9114. break;
  9115. }
  9116. o->mode = Addressing_Invalid;
  9117. }
  9118. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9119. check_expr_base(c, o, e, nullptr);
  9120. switch (o->mode) {
  9121. default:
  9122. return; // NOTE(bill): Valid
  9123. case Addressing_NoValue:
  9124. error_operand_no_value(o);
  9125. break;
  9126. case Addressing_Type:
  9127. error_operand_not_expression(o);
  9128. break;
  9129. }
  9130. o->mode = Addressing_Invalid;
  9131. }
  9132. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9133. check_expr_base(c, o, e, type_hint);
  9134. switch (o->mode) {
  9135. default:
  9136. return; // NOTE(bill): Valid
  9137. case Addressing_NoValue:
  9138. error_operand_no_value(o);
  9139. break;
  9140. case Addressing_Type:
  9141. error_operand_not_expression(o);
  9142. break;
  9143. }
  9144. o->mode = Addressing_Invalid;
  9145. }
  9146. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9147. if (o->mode == Addressing_Value) {
  9148. // NOTE(bill): Tuples are not first class thus never named
  9149. if (o->type->kind == Type_Tuple) {
  9150. isize count = o->type->Tuple.variables.count;
  9151. error(o->expr,
  9152. "%td-valued expression found where single value expected", count);
  9153. o->mode = Addressing_Invalid;
  9154. GB_ASSERT(count != 1);
  9155. }
  9156. }
  9157. }
  9158. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9159. check_multi_expr(c, o, e);
  9160. check_not_tuple(c, o);
  9161. }
  9162. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9163. check_expr_base(c, o, e, type_hint);
  9164. check_not_tuple(c, o);
  9165. error_operand_no_value(o);
  9166. }
  9167. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9168. switch (v.kind) {
  9169. case ExactValue_Invalid:
  9170. return true;
  9171. case ExactValue_Bool:
  9172. return !v.value_bool;
  9173. case ExactValue_String:
  9174. return v.value_string.len == 0;
  9175. case ExactValue_Integer:
  9176. return big_int_is_zero(&v.value_integer);
  9177. case ExactValue_Float:
  9178. return v.value_float == 0.0;
  9179. case ExactValue_Complex:
  9180. if (v.value_complex) {
  9181. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9182. }
  9183. return true;
  9184. case ExactValue_Quaternion:
  9185. if (v.value_quaternion) {
  9186. return v.value_quaternion->real == 0.0 &&
  9187. v.value_quaternion->imag == 0.0 &&
  9188. v.value_quaternion->jmag == 0.0 &&
  9189. v.value_quaternion->kmag == 0.0;
  9190. }
  9191. return true;
  9192. case ExactValue_Pointer:
  9193. return v.value_pointer == 0;
  9194. case ExactValue_Compound:
  9195. if (v.value_compound == nullptr) {
  9196. return true;
  9197. } else {
  9198. ast_node(cl, CompoundLit, v.value_compound);
  9199. if (cl->elems.count == 0) {
  9200. return true;
  9201. } else {
  9202. for (Ast *elem : cl->elems) {
  9203. if (elem->tav.mode != Addressing_Constant) {
  9204. return false;
  9205. }
  9206. if (!is_exact_value_zero(elem->tav.value)) {
  9207. return false;
  9208. }
  9209. }
  9210. return true;
  9211. }
  9212. }
  9213. case ExactValue_Procedure:
  9214. return v.value_procedure == nullptr;
  9215. case ExactValue_Typeid:
  9216. return v.value_typeid == nullptr;
  9217. }
  9218. return true;
  9219. }
  9220. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9221. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9222. for_array(i, params) {
  9223. if (i > 0) {
  9224. str = gb_string_appendc(str, ", ");
  9225. }
  9226. str = write_expr_to_string(str, params[i], false);
  9227. }
  9228. return str;
  9229. }
  9230. gb_internal gbString string_append_string(gbString str, String string) {
  9231. if (string.len > 0) {
  9232. return gb_string_append_length(str, &string[0], string.len);
  9233. }
  9234. return str;
  9235. }
  9236. gb_internal gbString string_append_token(gbString str, Token token) {
  9237. str = string_append_string(str, token.string);
  9238. return str;
  9239. }
  9240. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9241. if (node == nullptr)
  9242. return str;
  9243. if (is_ast_stmt(node)) {
  9244. GB_ASSERT("stmt passed to write_expr_to_string");
  9245. }
  9246. switch (node->kind) {
  9247. default:
  9248. str = gb_string_appendc(str, "(BadExpr)");
  9249. break;
  9250. case_ast_node(i, Ident, node);
  9251. str = string_append_token(str, i->token);
  9252. case_end;
  9253. case_ast_node(i, Implicit, node);
  9254. str = string_append_token(str, *i);
  9255. case_end;
  9256. case_ast_node(bl, BasicLit, node);
  9257. str = string_append_token(str, bl->token);
  9258. case_end;
  9259. case_ast_node(bd, BasicDirective, node);
  9260. str = gb_string_append_rune(str, '#');
  9261. str = string_append_string(str, bd->name.string);
  9262. case_end;
  9263. case_ast_node(ud, Uninit, node);
  9264. str = gb_string_appendc(str, "---");
  9265. case_end;
  9266. case_ast_node(pg, ProcGroup, node);
  9267. str = gb_string_appendc(str, "proc{");
  9268. for_array(i, pg->args) {
  9269. if (i > 0) str = gb_string_appendc(str, ", ");
  9270. str = write_expr_to_string(str, pg->args[i], shorthand);
  9271. }
  9272. str = gb_string_append_rune(str, '}');
  9273. case_end;
  9274. case_ast_node(pl, ProcLit, node);
  9275. str = write_expr_to_string(str, pl->type, shorthand);
  9276. if (pl->body) {
  9277. str = gb_string_appendc(str, " {...}");
  9278. } else {
  9279. str = gb_string_appendc(str, " ---");
  9280. }
  9281. case_end;
  9282. case_ast_node(cl, CompoundLit, node);
  9283. str = write_expr_to_string(str, cl->type, shorthand);
  9284. str = gb_string_append_rune(str, '{');
  9285. if (shorthand) {
  9286. str = gb_string_appendc(str, "...");
  9287. } else {
  9288. for_array(i, cl->elems) {
  9289. if (i > 0) str = gb_string_appendc(str, ", ");
  9290. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9291. }
  9292. }
  9293. str = gb_string_append_rune(str, '}');
  9294. case_end;
  9295. case_ast_node(te, TagExpr, node);
  9296. str = gb_string_append_rune(str, '#');
  9297. str = string_append_token(str, te->name);
  9298. str = write_expr_to_string(str, te->expr, shorthand);
  9299. case_end;
  9300. case_ast_node(ue, UnaryExpr, node);
  9301. str = string_append_token(str, ue->op);
  9302. str = write_expr_to_string(str, ue->expr, shorthand);
  9303. case_end;
  9304. case_ast_node(de, DerefExpr, node);
  9305. str = write_expr_to_string(str, de->expr, shorthand);
  9306. str = gb_string_append_rune(str, '^');
  9307. case_end;
  9308. case_ast_node(be, BinaryExpr, node);
  9309. str = write_expr_to_string(str, be->left, shorthand);
  9310. str = gb_string_append_rune(str, ' ');
  9311. str = string_append_token(str, be->op);
  9312. str = gb_string_append_rune(str, ' ');
  9313. str = write_expr_to_string(str, be->right, shorthand);
  9314. case_end;
  9315. case_ast_node(te, TernaryIfExpr, node);
  9316. TokenPos x = ast_token(te->x).pos;
  9317. TokenPos cond = ast_token(te->cond).pos;
  9318. if (x < cond) {
  9319. str = write_expr_to_string(str, te->x, shorthand);
  9320. str = gb_string_appendc(str, " if ");
  9321. str = write_expr_to_string(str, te->cond, shorthand);
  9322. str = gb_string_appendc(str, " else ");
  9323. str = write_expr_to_string(str, te->y, shorthand);
  9324. } else {
  9325. str = write_expr_to_string(str, te->cond, shorthand);
  9326. str = gb_string_appendc(str, " ? ");
  9327. str = write_expr_to_string(str, te->x, shorthand);
  9328. str = gb_string_appendc(str, " : ");
  9329. str = write_expr_to_string(str, te->y, shorthand);
  9330. }
  9331. case_end;
  9332. case_ast_node(te, TernaryWhenExpr, node);
  9333. str = write_expr_to_string(str, te->x, shorthand);
  9334. str = gb_string_appendc(str, " when ");
  9335. str = write_expr_to_string(str, te->cond, shorthand);
  9336. str = gb_string_appendc(str, " else ");
  9337. str = write_expr_to_string(str, te->y, shorthand);
  9338. case_end;
  9339. case_ast_node(oe, OrElseExpr, node);
  9340. str = write_expr_to_string(str, oe->x, shorthand);
  9341. str = gb_string_appendc(str, " or_else ");
  9342. str = write_expr_to_string(str, oe->y, shorthand);
  9343. case_end;
  9344. case_ast_node(oe, OrReturnExpr, node);
  9345. str = write_expr_to_string(str, oe->expr, shorthand);
  9346. str = gb_string_appendc(str, " or_return");
  9347. case_end;
  9348. case_ast_node(oe, OrBranchExpr, node);
  9349. str = write_expr_to_string(str, oe->expr, shorthand);
  9350. str = gb_string_append_rune(str, ' ');
  9351. str = string_append_token(str, oe->token);
  9352. if (oe->label) {
  9353. str = gb_string_append_rune(str, ' ');
  9354. str = write_expr_to_string(str, oe->label, shorthand);
  9355. }
  9356. case_end;
  9357. case_ast_node(pe, ParenExpr, node);
  9358. str = gb_string_append_rune(str, '(');
  9359. str = write_expr_to_string(str, pe->expr, shorthand);
  9360. str = gb_string_append_rune(str, ')');
  9361. case_end;
  9362. case_ast_node(se, SelectorExpr, node);
  9363. str = write_expr_to_string(str, se->expr, shorthand);
  9364. str = string_append_token(str, se->token);
  9365. str = write_expr_to_string(str, se->selector, shorthand);
  9366. case_end;
  9367. case_ast_node(se, ImplicitSelectorExpr, node);
  9368. str = gb_string_append_rune(str, '.');
  9369. str = write_expr_to_string(str, se->selector, shorthand);
  9370. case_end;
  9371. case_ast_node(se, SelectorCallExpr, node);
  9372. str = write_expr_to_string(str, se->expr, shorthand);
  9373. str = gb_string_appendc(str, "(");
  9374. ast_node(ce, CallExpr, se->call);
  9375. isize start = se->modified_call ? 1 : 0;
  9376. for (isize i = start; i < ce->args.count; i++) {
  9377. Ast *arg = ce->args[i];
  9378. if (i > start) {
  9379. str = gb_string_appendc(str, ", ");
  9380. }
  9381. str = write_expr_to_string(str, arg, shorthand);
  9382. }
  9383. str = gb_string_appendc(str, ")");
  9384. case_end;
  9385. case_ast_node(ta, TypeAssertion, node);
  9386. str = write_expr_to_string(str, ta->expr, shorthand);
  9387. if (ta->type != nullptr &&
  9388. ta->type->kind == Ast_UnaryExpr &&
  9389. ta->type->UnaryExpr.op.kind == Token_Question) {
  9390. str = gb_string_appendc(str, ".?");
  9391. } else {
  9392. str = gb_string_appendc(str, ".(");
  9393. str = write_expr_to_string(str, ta->type, shorthand);
  9394. str = gb_string_append_rune(str, ')');
  9395. }
  9396. case_end;
  9397. case_ast_node(tc, TypeCast, node);
  9398. str = string_append_token(str, tc->token);
  9399. str = gb_string_append_rune(str, '(');
  9400. str = write_expr_to_string(str, tc->type, shorthand);
  9401. str = gb_string_append_rune(str, ')');
  9402. str = write_expr_to_string(str, tc->expr, shorthand);
  9403. case_end;
  9404. case_ast_node(ac, AutoCast, node);
  9405. str = string_append_token(str, ac->token);
  9406. str = gb_string_append_rune(str, ' ');
  9407. str = write_expr_to_string(str, ac->expr, shorthand);
  9408. case_end;
  9409. case_ast_node(ie, IndexExpr, node);
  9410. str = write_expr_to_string(str, ie->expr, shorthand);
  9411. str = gb_string_append_rune(str, '[');
  9412. str = write_expr_to_string(str, ie->index, shorthand);
  9413. str = gb_string_append_rune(str, ']');
  9414. case_end;
  9415. case_ast_node(se, SliceExpr, node);
  9416. str = write_expr_to_string(str, se->expr, shorthand);
  9417. str = gb_string_append_rune(str, '[');
  9418. str = write_expr_to_string(str, se->low, shorthand);
  9419. str = string_append_token(str, se->interval);
  9420. str = write_expr_to_string(str, se->high, shorthand);
  9421. str = gb_string_append_rune(str, ']');
  9422. case_end;
  9423. case_ast_node(mie, MatrixIndexExpr, node);
  9424. str = write_expr_to_string(str, mie->expr, shorthand);
  9425. str = gb_string_append_rune(str, '[');
  9426. str = write_expr_to_string(str, mie->row_index, shorthand);
  9427. str = gb_string_appendc(str, ", ");
  9428. str = write_expr_to_string(str, mie->column_index, shorthand);
  9429. str = gb_string_append_rune(str, ']');
  9430. case_end;
  9431. case_ast_node(e, Ellipsis, node);
  9432. str = gb_string_appendc(str, "..");
  9433. str = write_expr_to_string(str, e->expr, shorthand);
  9434. case_end;
  9435. case_ast_node(fv, FieldValue, node);
  9436. str = write_expr_to_string(str, fv->field, shorthand);
  9437. str = gb_string_appendc(str, " = ");
  9438. str = write_expr_to_string(str, fv->value, shorthand);
  9439. case_end;
  9440. case_ast_node(fv, EnumFieldValue, node);
  9441. str = write_expr_to_string(str, fv->name, shorthand);
  9442. if (fv->value) {
  9443. str = gb_string_appendc(str, " = ");
  9444. str = write_expr_to_string(str, fv->value, shorthand);
  9445. }
  9446. case_end;
  9447. case_ast_node(ht, HelperType, node);
  9448. str = gb_string_appendc(str, "#type ");
  9449. str = write_expr_to_string(str, ht->type, shorthand);
  9450. case_end;
  9451. case_ast_node(ht, DistinctType, node);
  9452. str = gb_string_appendc(str, "distinct ");
  9453. str = write_expr_to_string(str, ht->type, shorthand);
  9454. case_end;
  9455. case_ast_node(pt, PolyType, node);
  9456. str = gb_string_append_rune(str, '$');
  9457. str = write_expr_to_string(str, pt->type, shorthand);
  9458. if (pt->specialization != nullptr) {
  9459. str = gb_string_append_rune(str, '/');
  9460. str = write_expr_to_string(str, pt->specialization, shorthand);
  9461. }
  9462. case_end;
  9463. case_ast_node(pt, PointerType, node);
  9464. str = gb_string_append_rune(str, '^');
  9465. str = write_expr_to_string(str, pt->type, shorthand);
  9466. case_end;
  9467. case_ast_node(pt, MultiPointerType, node);
  9468. str = gb_string_appendc(str, "[^]");
  9469. str = write_expr_to_string(str, pt->type, shorthand);
  9470. case_end;
  9471. case_ast_node(at, ArrayType, node);
  9472. str = gb_string_append_rune(str, '[');
  9473. if (at->count != nullptr &&
  9474. at->count->kind == Ast_UnaryExpr &&
  9475. at->count->UnaryExpr.op.kind == Token_Question) {
  9476. str = gb_string_appendc(str, "?");
  9477. } else {
  9478. str = write_expr_to_string(str, at->count, shorthand);
  9479. }
  9480. str = gb_string_append_rune(str, ']');
  9481. str = write_expr_to_string(str, at->elem, shorthand);
  9482. case_end;
  9483. case_ast_node(at, DynamicArrayType, node);
  9484. str = gb_string_appendc(str, "[dynamic]");
  9485. str = write_expr_to_string(str, at->elem, shorthand);
  9486. case_end;
  9487. case_ast_node(bs, BitSetType, node);
  9488. str = gb_string_appendc(str, "bit_set[");
  9489. str = write_expr_to_string(str, bs->elem, shorthand);
  9490. str = gb_string_appendc(str, "]");
  9491. case_end;
  9492. case_ast_node(mt, MapType, node);
  9493. str = gb_string_appendc(str, "map[");
  9494. str = write_expr_to_string(str, mt->key, shorthand);
  9495. str = gb_string_append_rune(str, ']');
  9496. str = write_expr_to_string(str, mt->value, shorthand);
  9497. case_end;
  9498. case_ast_node(mt, MatrixType, node);
  9499. str = gb_string_appendc(str, "matrix[");
  9500. str = write_expr_to_string(str, mt->row_count, shorthand);
  9501. str = gb_string_appendc(str, ", ");
  9502. str = write_expr_to_string(str, mt->column_count, shorthand);
  9503. str = gb_string_append_rune(str, ']');
  9504. str = write_expr_to_string(str, mt->elem, shorthand);
  9505. case_end;
  9506. case_ast_node(f, Field, node);
  9507. if (f->flags&FieldFlag_using) {
  9508. str = gb_string_appendc(str, "using ");
  9509. }
  9510. if (f->flags&FieldFlag_no_alias) {
  9511. str = gb_string_appendc(str, "#no_alias ");
  9512. }
  9513. if (f->flags&FieldFlag_c_vararg) {
  9514. str = gb_string_appendc(str, "#c_vararg ");
  9515. }
  9516. if (f->flags&FieldFlag_any_int) {
  9517. str = gb_string_appendc(str, "#any_int ");
  9518. }
  9519. if (f->flags&FieldFlag_const) {
  9520. str = gb_string_appendc(str, "#const ");
  9521. }
  9522. if (f->flags&FieldFlag_subtype) {
  9523. str = gb_string_appendc(str, "#subtype ");
  9524. }
  9525. for_array(i, f->names) {
  9526. Ast *name = f->names[i];
  9527. if (i > 0) str = gb_string_appendc(str, ", ");
  9528. str = write_expr_to_string(str, name, shorthand);
  9529. }
  9530. if (f->names.count > 0) {
  9531. if (f->type == nullptr && f->default_value != nullptr) {
  9532. str = gb_string_append_rune(str, ' ');
  9533. }
  9534. str = gb_string_appendc(str, ":");
  9535. }
  9536. if (f->type != nullptr) {
  9537. str = gb_string_append_rune(str, ' ');
  9538. str = write_expr_to_string(str, f->type, shorthand);
  9539. }
  9540. if (f->default_value != nullptr) {
  9541. if (f->type != nullptr) {
  9542. str = gb_string_append_rune(str, ' ');
  9543. }
  9544. str = gb_string_appendc(str, "= ");
  9545. str = write_expr_to_string(str, f->default_value, shorthand);
  9546. }
  9547. case_end;
  9548. case_ast_node(f, FieldList, node);
  9549. bool has_name = false;
  9550. for_array(i, f->list) {
  9551. ast_node(field, Field, f->list[i]);
  9552. if (field->names.count > 1) {
  9553. has_name = true;
  9554. break;
  9555. }
  9556. if (field->names.count == 0) {
  9557. continue;
  9558. }
  9559. if (!is_blank_ident(field->names[0])) {
  9560. has_name = true;
  9561. break;
  9562. }
  9563. }
  9564. for_array(i, f->list) {
  9565. if (i > 0) str = gb_string_appendc(str, ", ");
  9566. if (has_name) {
  9567. str = write_expr_to_string(str, f->list[i], shorthand);
  9568. } else {
  9569. ast_node(field, Field, f->list[i]);
  9570. if (field->flags&FieldFlag_using) {
  9571. str = gb_string_appendc(str, "using ");
  9572. }
  9573. if (field->flags&FieldFlag_no_alias) {
  9574. str = gb_string_appendc(str, "#no_alias ");
  9575. }
  9576. if (field->flags&FieldFlag_c_vararg) {
  9577. str = gb_string_appendc(str, "#c_vararg ");
  9578. }
  9579. str = write_expr_to_string(str, field->type, shorthand);
  9580. }
  9581. }
  9582. case_end;
  9583. case_ast_node(ce, CallExpr, node);
  9584. switch (ce->inlining) {
  9585. case ProcInlining_inline:
  9586. str = gb_string_appendc(str, "#force_inline ");
  9587. break;
  9588. case ProcInlining_no_inline:
  9589. str = gb_string_appendc(str, "#force_no_inline ");
  9590. break;
  9591. }
  9592. str = write_expr_to_string(str, ce->proc, shorthand);
  9593. str = gb_string_appendc(str, "(");
  9594. isize idx0 = cast(isize)ce->was_selector;
  9595. for (isize i = idx0; i < ce->args.count; i++) {
  9596. Ast *arg = ce->args[i];
  9597. if (i > idx0) {
  9598. str = gb_string_appendc(str, ", ");
  9599. }
  9600. str = write_expr_to_string(str, arg, shorthand);
  9601. }
  9602. str = gb_string_appendc(str, ")");
  9603. case_end;
  9604. case_ast_node(tt, TypeidType, node);
  9605. str = gb_string_appendc(str, "typeid");
  9606. if (tt->specialization) {
  9607. str = gb_string_appendc(str, "/");
  9608. str = write_expr_to_string(str, tt->specialization, shorthand);
  9609. }
  9610. case_end;
  9611. case_ast_node(pt, ProcType, node);
  9612. str = gb_string_appendc(str, "proc(");
  9613. str = write_expr_to_string(str, pt->params, shorthand);
  9614. str = gb_string_appendc(str, ")");
  9615. if (pt->results != nullptr) {
  9616. str = gb_string_appendc(str, " -> ");
  9617. bool parens_needed = false;
  9618. if (pt->results && pt->results->kind == Ast_FieldList) {
  9619. for (Ast *field : pt->results->FieldList.list) {
  9620. ast_node(f, Field, field);
  9621. if (f->names.count != 0) {
  9622. parens_needed = true;
  9623. break;
  9624. }
  9625. }
  9626. }
  9627. if (parens_needed) {
  9628. str = gb_string_append_rune(str, '(');
  9629. }
  9630. str = write_expr_to_string(str, pt->results, shorthand);
  9631. if (parens_needed) {
  9632. str = gb_string_append_rune(str, ')');
  9633. }
  9634. }
  9635. case_end;
  9636. case_ast_node(st, StructType, node);
  9637. str = gb_string_appendc(str, "struct ");
  9638. if (st->polymorphic_params) {
  9639. str = gb_string_append_rune(str, '(');
  9640. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9641. str = gb_string_appendc(str, ") ");
  9642. }
  9643. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9644. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9645. if (st->align) {
  9646. str = gb_string_appendc(str, "#align ");
  9647. str = write_expr_to_string(str, st->align, shorthand);
  9648. str = gb_string_append_rune(str, ' ');
  9649. }
  9650. str = gb_string_append_rune(str, '{');
  9651. if (shorthand) {
  9652. str = gb_string_appendc(str, "...");
  9653. } else {
  9654. str = write_struct_fields_to_string(str, st->fields);
  9655. }
  9656. str = gb_string_append_rune(str, '}');
  9657. case_end;
  9658. case_ast_node(st, UnionType, node);
  9659. str = gb_string_appendc(str, "union ");
  9660. if (st->polymorphic_params) {
  9661. str = gb_string_append_rune(str, '(');
  9662. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9663. str = gb_string_appendc(str, ") ");
  9664. }
  9665. switch (st->kind) {
  9666. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9667. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9668. }
  9669. if (st->align) {
  9670. str = gb_string_appendc(str, "#align ");
  9671. str = write_expr_to_string(str, st->align, shorthand);
  9672. str = gb_string_append_rune(str, ' ');
  9673. }
  9674. str = gb_string_append_rune(str, '{');
  9675. if (shorthand) {
  9676. str = gb_string_appendc(str, "...");
  9677. } else {
  9678. str = write_struct_fields_to_string(str, st->variants);
  9679. }
  9680. str = gb_string_append_rune(str, '}');
  9681. case_end;
  9682. case_ast_node(et, EnumType, node);
  9683. str = gb_string_appendc(str, "enum ");
  9684. if (et->base_type != nullptr) {
  9685. str = write_expr_to_string(str, et->base_type, shorthand);
  9686. str = gb_string_append_rune(str, ' ');
  9687. }
  9688. str = gb_string_append_rune(str, '{');
  9689. if (shorthand) {
  9690. str = gb_string_appendc(str, "...");
  9691. } else {
  9692. for_array(i, et->fields) {
  9693. if (i > 0) {
  9694. str = gb_string_appendc(str, ", ");
  9695. }
  9696. str = write_expr_to_string(str, et->fields[i], shorthand);
  9697. }
  9698. }
  9699. str = gb_string_append_rune(str, '}');
  9700. case_end;
  9701. case_ast_node(rt, RelativeType, node);
  9702. str = write_expr_to_string(str, rt->tag, shorthand);
  9703. str = gb_string_appendc(str, "" );
  9704. str = write_expr_to_string(str, rt->type, shorthand);
  9705. case_end;
  9706. case_ast_node(ia, InlineAsmExpr, node);
  9707. str = gb_string_appendc(str, "asm(");
  9708. for_array(i, ia->param_types) {
  9709. if (i > 0) {
  9710. str = gb_string_appendc(str, ", ");
  9711. }
  9712. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9713. }
  9714. str = gb_string_appendc(str, ")");
  9715. if (ia->return_type != nullptr) {
  9716. str = gb_string_appendc(str, " -> ");
  9717. str = write_expr_to_string(str, ia->return_type, shorthand);
  9718. }
  9719. if (ia->has_side_effects) {
  9720. str = gb_string_appendc(str, " #side_effects");
  9721. }
  9722. if (ia->is_align_stack) {
  9723. str = gb_string_appendc(str, " #stack_align");
  9724. }
  9725. if (ia->dialect) {
  9726. str = gb_string_appendc(str, " #");
  9727. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9728. }
  9729. str = gb_string_appendc(str, " {");
  9730. if (shorthand) {
  9731. str = gb_string_appendc(str, "...");
  9732. } else {
  9733. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9734. str = gb_string_appendc(str, ", ");
  9735. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9736. }
  9737. str = gb_string_appendc(str, "}");
  9738. case_end;
  9739. }
  9740. return str;
  9741. }
  9742. gb_internal gbString expr_to_string(Ast *expression) {
  9743. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9744. }
  9745. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  9746. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  9747. }
  9748. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  9749. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9750. }