check_expr.cpp 314 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957
  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. ERROR_BLOCK();
  161. GB_ASSERT(e->kind == Entity_TypeName);
  162. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  163. auto *objc_metadata = e->TypeName.objc_metadata;
  164. MUTEX_GUARD(objc_metadata->mutex);
  165. StringSet set = {};
  166. defer (string_set_destroy(&set));
  167. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  168. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  169. defer (did_you_mean_destroy(&d));
  170. for (String const &target : set) {
  171. did_you_mean_append(&d, target);
  172. }
  173. check_did_you_mean_print(&d, prefix);
  174. }
  175. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  176. ERROR_BLOCK();
  177. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  178. defer (did_you_mean_destroy(&d));
  179. for (Entity *e : fields) {
  180. did_you_mean_append(&d, e->token.string);
  181. }
  182. check_did_you_mean_print(&d, prefix);
  183. }
  184. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  185. ERROR_BLOCK();
  186. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  187. defer (did_you_mean_destroy(&d));
  188. for (Entity *e : fields) {
  189. did_you_mean_append(&d, e->token.string);
  190. }
  191. check_did_you_mean_print(&d, prefix);
  192. }
  193. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  194. ERROR_BLOCK();
  195. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  196. defer (did_you_mean_destroy(&d));
  197. rw_mutex_shared_lock(&scope->mutex);
  198. for (auto const &entry : scope->elements) {
  199. Entity *e = entry.value;
  200. did_you_mean_append(&d, e->token.string);
  201. }
  202. rw_mutex_shared_unlock(&scope->mutex);
  203. check_did_you_mean_print(&d, prefix);
  204. }
  205. gb_internal Entity *entity_from_expr(Ast *expr) {
  206. expr = unparen_expr(expr);
  207. switch (expr->kind) {
  208. case Ast_Ident:
  209. return expr->Ident.entity;
  210. case Ast_SelectorExpr:
  211. return entity_from_expr(expr->SelectorExpr.selector);
  212. }
  213. return nullptr;
  214. }
  215. gb_internal void error_operand_not_expression(Operand *o) {
  216. if (o->mode == Addressing_Type) {
  217. gbString err = expr_to_string(o->expr);
  218. error(o->expr, "'%s' is not an expression but a type", err);
  219. gb_string_free(err);
  220. o->mode = Addressing_Invalid;
  221. }
  222. }
  223. gb_internal void error_operand_no_value(Operand *o) {
  224. if (o->mode == Addressing_NoValue) {
  225. gbString err = expr_to_string(o->expr);
  226. Ast *x = unparen_expr(o->expr);
  227. if (x->kind == Ast_CallExpr) {
  228. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  229. } else {
  230. error(o->expr, "'%s' used as a value", err);
  231. }
  232. gb_string_free(err);
  233. o->mode = Addressing_Invalid;
  234. }
  235. }
  236. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  237. if (build_context.dynamic_map_calls) {
  238. add_package_dependency(c, "runtime", "__dynamic_map_get");
  239. } else {
  240. add_package_dependency(c, "runtime", "map_desired_position");
  241. add_package_dependency(c, "runtime", "map_probe_distance");
  242. }
  243. }
  244. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  245. init_core_source_code_location(c->checker);
  246. if (t_map_set_proc == nullptr) {
  247. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  248. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  249. }
  250. if (build_context.dynamic_map_calls) {
  251. add_package_dependency(c, "runtime", "__dynamic_map_set");
  252. } else {
  253. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  254. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  255. }
  256. }
  257. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  258. init_core_source_code_location(c->checker);
  259. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  260. }
  261. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  262. Scope *s = c->scope;
  263. check_collect_entities(c, nodes);
  264. for (auto const &entry : s->elements) {
  265. Entity *e = entry.value;
  266. switch (e->kind) {
  267. case Entity_Constant:
  268. case Entity_TypeName:
  269. case Entity_Procedure:
  270. break;
  271. default:
  272. continue;
  273. }
  274. DeclInfo *d = decl_info_of_entity(e);
  275. if (d != nullptr) {
  276. check_entity_decl(c, e, d, nullptr);
  277. }
  278. }
  279. }
  280. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  281. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  282. ///////////////////////////////////////////////////////////////////////////////
  283. // //
  284. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  285. // //
  286. ///////////////////////////////////////////////////////////////////////////////
  287. CheckerInfo *info = old_c->info;
  288. if (base_entity == nullptr) {
  289. return false;
  290. }
  291. if (!is_type_proc(base_entity->type)) {
  292. return false;
  293. }
  294. if (base_entity->flags & EntityFlag_Disabled) {
  295. return false;
  296. }
  297. String name = base_entity->token.string;
  298. Type *src = base_type(base_entity->type);
  299. Type *dst = nullptr;
  300. if (type != nullptr) {
  301. dst = base_type(type);
  302. }
  303. if (param_operands == nullptr) {
  304. GB_ASSERT(dst != nullptr);
  305. }
  306. if (param_operands != nullptr) {
  307. GB_ASSERT(dst == nullptr);
  308. }
  309. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  310. return false;
  311. }
  312. if (dst != nullptr) {
  313. if (dst->Proc.is_polymorphic) {
  314. return false;
  315. }
  316. if (dst->Proc.param_count != src->Proc.param_count ||
  317. dst->Proc.result_count != src->Proc.result_count) {
  318. return false;
  319. }
  320. }
  321. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  322. if (old_decl == nullptr) {
  323. return false;
  324. }
  325. gbAllocator a = heap_allocator();
  326. Array<Operand> operands = {};
  327. if (param_operands) {
  328. operands = *param_operands;
  329. } else {
  330. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  331. for (isize i = 0; i < dst->Proc.param_count; i++) {
  332. Entity *param = dst->Proc.params->Tuple.variables[i];
  333. Operand o = {Addressing_Value};
  334. o.type = param->type;
  335. array_add(&operands, o);
  336. }
  337. }
  338. defer (if (param_operands == nullptr) {
  339. array_free(&operands);
  340. });
  341. CheckerContext nctx = *old_c;
  342. Scope *scope = create_scope(info, base_entity->scope);
  343. scope->flags |= ScopeFlag_Proc;
  344. nctx.scope = scope;
  345. nctx.allow_polymorphic_types = true;
  346. if (nctx.polymorphic_scope == nullptr) {
  347. nctx.polymorphic_scope = scope;
  348. }
  349. auto *pt = &src->Proc;
  350. // NOTE(bill): This is slightly memory leaking if the type already exists
  351. // Maybe it's better to check with the previous types first?
  352. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  353. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  354. if (!success) {
  355. return false;
  356. }
  357. GenProcsData *gen_procs = nullptr;
  358. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  359. GB_ASSERT(base_entity->kind == Entity_Procedure);
  360. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  361. gen_procs = base_entity->Procedure.gen_procs;
  362. if (gen_procs) {
  363. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  364. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  365. for (Entity *other : gen_procs->procs) {
  366. Type *pt = base_type(other->type);
  367. if (are_types_identical(pt, final_proc_type)) {
  368. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  369. if (poly_proc_data) {
  370. poly_proc_data->gen_entity = other;
  371. }
  372. return true;
  373. }
  374. }
  375. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  376. } else {
  377. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  378. gen_procs->procs.allocator = heap_allocator();
  379. base_entity->Procedure.gen_procs = gen_procs;
  380. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  381. }
  382. {
  383. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  384. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  385. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  386. nctx.no_polymorphic_errors = false;
  387. // NOTE(bill): Reset scope from the failed procedure type
  388. scope_reset(scope);
  389. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  390. Ast *cloned_proc_type_node = clone_ast(pt->node);
  391. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  392. if (!success) {
  393. return false;
  394. }
  395. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  396. for (Entity *other : gen_procs->procs) {
  397. Type *pt = base_type(other->type);
  398. if (are_types_identical(pt, final_proc_type)) {
  399. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  400. if (poly_proc_data) {
  401. poly_proc_data->gen_entity = other;
  402. }
  403. DeclInfo *decl = other->decl_info;
  404. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  405. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  406. proc_info->file = other->file;
  407. proc_info->token = other->token;
  408. proc_info->decl = decl;
  409. proc_info->type = other->type;
  410. proc_info->body = decl->proc_lit->ProcLit.body;
  411. proc_info->tags = other->Procedure.tags;;
  412. proc_info->generated_from_polymorphic = true;
  413. proc_info->poly_def_node = poly_def_node;
  414. check_procedure_later(nctx.checker, proc_info);
  415. }
  416. return true;
  417. }
  418. }
  419. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  420. }
  421. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  422. ast_node(pl, ProcLit, proc_lit);
  423. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  424. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  425. final_proc_type->Proc.is_poly_specialized = true;
  426. final_proc_type->Proc.is_polymorphic = true;
  427. final_proc_type->Proc.variadic = src->Proc.variadic;
  428. final_proc_type->Proc.require_results = src->Proc.require_results;
  429. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  430. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  431. final_proc_type->Proc.diverging = src->Proc.diverging;
  432. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  433. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  434. for (isize i = 0; i < operands.count; i++) {
  435. Operand o = operands[i];
  436. if (final_proc_type == o.type ||
  437. base_entity->type == o.type) {
  438. // NOTE(bill): Cycle
  439. final_proc_type->Proc.is_poly_specialized = false;
  440. break;
  441. }
  442. }
  443. u64 tags = base_entity->Procedure.tags;
  444. Ast *ident = clone_ast(base_entity->identifier);
  445. Token token = ident->Ident.token;
  446. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  447. d->gen_proc_type = final_proc_type;
  448. d->type_expr = pl->type;
  449. d->proc_lit = proc_lit;
  450. d->proc_checked_state = ProcCheckedState_Unchecked;
  451. d->defer_use_checked = false;
  452. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  453. entity->identifier = ident;
  454. add_entity_and_decl_info(&nctx, ident, entity, d);
  455. // NOTE(bill): Set the scope afterwards as this is not real overloading
  456. entity->scope = scope->parent;
  457. entity->file = base_entity->file;
  458. entity->pkg = base_entity->pkg;
  459. entity->flags = 0;
  460. d->entity = entity;
  461. AstFile *file = nullptr;
  462. {
  463. Scope *s = entity->scope;
  464. while (s != nullptr && s->file == nullptr) {
  465. file = s->file;
  466. s = s->parent;
  467. }
  468. }
  469. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  470. array_add(&gen_procs->procs, entity);
  471. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  472. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  473. proc_info->file = file;
  474. proc_info->token = token;
  475. proc_info->decl = d;
  476. proc_info->type = final_proc_type;
  477. proc_info->body = pl->body;
  478. proc_info->tags = tags;
  479. proc_info->generated_from_polymorphic = true;
  480. proc_info->poly_def_node = poly_def_node;
  481. if (poly_proc_data) {
  482. poly_proc_data->gen_entity = entity;
  483. poly_proc_data->proc_info = proc_info;
  484. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  485. }
  486. // NOTE(bill): Check the newly generated procedure body
  487. check_procedure_later(nctx.checker, proc_info);
  488. return true;
  489. }
  490. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  491. if (operand->expr == nullptr) return false;
  492. Entity *base_entity = entity_of_node(operand->expr);
  493. if (base_entity == nullptr) return false;
  494. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  495. }
  496. 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) {
  497. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  498. }
  499. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  500. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  501. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  502. #define MAXIMUM_TYPE_DISTANCE 10
  503. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  504. if (c == nullptr) {
  505. GB_ASSERT(operand->mode == Addressing_Value);
  506. GB_ASSERT(is_type_typed(operand->type));
  507. }
  508. if (operand->mode == Addressing_Invalid ||
  509. type == t_invalid) {
  510. return -1;
  511. }
  512. if (operand->mode == Addressing_Builtin) {
  513. return -1;
  514. }
  515. if (operand->mode == Addressing_Type) {
  516. if (is_type_typeid(type)) {
  517. if (is_type_polymorphic(operand->type)) {
  518. return -1;
  519. }
  520. add_type_info_type(c, operand->type);
  521. return 4;
  522. }
  523. return -1;
  524. }
  525. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  526. return -1;
  527. }
  528. Type *s = operand->type;
  529. if (are_types_identical(s, type)) {
  530. return 0;
  531. }
  532. Type *src = base_type(s);
  533. Type *dst = base_type(type);
  534. if (is_type_untyped_uninit(src)) {
  535. return 1;
  536. }
  537. if (is_type_untyped_nil(src)) {
  538. if (type_has_nil(dst)) {
  539. return 1;
  540. }
  541. return -1;
  542. }
  543. if (is_type_untyped(src)) {
  544. if (is_type_any(dst)) {
  545. // NOTE(bill): Anything can cast to 'Any'
  546. add_type_info_type(c, s);
  547. return MAXIMUM_TYPE_DISTANCE;
  548. }
  549. if (dst->kind == Type_Basic) {
  550. if (operand->mode == Addressing_Constant) {
  551. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  552. if (is_type_typed(dst) && src->kind == Type_Basic) {
  553. switch (src->Basic.kind) {
  554. case Basic_UntypedBool:
  555. if (is_type_boolean(dst)) {
  556. return 1;
  557. }
  558. break;
  559. case Basic_UntypedRune:
  560. if (is_type_integer(dst) || is_type_rune(dst)) {
  561. return 1;
  562. }
  563. break;
  564. case Basic_UntypedInteger:
  565. if (is_type_integer(dst) || is_type_rune(dst)) {
  566. return 1;
  567. }
  568. break;
  569. case Basic_UntypedString:
  570. if (is_type_string(dst)) {
  571. return 1;
  572. }
  573. break;
  574. case Basic_UntypedFloat:
  575. if (is_type_float(dst)) {
  576. return 1;
  577. }
  578. break;
  579. case Basic_UntypedComplex:
  580. if (is_type_complex(dst)) {
  581. return 1;
  582. }
  583. if (is_type_quaternion(dst)) {
  584. return 2;
  585. }
  586. break;
  587. case Basic_UntypedQuaternion:
  588. if (is_type_quaternion(dst)) {
  589. return 1;
  590. }
  591. break;
  592. }
  593. }
  594. return 2;
  595. }
  596. return -1;
  597. }
  598. if (src->kind == Type_Basic) {
  599. Type *d = base_array_type(dst);
  600. i64 score = -1;
  601. switch (src->Basic.kind) {
  602. case Basic_UntypedBool:
  603. if (is_type_boolean(d)) {
  604. score = 1;
  605. }
  606. break;
  607. case Basic_UntypedRune:
  608. if (is_type_integer(d) || is_type_rune(d)) {
  609. score = 1;
  610. }
  611. break;
  612. case Basic_UntypedInteger:
  613. if (is_type_integer(d) || is_type_rune(d)) {
  614. score = 1;
  615. }
  616. break;
  617. case Basic_UntypedString:
  618. if (is_type_string(d)) {
  619. score = 1;
  620. }
  621. break;
  622. case Basic_UntypedFloat:
  623. if (is_type_float(d)) {
  624. score = 1;
  625. }
  626. break;
  627. case Basic_UntypedComplex:
  628. if (is_type_complex(d)) {
  629. score = 1;
  630. }
  631. if (is_type_quaternion(d)) {
  632. score = 2;
  633. }
  634. break;
  635. case Basic_UntypedQuaternion:
  636. if (is_type_quaternion(d)) {
  637. score = 1;
  638. }
  639. break;
  640. }
  641. if (score > 0) {
  642. if (is_type_typed(d)) {
  643. score += 1;
  644. }
  645. if (d != dst) {
  646. score += 6;
  647. }
  648. }
  649. return score;
  650. }
  651. }
  652. }
  653. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  654. if (c->in_enum_type) {
  655. return 3;
  656. }
  657. }
  658. {
  659. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  660. if (subtype_level > 0) {
  661. return 4 + subtype_level;
  662. }
  663. }
  664. // rawptr <- ^T
  665. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  666. return 5;
  667. }
  668. // rawptr <- [^]T
  669. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  670. return 5;
  671. }
  672. // ^T <- [^]T
  673. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  674. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  675. return 4;
  676. }
  677. }
  678. // [^]T <- ^T
  679. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  680. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  681. return 4;
  682. }
  683. }
  684. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  685. bool modify_type = !c->no_polymorphic_errors;
  686. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  687. return 2;
  688. }
  689. }
  690. if (is_type_union(dst)) {
  691. for (Type *vt : dst->Union.variants) {
  692. if (are_types_identical(vt, s)) {
  693. return 1;
  694. }
  695. }
  696. if (dst->Union.variants.count == 1) {
  697. Type *vt = dst->Union.variants[0];
  698. i64 score = check_distance_between_types(c, operand, vt);
  699. if (score >= 0) {
  700. return score+2;
  701. }
  702. } else if (is_type_untyped(src)) {
  703. i64 prev_lowest_score = -1;
  704. i64 lowest_score = -1;
  705. for (Type *vt : dst->Union.variants) {
  706. i64 score = check_distance_between_types(c, operand, vt);
  707. if (score >= 0) {
  708. if (lowest_score < 0) {
  709. lowest_score = score;
  710. } else {
  711. if (prev_lowest_score < 0) {
  712. prev_lowest_score = lowest_score;
  713. } else {
  714. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  715. }
  716. lowest_score = gb_min(lowest_score, score);
  717. }
  718. }
  719. }
  720. if (lowest_score >= 0) {
  721. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  722. return lowest_score+2;
  723. }
  724. }
  725. }
  726. }
  727. if (is_type_relative_pointer(dst)) {
  728. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  729. if (score >= 0) {
  730. return score+2;
  731. }
  732. }
  733. if (is_type_relative_multi_pointer(dst)) {
  734. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type);
  735. if (score >= 0) {
  736. return score+2;
  737. }
  738. }
  739. if (is_type_proc(dst)) {
  740. if (are_types_identical(src, dst)) {
  741. return 3;
  742. }
  743. PolyProcData poly_proc_data = {};
  744. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  745. Entity *e = poly_proc_data.gen_entity;
  746. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  747. add_entity_use(c, operand->expr, e);
  748. return 4;
  749. }
  750. }
  751. if (is_type_complex_or_quaternion(dst)) {
  752. Type *elem = base_complex_elem_type(dst);
  753. if (are_types_identical(elem, base_type(src))) {
  754. return 5;
  755. }
  756. }
  757. if (is_type_array(dst)) {
  758. Type *elem = base_array_type(dst);
  759. i64 distance = check_distance_between_types(c, operand, elem);
  760. if (distance >= 0) {
  761. return distance + 6;
  762. }
  763. }
  764. if (is_type_simd_vector(dst)) {
  765. Type *dst_elem = base_array_type(dst);
  766. i64 distance = check_distance_between_types(c, operand, dst_elem);
  767. if (distance >= 0) {
  768. return distance + 6;
  769. }
  770. }
  771. if (is_type_matrix(dst)) {
  772. if (are_types_identical(src, dst)) {
  773. return 5;
  774. }
  775. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  776. Type *dst_elem = base_array_type(dst);
  777. i64 distance = check_distance_between_types(c, operand, dst_elem);
  778. if (distance >= 0) {
  779. return distance + 7;
  780. }
  781. }
  782. }
  783. if (is_type_any(dst)) {
  784. if (!is_type_polymorphic(src)) {
  785. if (operand->mode == Addressing_Context && operand->type == t_context) {
  786. return -1;
  787. } else {
  788. // NOTE(bill): Anything can cast to 'Any'
  789. add_type_info_type(c, s);
  790. return MAXIMUM_TYPE_DISTANCE;
  791. }
  792. }
  793. }
  794. Ast *expr = unparen_expr(operand->expr);
  795. if (expr != nullptr) {
  796. if (expr->kind == Ast_AutoCast) {
  797. Operand x = *operand;
  798. x.expr = expr->AutoCast.expr;
  799. if (check_cast_internal(c, &x, type)) {
  800. return MAXIMUM_TYPE_DISTANCE;
  801. }
  802. }
  803. }
  804. return -1;
  805. }
  806. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  807. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  808. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  809. // TODO(bill): A decent score function
  810. i64 d = distance*distance; // x^2
  811. if (is_variadic && d >= 0) {
  812. d += distance + 1; // x^2 + x + 1
  813. }
  814. return gb_max(c - d, 0);
  815. }
  816. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  817. i64 score = 0;
  818. i64 distance = check_distance_between_types(c, operand, type);
  819. bool ok = distance >= 0;
  820. if (ok) {
  821. score = assign_score_function(distance, is_variadic);
  822. }
  823. if (score_) *score_ = score;
  824. return ok;
  825. }
  826. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  827. i64 score = 0;
  828. return check_is_assignable_to_with_score(c, operand, type, &score);
  829. }
  830. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  831. Operand x = {};
  832. x.type = src;
  833. x.mode = Addressing_Value;
  834. return check_is_assignable_to(nullptr, &x, dst);
  835. }
  836. gb_internal AstPackage *get_package_of_type(Type *type) {
  837. for (;;) {
  838. if (type == nullptr) {
  839. return nullptr;
  840. }
  841. switch (type->kind) {
  842. case Type_Basic:
  843. return builtin_pkg;
  844. case Type_Named:
  845. if (type->Named.type_name != nullptr) {
  846. return type->Named.type_name->pkg;
  847. }
  848. return nullptr;
  849. case Type_Pointer:
  850. type = type->Pointer.elem;
  851. continue;
  852. case Type_Array:
  853. type = type->Array.elem;
  854. continue;
  855. case Type_Slice:
  856. type = type->Slice.elem;
  857. continue;
  858. case Type_DynamicArray:
  859. type = type->DynamicArray.elem;
  860. continue;
  861. case Type_RelativePointer:
  862. type = type->RelativePointer.pointer_type;
  863. continue;
  864. case Type_RelativeMultiPointer:
  865. type = type->RelativeMultiPointer.pointer_type;
  866. continue;
  867. }
  868. return nullptr;
  869. }
  870. }
  871. // NOTE(bill): 'content_name' is for debugging and error messages
  872. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  873. check_not_tuple(c, operand);
  874. if (operand->mode == Addressing_Invalid) {
  875. return;
  876. }
  877. if (is_type_untyped(operand->type)) {
  878. Type *target_type = type;
  879. if (type == nullptr || is_type_any(type)) {
  880. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  881. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  882. operand->mode = Addressing_Invalid;
  883. return;
  884. }
  885. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  886. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  887. operand->mode = Addressing_Invalid;
  888. return;
  889. }
  890. target_type = default_type(operand->type);
  891. if (type != nullptr && !is_type_any(type)) {
  892. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  893. }
  894. add_type_info_type(c, type);
  895. add_type_info_type(c, target_type);
  896. }
  897. convert_to_typed(c, operand, target_type);
  898. if (operand->mode == Addressing_Invalid) {
  899. return;
  900. }
  901. }
  902. if (type == nullptr) {
  903. return;
  904. }
  905. if (operand->mode == Addressing_ProcGroup) {
  906. bool good = false;
  907. if (type != nullptr && is_type_proc(type)) {
  908. Array<Entity *> procs = proc_group_entities(c, *operand);
  909. // NOTE(bill): These should be done
  910. for (Entity *e : procs) {
  911. Type *t = base_type(e->type);
  912. if (t == t_invalid) {
  913. continue;
  914. }
  915. Operand x = {};
  916. x.mode = Addressing_Value;
  917. x.type = t;
  918. if (check_is_assignable_to(c, &x, type)) {
  919. add_entity_use(c, operand->expr, e);
  920. good = true;
  921. break;
  922. }
  923. }
  924. }
  925. if (!good) {
  926. gbString expr_str = expr_to_string(operand->expr);
  927. gbString op_type_str = type_to_string(operand->type);
  928. gbString type_str = type_to_string(type);
  929. defer (gb_string_free(type_str));
  930. defer (gb_string_free(op_type_str));
  931. defer (gb_string_free(expr_str));
  932. // TODO(bill): is this a good enough error message?
  933. error(operand->expr,
  934. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  935. expr_str,
  936. op_type_str,
  937. LIT(context_name));
  938. operand->mode = Addressing_Invalid;
  939. }
  940. convert_to_typed(c, operand, type);
  941. return;
  942. }
  943. if (check_is_assignable_to(c, operand, type)) {
  944. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  945. add_type_info_type(c, operand->type);
  946. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  947. }
  948. } else {
  949. gbString expr_str = expr_to_string(operand->expr);
  950. gbString op_type_str = type_to_string(operand->type);
  951. gbString type_str = type_to_string(type);
  952. defer (gb_string_free(type_str));
  953. defer (gb_string_free(op_type_str));
  954. defer (gb_string_free(expr_str));
  955. switch (operand->mode) {
  956. case Addressing_Builtin:
  957. error(operand->expr,
  958. "Cannot assign built-in procedure '%s' in %.*s",
  959. expr_str,
  960. LIT(context_name));
  961. break;
  962. case Addressing_Type:
  963. if (is_type_polymorphic(operand->type)) {
  964. error(operand->expr,
  965. "Cannot assign '%s' which is a polymorphic type in %.*s",
  966. op_type_str,
  967. LIT(context_name));
  968. } else {
  969. error(operand->expr,
  970. "Cannot assign '%s' which is a type in %.*s",
  971. op_type_str,
  972. LIT(context_name));
  973. }
  974. break;
  975. default:
  976. // TODO(bill): is this a good enough error message?
  977. {
  978. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  979. gbString type_extra = gb_string_make(heap_allocator(), "");
  980. defer (gb_string_free(op_type_extra));
  981. defer (gb_string_free(type_extra));
  982. isize on = gb_string_length(op_type_str);
  983. isize tn = gb_string_length(type_str);
  984. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  985. AstPackage *op_pkg = get_package_of_type(operand->type);
  986. AstPackage *type_pkg = get_package_of_type(type);
  987. if (op_pkg != nullptr) {
  988. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  989. }
  990. if (type_pkg != nullptr) {
  991. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  992. }
  993. }
  994. ERROR_BLOCK();
  995. error(operand->expr,
  996. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  997. expr_str,
  998. op_type_str, op_type_extra,
  999. type_str, type_extra,
  1000. LIT(context_name));
  1001. check_assignment_error_suggestion(c, operand, type);
  1002. }
  1003. break;
  1004. }
  1005. operand->mode = Addressing_Invalid;
  1006. return;
  1007. }
  1008. }
  1009. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1010. Type *gt = *gt_;
  1011. GB_ASSERT(gt->kind == Type_Generic);
  1012. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1013. GB_ASSERT(e != nullptr);
  1014. if (e->kind == Entity_TypeName) {
  1015. *gt_ = nullptr;
  1016. *dst_count = source_count;
  1017. e->kind = Entity_Constant;
  1018. e->Constant.value = exact_value_i64(source_count);
  1019. e->type = t_untyped_integer;
  1020. return true;
  1021. } else if (e->kind == Entity_Constant) {
  1022. *gt_ = nullptr;
  1023. if (e->Constant.value.kind != ExactValue_Integer) {
  1024. return false;
  1025. }
  1026. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1027. if (count != source_count) {
  1028. return false;
  1029. }
  1030. *dst_count = source_count;
  1031. return true;
  1032. }
  1033. return false;
  1034. }
  1035. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1036. Operand o = {Addressing_Value};
  1037. o.type = source;
  1038. switch (poly->kind) {
  1039. case Type_Basic:
  1040. if (compound) return are_types_identical(poly, source);
  1041. return check_is_assignable_to(c, &o, poly);
  1042. case Type_Named: {
  1043. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1044. return true;
  1045. }
  1046. if (compound || !is_type_generic(poly)) {
  1047. return are_types_identical(poly, source);
  1048. }
  1049. return check_is_assignable_to(c, &o, poly);
  1050. }
  1051. case Type_Generic: {
  1052. if (poly->Generic.specialized != nullptr) {
  1053. Type *s = poly->Generic.specialized;
  1054. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1055. return false;
  1056. }
  1057. }
  1058. if (modify_type) {
  1059. Type *ds = default_type(source);
  1060. gb_memmove(poly, ds, gb_size_of(Type));
  1061. }
  1062. return true;
  1063. }
  1064. case Type_Pointer:
  1065. if (source->kind == Type_Pointer) {
  1066. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem);
  1067. if (level > 0) {
  1068. return true;
  1069. }
  1070. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1071. } else if (source->kind == Type_MultiPointer) {
  1072. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1073. if (level > 0) {
  1074. return true;
  1075. }
  1076. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1077. }
  1078. return false;
  1079. case Type_MultiPointer:
  1080. if (source->kind == Type_MultiPointer) {
  1081. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1082. if (level > 0) {
  1083. return true;
  1084. }
  1085. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1086. } else if (source->kind == Type_Pointer) {
  1087. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1088. if (level > 0) {
  1089. return true;
  1090. }
  1091. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1092. }
  1093. return false;
  1094. case Type_Array:
  1095. if (source->kind == Type_Array) {
  1096. if (poly->Array.generic_count != nullptr) {
  1097. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1098. return false;
  1099. }
  1100. }
  1101. if (poly->Array.count == source->Array.count) {
  1102. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1103. }
  1104. } else if (source->kind == Type_EnumeratedArray) {
  1105. if (poly->Array.generic_count != nullptr) {
  1106. Type *gt = poly->Array.generic_count;
  1107. GB_ASSERT(gt->kind == Type_Generic);
  1108. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1109. GB_ASSERT(e != nullptr);
  1110. if (e->kind == Entity_TypeName) {
  1111. Type *index = source->EnumeratedArray.index;
  1112. Type *it = base_type(index);
  1113. if (it->kind != Type_Enum) {
  1114. return false;
  1115. }
  1116. poly->kind = Type_EnumeratedArray;
  1117. poly->cached_size = -1;
  1118. poly->cached_align = -1;
  1119. poly->flags.exchange(source->flags);
  1120. poly->failure = false;
  1121. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1122. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1123. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1124. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1125. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1126. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1127. e->kind = Entity_TypeName;
  1128. e->TypeName.is_type_alias = true;
  1129. e->type = index;
  1130. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1131. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1132. }
  1133. }
  1134. }
  1135. }
  1136. return false;
  1137. case Type_EnumeratedArray:
  1138. if (source->kind == Type_EnumeratedArray) {
  1139. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1140. return false;
  1141. }
  1142. if (poly->EnumeratedArray.op) {
  1143. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1144. return false;
  1145. }
  1146. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1147. return false;
  1148. }
  1149. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1150. return false;
  1151. }
  1152. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1153. }
  1154. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1155. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1156. return index || elem;
  1157. }
  1158. return false;
  1159. case Type_DynamicArray:
  1160. if (source->kind == Type_DynamicArray) {
  1161. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1162. }
  1163. return false;
  1164. case Type_Slice:
  1165. if (source->kind == Type_Slice) {
  1166. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1167. }
  1168. return false;
  1169. case Type_Enum:
  1170. return false;
  1171. case Type_BitSet:
  1172. if (source->kind == Type_BitSet) {
  1173. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1174. return false;
  1175. }
  1176. if (poly->BitSet.underlying == nullptr) {
  1177. if (modify_type) {
  1178. poly->BitSet.underlying = source->BitSet.underlying;
  1179. }
  1180. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1181. return false;
  1182. }
  1183. return true;
  1184. }
  1185. return false;
  1186. case Type_Union:
  1187. if (source->kind == Type_Union) {
  1188. TypeUnion *x = &poly->Union;
  1189. TypeUnion *y = &source->Union;
  1190. if (x->variants.count != y->variants.count) {
  1191. return false;
  1192. }
  1193. for_array(i, x->variants) {
  1194. Type *a = x->variants[i];
  1195. Type *b = y->variants[i];
  1196. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1197. if (!ok) return false;
  1198. }
  1199. return true;
  1200. }
  1201. return false;
  1202. case Type_Struct:
  1203. if (source->kind == Type_Struct) {
  1204. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1205. poly->Struct.soa_kind != StructSoa_None) {
  1206. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1207. if (ok) switch (source->Struct.soa_kind) {
  1208. case StructSoa_Fixed:
  1209. default:
  1210. GB_PANIC("Unhandled SOA Kind");
  1211. break;
  1212. case StructSoa_Slice:
  1213. if (modify_type) {
  1214. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1215. gb_memmove(poly, type, gb_size_of(*type));
  1216. }
  1217. break;
  1218. case StructSoa_Dynamic:
  1219. if (modify_type) {
  1220. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1221. gb_memmove(poly, type, gb_size_of(*type));
  1222. }
  1223. break;
  1224. }
  1225. return ok;
  1226. }
  1227. // return check_is_assignable_to(c, &o, poly);
  1228. }
  1229. return false;
  1230. case Type_Tuple:
  1231. GB_PANIC("This should never happen");
  1232. return false;
  1233. case Type_Proc:
  1234. if (source->kind == Type_Proc) {
  1235. TypeProc *x = &poly->Proc;
  1236. TypeProc *y = &source->Proc;
  1237. if (x->calling_convention != y->calling_convention) {
  1238. return false;
  1239. }
  1240. if (x->c_vararg != y->c_vararg) {
  1241. return false;
  1242. }
  1243. if (x->variadic != y->variadic) {
  1244. return false;
  1245. }
  1246. if (x->param_count != y->param_count) {
  1247. return false;
  1248. }
  1249. if (x->result_count != y->result_count) {
  1250. return false;
  1251. }
  1252. for (isize i = 0; i < x->param_count; i++) {
  1253. Entity *a = x->params->Tuple.variables[i];
  1254. Entity *b = y->params->Tuple.variables[i];
  1255. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1256. if (!ok) return false;
  1257. }
  1258. for (isize i = 0; i < x->result_count; i++) {
  1259. Entity *a = x->results->Tuple.variables[i];
  1260. Entity *b = y->results->Tuple.variables[i];
  1261. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1262. if (!ok) return false;
  1263. }
  1264. return true;
  1265. }
  1266. return false;
  1267. case Type_Map:
  1268. if (source->kind == Type_Map) {
  1269. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1270. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1271. if (key || value) {
  1272. poly->Map.lookup_result_type = nullptr;
  1273. init_map_internal_types(poly);
  1274. return true;
  1275. }
  1276. }
  1277. return false;
  1278. case Type_Matrix:
  1279. if (source->kind == Type_Matrix) {
  1280. if (poly->Matrix.generic_row_count != nullptr) {
  1281. poly->Matrix.stride_in_bytes = 0;
  1282. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1283. return false;
  1284. }
  1285. }
  1286. if (poly->Matrix.generic_column_count != nullptr) {
  1287. poly->Matrix.stride_in_bytes = 0;
  1288. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1289. return false;
  1290. }
  1291. }
  1292. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1293. poly->Matrix.column_count == source->Matrix.column_count) {
  1294. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1295. }
  1296. }
  1297. return false;
  1298. case Type_SimdVector:
  1299. if (source->kind == Type_SimdVector) {
  1300. if (poly->SimdVector.generic_count != nullptr) {
  1301. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1302. return false;
  1303. }
  1304. }
  1305. if (poly->SimdVector.count == source->SimdVector.count) {
  1306. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1307. }
  1308. }
  1309. return false;
  1310. }
  1311. return false;
  1312. }
  1313. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1314. if (curr->state != EntityState_InProgress) {
  1315. return false;
  1316. }
  1317. for_array(i, *c->type_path) {
  1318. Entity *prev = c->type_path->data[i];
  1319. if (prev == curr) {
  1320. if (report) {
  1321. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1322. for (isize j = i; j < c->type_path->count; j++) {
  1323. Entity *curr = (*c->type_path)[j];
  1324. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1325. }
  1326. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1327. curr->type = t_invalid;
  1328. }
  1329. return true;
  1330. }
  1331. }
  1332. return false;
  1333. }
  1334. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1335. GB_ASSERT(n->kind == Ast_Ident);
  1336. o->mode = Addressing_Invalid;
  1337. o->expr = n;
  1338. String name = n->Ident.token.string;
  1339. Entity *e = scope_lookup(c->scope, name);
  1340. if (e == nullptr) {
  1341. if (is_blank_ident(name)) {
  1342. error(n, "'_' cannot be used as a value");
  1343. } else {
  1344. error(n, "Undeclared name: %.*s", LIT(name));
  1345. }
  1346. o->type = t_invalid;
  1347. o->mode = Addressing_Invalid;
  1348. if (named_type != nullptr) {
  1349. set_base_type(named_type, t_invalid);
  1350. }
  1351. return nullptr;
  1352. }
  1353. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1354. if (e->parent_proc_decl != nullptr &&
  1355. e->parent_proc_decl != c->curr_proc_decl) {
  1356. if (e->kind == Entity_Variable) {
  1357. if ((e->flags & EntityFlag_Static) == 0) {
  1358. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1359. return nullptr;
  1360. }
  1361. } else if (e->kind == Entity_Label) {
  1362. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1363. return nullptr;
  1364. }
  1365. }
  1366. if (e->kind == Entity_ProcGroup) {
  1367. auto *pge = &e->ProcGroup;
  1368. DeclInfo *d = decl_info_of_entity(e);
  1369. check_entity_decl(c, e, d, nullptr);
  1370. Array<Entity *> procs = pge->entities;
  1371. bool skip = false;
  1372. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1373. // NOTE(bill): These should be done
  1374. for (Entity *proc : procs) {
  1375. Type *t = base_type(proc->type);
  1376. if (t == t_invalid) {
  1377. continue;
  1378. }
  1379. Operand x = {};
  1380. x.mode = Addressing_Value;
  1381. x.type = t;
  1382. if (check_is_assignable_to(c, &x, type_hint)) {
  1383. e = proc;
  1384. add_entity_use(c, n, e);
  1385. skip = true;
  1386. break;
  1387. }
  1388. }
  1389. }
  1390. if (!skip) {
  1391. o->mode = Addressing_ProcGroup;
  1392. o->type = t_invalid;
  1393. o->proc_group = e;
  1394. return nullptr;
  1395. }
  1396. }
  1397. add_entity_use(c, n, e);
  1398. if (e->state == EntityState_Unresolved) {
  1399. check_entity_decl(c, e, nullptr, named_type);
  1400. }
  1401. if (e->type == nullptr) {
  1402. // TODO(bill): Which is correct? return or compiler_error?
  1403. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1404. return nullptr;
  1405. }
  1406. e->flags |= EntityFlag_Used;
  1407. Type *type = e->type;
  1408. o->type = type;
  1409. switch (e->kind) {
  1410. case Entity_Constant:
  1411. if (type == t_invalid) {
  1412. o->type = t_invalid;
  1413. return e;
  1414. }
  1415. o->value = e->Constant.value;
  1416. if (o->value.kind == ExactValue_Invalid) {
  1417. return e;
  1418. }
  1419. if (o->value.kind == ExactValue_Procedure) {
  1420. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1421. if (proc != nullptr) {
  1422. o->mode = Addressing_Value;
  1423. o->type = proc->type;
  1424. return proc;
  1425. }
  1426. }
  1427. o->mode = Addressing_Constant;
  1428. break;
  1429. case Entity_Variable:
  1430. e->flags |= EntityFlag_Used;
  1431. if (type == t_invalid) {
  1432. o->type = t_invalid;
  1433. return e;
  1434. }
  1435. o->mode = Addressing_Variable;
  1436. if (e->flags & EntityFlag_Value) {
  1437. o->mode = Addressing_Value;
  1438. }
  1439. break;
  1440. case Entity_Procedure:
  1441. o->mode = Addressing_Value;
  1442. o->value = exact_value_procedure(n);
  1443. break;
  1444. case Entity_Builtin:
  1445. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1446. o->mode = Addressing_Builtin;
  1447. break;
  1448. case Entity_TypeName:
  1449. o->mode = Addressing_Type;
  1450. if (check_cycle(c, e, true)) {
  1451. o->type = t_invalid;
  1452. }
  1453. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1454. o->type = base_type(o->type);
  1455. }
  1456. break;
  1457. case Entity_ImportName:
  1458. if (!allow_import_name) {
  1459. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1460. }
  1461. return e;
  1462. case Entity_LibraryName:
  1463. if (!allow_import_name) {
  1464. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1465. }
  1466. return e;
  1467. case Entity_Label:
  1468. o->mode = Addressing_NoValue;
  1469. break;
  1470. case Entity_Nil:
  1471. o->mode = Addressing_Value;
  1472. break;
  1473. default:
  1474. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1475. break;
  1476. }
  1477. return e;
  1478. }
  1479. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1480. if (o->type == nullptr) {
  1481. gbString str = expr_to_string(o->expr);
  1482. error(o->expr, "Expression has no value '%s'", str);
  1483. gb_string_free(str);
  1484. return false;
  1485. }
  1486. Type *type = base_type(core_array_type(o->type));
  1487. gbString str = nullptr;
  1488. switch (op.kind) {
  1489. case Token_Add:
  1490. case Token_Sub:
  1491. if (!is_type_numeric(type)) {
  1492. str = expr_to_string(o->expr);
  1493. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1494. gb_string_free(str);
  1495. }
  1496. break;
  1497. case Token_Xor:
  1498. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1499. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1500. }
  1501. break;
  1502. case Token_Not:
  1503. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1504. ERROR_BLOCK();
  1505. str = expr_to_string(o->expr);
  1506. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1507. gb_string_free(str);
  1508. if (is_type_integer(type)) {
  1509. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1510. }
  1511. } else {
  1512. o->type = t_untyped_bool;
  1513. }
  1514. break;
  1515. default:
  1516. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1517. return false;
  1518. }
  1519. return true;
  1520. }
  1521. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1522. Type *main_type = o->type;
  1523. Type *type = base_type(core_array_type(main_type));
  1524. Type *ct = core_type(type);
  1525. switch (op.kind) {
  1526. case Token_Sub:
  1527. case Token_SubEq:
  1528. if (is_type_bit_set(type)) {
  1529. return true;
  1530. } else if (!is_type_numeric(type)) {
  1531. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1532. return false;
  1533. }
  1534. break;
  1535. case Token_Quo:
  1536. case Token_QuoEq:
  1537. if (is_type_matrix(main_type)) {
  1538. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1539. return false;
  1540. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1541. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1542. return false;
  1543. }
  1544. /*fallthrough*/
  1545. case Token_Mul:
  1546. case Token_MulEq:
  1547. case Token_AddEq:
  1548. if (is_type_bit_set(type)) {
  1549. return true;
  1550. } else if (!is_type_numeric(type)) {
  1551. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1552. return false;
  1553. }
  1554. break;
  1555. case Token_Add:
  1556. if (is_type_string(type)) {
  1557. if (o->mode == Addressing_Constant) {
  1558. return true;
  1559. }
  1560. error(op, "String concatenation is only allowed with constant strings");
  1561. return false;
  1562. } else if (is_type_bit_set(type)) {
  1563. return true;
  1564. } else if (!is_type_numeric(type)) {
  1565. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1566. return false;
  1567. }
  1568. break;
  1569. case Token_And:
  1570. case Token_Or:
  1571. case Token_AndEq:
  1572. case Token_OrEq:
  1573. case Token_Xor:
  1574. case Token_XorEq:
  1575. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1576. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1577. return false;
  1578. }
  1579. break;
  1580. case Token_Mod:
  1581. case Token_ModMod:
  1582. case Token_ModEq:
  1583. case Token_ModModEq:
  1584. if (is_type_matrix(main_type)) {
  1585. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1586. return false;
  1587. }
  1588. if (!is_type_integer(type)) {
  1589. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1590. return false;
  1591. } else if (is_type_simd_vector(main_type)) {
  1592. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1593. return false;
  1594. }
  1595. break;
  1596. case Token_AndNot:
  1597. case Token_AndNotEq:
  1598. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1599. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1600. return false;
  1601. }
  1602. break;
  1603. case Token_CmpAnd:
  1604. case Token_CmpOr:
  1605. case Token_CmpAndEq:
  1606. case Token_CmpOrEq:
  1607. if (!is_type_boolean(type)) {
  1608. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1609. return false;
  1610. }
  1611. break;
  1612. default:
  1613. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1614. return false;
  1615. }
  1616. return true;
  1617. }
  1618. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1619. if (in_value.kind == ExactValue_Invalid) {
  1620. // NOTE(bill): There's already been an error
  1621. return true;
  1622. }
  1623. type = core_type(type);
  1624. if (type == t_invalid) {
  1625. return false;
  1626. } else if (is_type_boolean(type)) {
  1627. return in_value.kind == ExactValue_Bool;
  1628. } else if (is_type_string(type)) {
  1629. return in_value.kind == ExactValue_String;
  1630. } else if (is_type_integer(type) || is_type_rune(type)) {
  1631. if (in_value.kind == ExactValue_Bool) {
  1632. return false;
  1633. }
  1634. ExactValue v = exact_value_to_integer(in_value);
  1635. if (v.kind != ExactValue_Integer) {
  1636. return false;
  1637. }
  1638. if (out_value) *out_value = v;
  1639. if (is_type_untyped(type)) {
  1640. return true;
  1641. }
  1642. BigInt i = v.value_integer;
  1643. i64 bit_size = type_size_of(type);
  1644. BigInt umax = {};
  1645. BigInt imin = {};
  1646. BigInt imax = {};
  1647. if (bit_size < 16) {
  1648. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1649. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1650. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1651. } else {
  1652. big_int_from_u64(&umax, 1);
  1653. big_int_from_i64(&imin, 1);
  1654. big_int_from_i64(&imax, 1);
  1655. BigInt bi128 = {};
  1656. BigInt bi127 = {};
  1657. big_int_from_i64(&bi128, 128);
  1658. big_int_from_i64(&bi127, 127);
  1659. big_int_shl_eq(&umax, &bi128);
  1660. mp_decr(&umax);
  1661. big_int_shl_eq(&imin, &bi127);
  1662. big_int_neg(&imin, &imin);
  1663. big_int_shl_eq(&imax, &bi127);
  1664. mp_decr(&imax);
  1665. }
  1666. switch (type->Basic.kind) {
  1667. case Basic_rune:
  1668. case Basic_i8:
  1669. case Basic_i16:
  1670. case Basic_i32:
  1671. case Basic_i64:
  1672. case Basic_i128:
  1673. case Basic_int:
  1674. case Basic_i16le:
  1675. case Basic_i32le:
  1676. case Basic_i64le:
  1677. case Basic_i128le:
  1678. case Basic_i16be:
  1679. case Basic_i32be:
  1680. case Basic_i64be:
  1681. case Basic_i128be:
  1682. {
  1683. // return imin <= i && i <= imax;
  1684. int a = big_int_cmp(&imin, &i);
  1685. int b = big_int_cmp(&i, &imax);
  1686. return (a <= 0) && (b <= 0);
  1687. }
  1688. case Basic_u8:
  1689. case Basic_u16:
  1690. case Basic_u32:
  1691. case Basic_u64:
  1692. case Basic_u128:
  1693. case Basic_uint:
  1694. case Basic_uintptr:
  1695. case Basic_u16le:
  1696. case Basic_u32le:
  1697. case Basic_u64le:
  1698. case Basic_u128le:
  1699. case Basic_u16be:
  1700. case Basic_u32be:
  1701. case Basic_u64be:
  1702. case Basic_u128be:
  1703. {
  1704. // return 0ull <= i && i <= umax;
  1705. int b = big_int_cmp(&i, &umax);
  1706. return !i.sign && (b <= 0);
  1707. }
  1708. case Basic_UntypedInteger:
  1709. return true;
  1710. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1711. }
  1712. } else if (is_type_float(type)) {
  1713. ExactValue v = exact_value_to_float(in_value);
  1714. if (v.kind != ExactValue_Float) {
  1715. return false;
  1716. }
  1717. if (out_value) *out_value = v;
  1718. switch (type->Basic.kind) {
  1719. case Basic_f16:
  1720. case Basic_f32:
  1721. case Basic_f64:
  1722. return true;
  1723. case Basic_f16le:
  1724. case Basic_f16be:
  1725. case Basic_f32le:
  1726. case Basic_f32be:
  1727. case Basic_f64le:
  1728. case Basic_f64be:
  1729. return true;
  1730. case Basic_UntypedFloat:
  1731. return true;
  1732. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1733. }
  1734. } else if (is_type_complex(type)) {
  1735. ExactValue v = exact_value_to_complex(in_value);
  1736. if (v.kind != ExactValue_Complex) {
  1737. return false;
  1738. }
  1739. switch (type->Basic.kind) {
  1740. case Basic_complex32:
  1741. case Basic_complex64:
  1742. case Basic_complex128: {
  1743. ExactValue real = exact_value_real(v);
  1744. ExactValue imag = exact_value_imag(v);
  1745. if (real.kind != ExactValue_Invalid &&
  1746. imag.kind != ExactValue_Invalid) {
  1747. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1748. return true;
  1749. }
  1750. break;
  1751. }
  1752. case Basic_UntypedComplex:
  1753. return true;
  1754. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1755. }
  1756. return false;
  1757. } else if (is_type_quaternion(type)) {
  1758. ExactValue v = exact_value_to_quaternion(in_value);
  1759. if (v.kind != ExactValue_Quaternion) {
  1760. return false;
  1761. }
  1762. switch (type->Basic.kind) {
  1763. case Basic_quaternion64:
  1764. case Basic_quaternion128:
  1765. case Basic_quaternion256: {
  1766. ExactValue real = exact_value_real(v);
  1767. ExactValue imag = exact_value_imag(v);
  1768. ExactValue jmag = exact_value_jmag(v);
  1769. ExactValue kmag = exact_value_kmag(v);
  1770. if (real.kind != ExactValue_Invalid &&
  1771. imag.kind != ExactValue_Invalid) {
  1772. 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));
  1773. return true;
  1774. }
  1775. break;
  1776. }
  1777. case Basic_UntypedComplex:
  1778. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1779. return true;
  1780. case Basic_UntypedQuaternion:
  1781. return true;
  1782. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1783. }
  1784. return false;
  1785. } else if (is_type_pointer(type)) {
  1786. if (in_value.kind == ExactValue_Pointer) {
  1787. return true;
  1788. }
  1789. if (in_value.kind == ExactValue_Integer) {
  1790. return false;
  1791. // return true;
  1792. }
  1793. if (in_value.kind == ExactValue_String) {
  1794. return false;
  1795. }
  1796. if (out_value) *out_value = in_value;
  1797. } else if (is_type_bit_set(type)) {
  1798. if (in_value.kind == ExactValue_Integer) {
  1799. return true;
  1800. }
  1801. }
  1802. return false;
  1803. }
  1804. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1805. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1806. gbString b = type_to_string(type);
  1807. i64 sz = type_size_of(type);
  1808. BigInt *bi = &o->value.value_integer;
  1809. if (is_type_unsigned(type)) {
  1810. if (big_int_is_neg(bi)) {
  1811. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1812. } else {
  1813. BigInt one = big_int_make_u64(1);
  1814. BigInt max_size = big_int_make_u64(1);
  1815. BigInt bits = big_int_make_i64(8*sz);
  1816. big_int_shl_eq(&max_size, &bits);
  1817. big_int_sub_eq(&max_size, &one);
  1818. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1819. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1820. }
  1821. } else {
  1822. BigInt zero = big_int_make_u64(0);
  1823. BigInt one = big_int_make_u64(1);
  1824. BigInt max_size = big_int_make_u64(1);
  1825. BigInt bits = big_int_make_i64(8*sz - 1);
  1826. big_int_shl_eq(&max_size, &bits);
  1827. if (big_int_is_neg(bi)) {
  1828. big_int_neg(&max_size, &max_size);
  1829. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1830. error_line("\tThe minimum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1831. } else {
  1832. big_int_sub_eq(&max_size, &one);
  1833. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1834. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1835. }
  1836. }
  1837. gb_string_free(b);
  1838. return true;
  1839. }
  1840. return false;
  1841. }
  1842. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1843. gbString a = expr_to_string(o->expr);
  1844. gbString b = type_to_string(type);
  1845. defer(
  1846. gb_string_free(b);
  1847. gb_string_free(a);
  1848. );
  1849. Type *src = base_type(o->type);
  1850. Type *dst = base_type(type);
  1851. if (is_type_array(src) && is_type_slice(dst)) {
  1852. Type *s = src->Array.elem;
  1853. Type *d = dst->Slice.elem;
  1854. if (are_types_identical(s, d)) {
  1855. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1856. }
  1857. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1858. Type *s = src->DynamicArray.elem;
  1859. Type *d = dst->Slice.elem;
  1860. if (are_types_identical(s, d)) {
  1861. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1862. }
  1863. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1864. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1865. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1866. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1867. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1868. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1869. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1870. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1871. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1872. return;
  1873. }
  1874. }
  1875. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1876. gbString a = expr_to_string(o->expr);
  1877. gbString b = type_to_string(type);
  1878. defer(
  1879. gb_string_free(b);
  1880. gb_string_free(a);
  1881. );
  1882. Type *src = base_type(o->type);
  1883. Type *dst = base_type(type);
  1884. if (is_type_array(src) && is_type_slice(dst)) {
  1885. Type *s = src->Array.elem;
  1886. Type *d = dst->Slice.elem;
  1887. if (are_types_identical(s, d)) {
  1888. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1889. }
  1890. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1891. if (is_type_uintptr(type)) {
  1892. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1893. } else {
  1894. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1895. i64 x = type_size_of(o->type);
  1896. i64 y = type_size_of(type);
  1897. if (x != y) {
  1898. 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);
  1899. }
  1900. }
  1901. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  1902. if (is_type_uintptr(o->type)) {
  1903. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  1904. } else {
  1905. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  1906. }
  1907. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1908. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1909. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1910. return;
  1911. }
  1912. }
  1913. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  1914. GB_ASSERT(o->mode == Addressing_Constant);
  1915. ExactValue out_value = o->value;
  1916. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  1917. o->value = out_value;
  1918. return true;
  1919. } else {
  1920. o->value = out_value;
  1921. gbString a = expr_to_string(o->expr);
  1922. gbString b = type_to_string(type);
  1923. gbString c = type_to_string(o->type);
  1924. gbString s = exact_value_to_string(o->value);
  1925. defer(
  1926. gb_string_free(s);
  1927. gb_string_free(c);
  1928. gb_string_free(b);
  1929. gb_string_free(a);
  1930. o->mode = Addressing_Invalid;
  1931. );
  1932. ERROR_BLOCK();
  1933. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1934. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1935. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  1936. } else {
  1937. if (are_types_identical(o->type, type)) {
  1938. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  1939. } else {
  1940. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  1941. }
  1942. check_assignment_error_suggestion(ctx, o, type);
  1943. }
  1944. } else {
  1945. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  1946. check_assignment_error_suggestion(ctx, o, type);
  1947. }
  1948. return false;
  1949. }
  1950. }
  1951. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1952. if (o->mode == Addressing_OptionalOk) {
  1953. Ast *expr = unselector_expr(o->expr);
  1954. if (expr->kind != Ast_TypeAssertion) {
  1955. return true;
  1956. }
  1957. ast_node(ta, TypeAssertion, expr);
  1958. TypeAndValue tv = ta->expr->tav;
  1959. if (is_type_pointer(tv.type)) {
  1960. return false;
  1961. }
  1962. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1963. return false;
  1964. }
  1965. if (is_type_any(tv.type)) {
  1966. return false;
  1967. }
  1968. return true;
  1969. }
  1970. if (o->mode == Addressing_MapIndex) {
  1971. return false;
  1972. }
  1973. Ast *expr = unparen_expr(o->expr);
  1974. if (expr->kind == Ast_CompoundLit) {
  1975. return false;
  1976. }
  1977. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  1978. }
  1979. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  1980. if (!(build_context.strict_style || (check_vet_flags(expr) & VetFlag_Style))) {
  1981. return;
  1982. }
  1983. Entity *e = entity_of_node(expr);
  1984. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  1985. GB_ASSERT(e->kind == Entity_Variable);
  1986. begin_error_block();
  1987. defer (end_error_block());
  1988. if ((e->flags & EntityFlag_ForValue) != 0) {
  1989. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  1990. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  1991. if (is_type_map(parent_type)) {
  1992. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  1993. } else {
  1994. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  1995. }
  1996. } else {
  1997. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  1998. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  1999. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2000. }
  2001. }
  2002. }
  2003. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2004. switch (op.kind) {
  2005. case Token_And: { // Pointer address
  2006. if (check_is_not_addressable(c, o)) {
  2007. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2008. ast_node(ue, UnaryExpr, node);
  2009. gbString str = expr_to_string(ue->expr);
  2010. defer (gb_string_free(str));
  2011. Entity *e = entity_of_node(ue->expr);
  2012. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2013. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2014. } else {
  2015. switch (o->mode) {
  2016. case Addressing_Constant:
  2017. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2018. break;
  2019. case Addressing_SwizzleValue:
  2020. case Addressing_SwizzleVariable:
  2021. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2022. break;
  2023. default:
  2024. {
  2025. begin_error_block();
  2026. defer (end_error_block());
  2027. error(op, "Cannot take the pointer address of '%s'", str);
  2028. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2029. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2030. if (parent_type != nullptr && is_type_string(parent_type)) {
  2031. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2032. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2033. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2034. } else {
  2035. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2036. }
  2037. }
  2038. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2039. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2040. }
  2041. }
  2042. break;
  2043. }
  2044. }
  2045. }
  2046. o->mode = Addressing_Invalid;
  2047. return;
  2048. }
  2049. if (o->mode == Addressing_SoaVariable) {
  2050. ast_node(ue, UnaryExpr, node);
  2051. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2052. ast_node(ie, IndexExpr, ue->expr);
  2053. Type *soa_type = type_of_expr(ie->expr);
  2054. GB_ASSERT(is_type_soa_struct(soa_type));
  2055. o->type = alloc_type_soa_pointer(soa_type);
  2056. } else {
  2057. o->type = alloc_type_pointer(o->type);
  2058. }
  2059. } else {
  2060. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2061. ast_node(ue, UnaryExpr, node);
  2062. check_old_for_or_switch_value_usage(ue->expr);
  2063. }
  2064. o->type = alloc_type_pointer(o->type);
  2065. }
  2066. switch (o->mode) {
  2067. case Addressing_OptionalOk:
  2068. case Addressing_MapIndex:
  2069. o->mode = Addressing_OptionalOkPtr;
  2070. break;
  2071. default:
  2072. o->mode = Addressing_Value;
  2073. break;
  2074. }
  2075. return;
  2076. }
  2077. }
  2078. if (!check_unary_op(c, o, op)) {
  2079. o->mode = Addressing_Invalid;
  2080. return;
  2081. }
  2082. if (o->mode == Addressing_Constant) {
  2083. Type *type = base_type(o->type);
  2084. if (!is_type_constant_type(o->type)) {
  2085. gbString xt = type_to_string(o->type);
  2086. gbString err_str = expr_to_string(node);
  2087. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2088. gb_string_free(err_str);
  2089. gb_string_free(xt);
  2090. o->mode = Addressing_Invalid;
  2091. return;
  2092. }
  2093. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2094. gbString err_str = expr_to_string(node);
  2095. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2096. gb_string_free(err_str);
  2097. o->mode = Addressing_Invalid;
  2098. return;
  2099. }
  2100. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2101. gbString err_str = expr_to_string(node);
  2102. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2103. gb_string_free(err_str);
  2104. o->mode = Addressing_Invalid;
  2105. return;
  2106. }
  2107. i32 precision = 0;
  2108. if (is_type_typed(type)) {
  2109. precision = cast(i32)(8 * type_size_of(type));
  2110. }
  2111. bool is_unsigned = is_type_unsigned(type);
  2112. if (is_type_rune(type)) {
  2113. GB_ASSERT(!is_unsigned);
  2114. }
  2115. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2116. if (is_type_typed(type)) {
  2117. if (node != nullptr) {
  2118. o->expr = node;
  2119. }
  2120. check_is_expressible(c, o, type);
  2121. }
  2122. return;
  2123. }
  2124. o->mode = Addressing_Value;
  2125. }
  2126. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2127. if (t == nullptr) {
  2128. return;
  2129. }
  2130. t = base_type(t);
  2131. if (!is_type_comparable(t)) {
  2132. return;
  2133. }
  2134. switch (t->kind) {
  2135. case Type_Basic:
  2136. switch (t->Basic.kind) {
  2137. case Basic_complex32:
  2138. add_package_dependency(c, "runtime", "complex32_eq");
  2139. add_package_dependency(c, "runtime", "complex32_ne");
  2140. break;
  2141. case Basic_complex64:
  2142. add_package_dependency(c, "runtime", "complex64_eq");
  2143. add_package_dependency(c, "runtime", "complex64_ne");
  2144. break;
  2145. case Basic_complex128:
  2146. add_package_dependency(c, "runtime", "complex128_eq");
  2147. add_package_dependency(c, "runtime", "complex128_ne");
  2148. break;
  2149. case Basic_quaternion64:
  2150. add_package_dependency(c, "runtime", "quaternion64_eq");
  2151. add_package_dependency(c, "runtime", "quaternion64_ne");
  2152. break;
  2153. case Basic_quaternion128:
  2154. add_package_dependency(c, "runtime", "quaternion128_eq");
  2155. add_package_dependency(c, "runtime", "quaternion128_ne");
  2156. break;
  2157. case Basic_quaternion256:
  2158. add_package_dependency(c, "runtime", "quaternion256_eq");
  2159. add_package_dependency(c, "runtime", "quaternion256_ne");
  2160. break;
  2161. case Basic_cstring:
  2162. add_package_dependency(c, "runtime", "cstring_eq");
  2163. add_package_dependency(c, "runtime", "cstring_ne");
  2164. break;
  2165. case Basic_string:
  2166. add_package_dependency(c, "runtime", "string_eq");
  2167. add_package_dependency(c, "runtime", "string_ne");
  2168. break;
  2169. }
  2170. break;
  2171. case Type_Struct:
  2172. for (Entity *field : t->Struct.fields) {
  2173. add_comparison_procedures_for_fields(c, field->type);
  2174. }
  2175. break;
  2176. }
  2177. }
  2178. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2179. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2180. bool comp = are_types_identical(x->type, y->type);
  2181. switch (op) {
  2182. case Token_CmpEq: /* comp = comp; */ break;
  2183. case Token_NotEq: comp = !comp; break;
  2184. }
  2185. x->mode = Addressing_Constant;
  2186. x->type = t_untyped_bool;
  2187. x->value = exact_value_bool(comp);
  2188. return;
  2189. }
  2190. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2191. add_type_info_type(c, x->type);
  2192. add_type_info_type(c, y->type);
  2193. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2194. x->mode = Addressing_Value;
  2195. x->type = t_untyped_bool;
  2196. return;
  2197. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2198. add_type_info_type(c, x->type);
  2199. add_type_info_type(c, y->type);
  2200. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2201. x->mode = Addressing_Value;
  2202. x->type = t_untyped_bool;
  2203. return;
  2204. }
  2205. TEMPORARY_ALLOCATOR_GUARD();
  2206. gbString err_str = nullptr;
  2207. if (check_is_assignable_to(c, x, y->type) ||
  2208. check_is_assignable_to(c, y, x->type)) {
  2209. Type *err_type = x->type;
  2210. bool defined = false;
  2211. switch (op) {
  2212. case Token_CmpEq:
  2213. case Token_NotEq:
  2214. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2215. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2216. (is_operand_nil(*y) && type_has_nil(x->type));
  2217. break;
  2218. case Token_Lt:
  2219. case Token_Gt:
  2220. case Token_LtEq:
  2221. case Token_GtEq:
  2222. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2223. defined = true;
  2224. } else {
  2225. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2226. }
  2227. break;
  2228. }
  2229. if (!defined) {
  2230. gbString xs = type_to_string(x->type, temporary_allocator());
  2231. gbString ys = type_to_string(y->type, temporary_allocator());
  2232. err_str = gb_string_make(temporary_allocator(),
  2233. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2234. );
  2235. } else {
  2236. Type *comparison_type = x->type;
  2237. if (x->type == err_type && is_operand_nil(*x)) {
  2238. comparison_type = y->type;
  2239. }
  2240. add_comparison_procedures_for_fields(c, comparison_type);
  2241. }
  2242. } else {
  2243. gbString xt, yt;
  2244. if (x->mode == Addressing_ProcGroup) {
  2245. xt = gb_string_make(temporary_allocator(), "procedure group");
  2246. } else {
  2247. xt = type_to_string(x->type);
  2248. }
  2249. if (y->mode == Addressing_ProcGroup) {
  2250. yt = gb_string_make(temporary_allocator(), "procedure group");
  2251. } else {
  2252. yt = type_to_string(y->type);
  2253. }
  2254. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2255. }
  2256. if (err_str != nullptr) {
  2257. error(node, "Cannot compare expression, %s", err_str);
  2258. x->type = t_untyped_bool;
  2259. } else {
  2260. if (x->mode == Addressing_Constant &&
  2261. y->mode == Addressing_Constant) {
  2262. if (is_type_constant_type(x->type)) {
  2263. if (is_type_bit_set(x->type)) {
  2264. switch (op) {
  2265. case Token_CmpEq:
  2266. case Token_NotEq:
  2267. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2268. break;
  2269. case Token_Lt:
  2270. case Token_LtEq:
  2271. {
  2272. ExactValue lhs = x->value;
  2273. ExactValue rhs = y->value;
  2274. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2275. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2276. if (op == Token_Lt) {
  2277. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2278. }
  2279. x->value = res;
  2280. break;
  2281. }
  2282. case Token_Gt:
  2283. case Token_GtEq:
  2284. {
  2285. ExactValue lhs = x->value;
  2286. ExactValue rhs = y->value;
  2287. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2288. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2289. if (op == Token_Gt) {
  2290. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2291. }
  2292. x->value = res;
  2293. break;
  2294. }
  2295. }
  2296. } else {
  2297. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2298. }
  2299. } else {
  2300. x->mode = Addressing_Value;
  2301. }
  2302. } else {
  2303. x->mode = Addressing_Value;
  2304. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2305. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2306. i64 size = 0;
  2307. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2308. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2309. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2310. switch (op) {
  2311. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2312. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2313. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2314. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2315. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2316. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2317. }
  2318. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2319. switch (op) {
  2320. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2321. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2322. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2323. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2324. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2325. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2326. }
  2327. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2328. switch (op) {
  2329. case Token_CmpEq:
  2330. switch (8*size) {
  2331. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2332. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2333. }
  2334. break;
  2335. case Token_NotEq:
  2336. switch (8*size) {
  2337. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2338. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2339. }
  2340. break;
  2341. }
  2342. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2343. switch (op) {
  2344. case Token_CmpEq:
  2345. switch (8*size) {
  2346. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2347. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2348. }
  2349. break;
  2350. case Token_NotEq:
  2351. switch (8*size) {
  2352. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2353. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2354. }
  2355. break;
  2356. }
  2357. }
  2358. }
  2359. x->type = t_untyped_bool;
  2360. }
  2361. }
  2362. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2363. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2364. ast_node(be, BinaryExpr, node);
  2365. ExactValue x_val = {};
  2366. if (x->mode == Addressing_Constant) {
  2367. x_val = exact_value_to_integer(x->value);
  2368. }
  2369. bool x_is_untyped = is_type_untyped(x->type);
  2370. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2371. gbString err_str = expr_to_string(x->expr);
  2372. error(node, "Shifted operand '%s' must be an integer", err_str);
  2373. gb_string_free(err_str);
  2374. x->mode = Addressing_Invalid;
  2375. return;
  2376. }
  2377. if (is_type_unsigned(y->type)) {
  2378. } else if (is_type_untyped(y->type)) {
  2379. convert_to_typed(c, y, t_untyped_integer);
  2380. if (y->mode == Addressing_Invalid) {
  2381. x->mode = Addressing_Invalid;
  2382. return;
  2383. }
  2384. } else {
  2385. gbString err_str = expr_to_string(y->expr);
  2386. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2387. gb_string_free(err_str);
  2388. x->mode = Addressing_Invalid;
  2389. return;
  2390. }
  2391. if (x->mode == Addressing_Constant) {
  2392. if (y->mode == Addressing_Constant) {
  2393. ExactValue y_val = exact_value_to_integer(y->value);
  2394. if (y_val.kind != ExactValue_Integer) {
  2395. gbString err_str = expr_to_string(y->expr);
  2396. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2397. gb_string_free(err_str);
  2398. x->mode = Addressing_Invalid;
  2399. return;
  2400. }
  2401. BigInt max_shift = {};
  2402. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2403. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2404. gbString err_str = expr_to_string(y->expr);
  2405. error(node, "Shift amount too large: '%s'", err_str);
  2406. gb_string_free(err_str);
  2407. x->mode = Addressing_Invalid;
  2408. return;
  2409. }
  2410. if (!is_type_integer(x->type)) {
  2411. // NOTE(bill): It could be an untyped float but still representable
  2412. // as an integer
  2413. x->type = t_untyped_integer;
  2414. }
  2415. x->expr = node;
  2416. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2417. if (is_type_typed(x->type)) {
  2418. check_is_expressible(c, x, x->type);
  2419. }
  2420. return;
  2421. }
  2422. TokenPos pos = ast_token(x->expr).pos;
  2423. if (x_is_untyped) {
  2424. if (x->expr != nullptr) {
  2425. x->expr->tav.is_lhs = true;
  2426. }
  2427. x->mode = Addressing_Value;
  2428. if (type_hint) {
  2429. if (is_type_integer(type_hint)) {
  2430. x->type = type_hint;
  2431. } else {
  2432. gbString x_str = expr_to_string(x->expr);
  2433. gbString to_type = type_to_string(type_hint);
  2434. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2435. gb_string_free(x_str);
  2436. gb_string_free(to_type);
  2437. x->mode = Addressing_Invalid;
  2438. }
  2439. }
  2440. // x->value = x_val;
  2441. return;
  2442. }
  2443. }
  2444. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2445. gbString err_str = expr_to_string(y->expr);
  2446. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2447. gb_string_free(err_str);
  2448. }
  2449. if (!is_type_integer(x->type)) {
  2450. gbString err_str = expr_to_string(x->expr);
  2451. error(node, "Shift operand '%s' must be an integer", err_str);
  2452. gb_string_free(err_str);
  2453. x->mode = Addressing_Invalid;
  2454. return;
  2455. }
  2456. if (is_type_untyped(y->type)) {
  2457. convert_to_typed(c, y, t_uint);
  2458. }
  2459. x->mode = Addressing_Value;
  2460. }
  2461. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2462. if (check_is_assignable_to(c, operand, y)) {
  2463. return true;
  2464. }
  2465. bool is_constant = operand->mode == Addressing_Constant;
  2466. Type *x = operand->type;
  2467. Type *src = core_type(x);
  2468. Type *dst = core_type(y);
  2469. if (are_types_identical(src, dst)) {
  2470. return true;
  2471. }
  2472. // if (is_type_tuple(src)) {
  2473. // Ast *expr = unparen_expr(operand->expr);
  2474. // if (expr && expr->kind == Ast_CallExpr) {
  2475. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2476. // ast_node(ce, CallExpr, expr);
  2477. // Type *pt = base_type(type_of_expr(ce->proc));
  2478. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2479. // if (pt->Proc.result_count > 0) {
  2480. // Operand op = *operand;
  2481. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2482. // bool ok = check_is_castable_to(c, &op, y);
  2483. // if (ok) {
  2484. // ce->optional_ok_one = true;
  2485. // }
  2486. // return ok;
  2487. // }
  2488. // }
  2489. // }
  2490. // }
  2491. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2492. if (is_type_u8_array(dst)) {
  2493. String s = operand->value.value_string;
  2494. return s.len == dst->Array.count;
  2495. }
  2496. if (is_type_rune_array(dst)) {
  2497. String s = operand->value.value_string;
  2498. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2499. }
  2500. }
  2501. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2502. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2503. return dst->Array.count == src->Array.count;
  2504. }
  2505. }
  2506. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2507. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2508. }
  2509. // Cast between booleans and integers
  2510. if (is_type_boolean(src) || is_type_integer(src)) {
  2511. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2512. return true;
  2513. }
  2514. }
  2515. // Cast between numbers
  2516. if (is_type_integer(src) || is_type_float(src)) {
  2517. if (is_type_integer(dst) || is_type_float(dst)) {
  2518. return true;
  2519. }
  2520. }
  2521. if (is_type_integer(src) && is_type_rune(dst)) {
  2522. return true;
  2523. }
  2524. if (is_type_rune(src) && is_type_integer(dst)) {
  2525. return true;
  2526. }
  2527. if (is_type_complex(src) && is_type_complex(dst)) {
  2528. return true;
  2529. }
  2530. if (is_type_float(src) && is_type_complex(dst)) {
  2531. return true;
  2532. }
  2533. if (is_type_float(src) && is_type_quaternion(dst)) {
  2534. return true;
  2535. }
  2536. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2537. return true;
  2538. }
  2539. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2540. return true;
  2541. }
  2542. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2543. GB_ASSERT(src->kind == Type_Matrix);
  2544. GB_ASSERT(dst->kind == Type_Matrix);
  2545. Operand op = *operand;
  2546. op.type = src->Matrix.elem;
  2547. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2548. return false;
  2549. }
  2550. if (src->Matrix.row_count != src->Matrix.column_count) {
  2551. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2552. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2553. return src_count == dst_count;
  2554. }
  2555. return is_matrix_square(dst) && is_matrix_square(src);
  2556. }
  2557. // Cast between pointers
  2558. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2559. return true;
  2560. }
  2561. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2562. return true;
  2563. }
  2564. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2565. return true;
  2566. }
  2567. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2568. return true;
  2569. }
  2570. // uintptr <-> pointer
  2571. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2572. return true;
  2573. }
  2574. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2575. return true;
  2576. }
  2577. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2578. return true;
  2579. }
  2580. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2581. return true;
  2582. }
  2583. // []byte/[]u8 <-> string (not cstring)
  2584. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2585. return true;
  2586. }
  2587. // cstring -> string
  2588. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2589. if (operand->mode != Addressing_Constant) {
  2590. add_package_dependency(c, "runtime", "cstring_to_string");
  2591. }
  2592. return true;
  2593. }
  2594. // cstring -> ^u8
  2595. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2596. return !is_constant;
  2597. }
  2598. // cstring -> [^]u8
  2599. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2600. return !is_constant;
  2601. }
  2602. // cstring -> rawptr
  2603. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2604. return !is_constant;
  2605. }
  2606. // ^u8 -> cstring
  2607. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2608. return !is_constant;
  2609. }
  2610. // [^]u8 -> cstring
  2611. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2612. return !is_constant;
  2613. }
  2614. // rawptr -> cstring
  2615. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2616. return !is_constant;
  2617. }
  2618. // proc <-> proc
  2619. if (is_type_proc(src) && is_type_proc(dst)) {
  2620. return true;
  2621. }
  2622. // proc -> rawptr
  2623. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2624. return true;
  2625. }
  2626. // rawptr -> proc
  2627. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2628. return true;
  2629. }
  2630. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2631. if (src->SimdVector.count != dst->SimdVector.count) {
  2632. return false;
  2633. }
  2634. Type *elem_src = base_array_type(src);
  2635. Type *elem_dst = base_array_type(dst);
  2636. Operand x = {};
  2637. x.type = elem_src;
  2638. x.mode = Addressing_Value;
  2639. return check_is_castable_to(c, &x, elem_dst);
  2640. }
  2641. if (is_type_simd_vector(dst)) {
  2642. Type *elem = base_array_type(dst);
  2643. if (check_is_castable_to(c, operand, elem)) {
  2644. return true;
  2645. }
  2646. }
  2647. return false;
  2648. }
  2649. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2650. bool is_const_expr = x->mode == Addressing_Constant;
  2651. Type *bt = base_type(type);
  2652. if (is_const_expr && is_type_constant_type(bt)) {
  2653. if (core_type(bt)->kind == Type_Basic) {
  2654. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2655. return true;
  2656. } else if (check_is_castable_to(c, x, type)) {
  2657. if (is_type_pointer(type)) {
  2658. return true;
  2659. }
  2660. }
  2661. } else if (check_is_castable_to(c, x, type)) {
  2662. x->value = {};
  2663. x->mode = Addressing_Value;
  2664. return true;
  2665. }
  2666. } else if (check_is_castable_to(c, x, type)) {
  2667. if (x->mode != Addressing_Constant) {
  2668. x->mode = Addressing_Value;
  2669. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2670. x->mode = Addressing_Value;
  2671. } else if (is_type_union(type)) {
  2672. x->mode = Addressing_Value;
  2673. }
  2674. if (x->mode == Addressing_Value) {
  2675. x->value = {};
  2676. }
  2677. return true;
  2678. }
  2679. return false;
  2680. }
  2681. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2682. if (!is_operand_value(*x)) {
  2683. error(x->expr, "Only values can be casted");
  2684. x->mode = Addressing_Invalid;
  2685. return;
  2686. }
  2687. bool is_const_expr = x->mode == Addressing_Constant;
  2688. bool can_convert = check_cast_internal(c, x, type);
  2689. if (!can_convert) {
  2690. TEMPORARY_ALLOCATOR_GUARD();
  2691. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2692. gbString to_type = type_to_string(type, temporary_allocator());
  2693. gbString from_type = type_to_string(x->type, temporary_allocator());
  2694. x->mode = Addressing_Invalid;
  2695. begin_error_block();
  2696. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2697. if (is_const_expr) {
  2698. gbString val_str = exact_value_to_string(x->value);
  2699. if (is_type_float(x->type) && is_type_integer(type)) {
  2700. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2701. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2702. x->mode = Addressing_Constant;
  2703. x->type = type;
  2704. } else {
  2705. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2706. if (is_type_numeric(type)) {
  2707. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2708. x->mode = Addressing_Constant;
  2709. x->type = type;
  2710. }
  2711. }
  2712. gb_string_free(val_str);
  2713. }
  2714. check_cast_error_suggestion(c, x, type);
  2715. end_error_block();
  2716. return;
  2717. }
  2718. if (is_type_untyped(x->type)) {
  2719. Type *final_type = type;
  2720. if (is_const_expr && !is_type_constant_type(type)) {
  2721. final_type = default_type(x->type);
  2722. }
  2723. update_untyped_expr_type(c, x->expr, final_type, true);
  2724. }
  2725. if (check_vet_flags(x->expr) & VetFlag_Extra) {
  2726. if (are_types_identical(x->type, type)) {
  2727. gbString str = type_to_string(type);
  2728. warning(x->expr, "Unneeded cast to the same type '%s'", str);
  2729. gb_string_free(str);
  2730. }
  2731. }
  2732. x->type = type;
  2733. }
  2734. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2735. if (!is_operand_value(*o)) {
  2736. error(o->expr, "'transmute' can only be applied to values");
  2737. o->mode = Addressing_Invalid;
  2738. return false;
  2739. }
  2740. // if (o->mode == Addressing_Constant) {
  2741. // gbString expr_str = expr_to_string(o->expr);
  2742. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2743. // gb_string_free(expr_str);
  2744. // o->mode = Addressing_Invalid;
  2745. // o->expr = node;
  2746. // return false;
  2747. // }
  2748. Type *src_t = o->type;
  2749. Type *dst_t = t;
  2750. Type *src_bt = base_type(src_t);
  2751. Type *dst_bt = base_type(dst_t);
  2752. if (is_type_untyped(src_t)) {
  2753. gbString expr_str = expr_to_string(o->expr);
  2754. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2755. gb_string_free(expr_str);
  2756. o->mode = Addressing_Invalid;
  2757. o->expr = node;
  2758. return false;
  2759. }
  2760. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2761. GB_ASSERT(global_error_collector.count != 0);
  2762. o->mode = Addressing_Invalid;
  2763. o->expr = node;
  2764. return false;
  2765. }
  2766. if (src_bt == nullptr || src_bt == t_invalid) {
  2767. // NOTE(bill): this should be an error
  2768. GB_ASSERT(global_error_collector.count != 0);
  2769. o->mode = Addressing_Value;
  2770. o->expr = node;
  2771. o->type = dst_t;
  2772. return true;
  2773. }
  2774. i64 srcz = type_size_of(src_t);
  2775. i64 dstz = type_size_of(dst_t);
  2776. if (srcz != dstz) {
  2777. gbString expr_str = expr_to_string(o->expr);
  2778. gbString type_str = type_to_string(dst_t);
  2779. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2780. gb_string_free(type_str);
  2781. gb_string_free(expr_str);
  2782. o->mode = Addressing_Invalid;
  2783. o->expr = node;
  2784. return false;
  2785. }
  2786. if (check_vet_flags(node) & VetFlag_Extra) {
  2787. if (are_types_identical(o->type, dst_t)) {
  2788. gbString str = type_to_string(dst_t);
  2789. warning(o->expr, "Unneeded transmute to the same type '%s'", str);
  2790. gb_string_free(str);
  2791. }
  2792. }
  2793. o->expr = node;
  2794. o->type = dst_t;
  2795. if (o->mode == Addressing_Constant) {
  2796. if (are_types_identical(src_bt, dst_bt)) {
  2797. return true;
  2798. }
  2799. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2800. if (types_have_same_internal_endian(src_t, dst_t)) {
  2801. ExactValue src_v = exact_value_to_integer(o->value);
  2802. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2803. BigInt v = src_v.value_integer;
  2804. BigInt smax = {};
  2805. BigInt umax = {};
  2806. big_int_from_u64(&smax, 0);
  2807. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2808. big_int_from_u64(&umax, 1);
  2809. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2810. big_int_shl_eq(&umax, &sz_in_bits);
  2811. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2812. if (big_int_cmp(&v, &smax) >= 0) {
  2813. big_int_sub_eq(&v, &umax);
  2814. }
  2815. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2816. if (big_int_is_neg(&v)) {
  2817. big_int_add_eq(&v, &umax);
  2818. }
  2819. }
  2820. o->value.kind = ExactValue_Integer;
  2821. o->value.value_integer = v;
  2822. return true;
  2823. }
  2824. }
  2825. }
  2826. o->mode = Addressing_Value;
  2827. o->value = {};
  2828. return true;
  2829. }
  2830. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2831. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2832. if (check_is_assignable_to(c, y, x->type)) {
  2833. if (check_binary_op(c, x, op)) {
  2834. return true;
  2835. }
  2836. }
  2837. }
  2838. return false;
  2839. }
  2840. gb_internal bool is_ise_expr(Ast *node) {
  2841. node = unparen_expr(node);
  2842. return node->kind == Ast_ImplicitSelectorExpr;
  2843. }
  2844. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2845. if (use_lhs_as_type_hint) { // RHS in this case
  2846. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2847. }
  2848. return false;
  2849. }
  2850. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2851. Type *xt = base_type(matrix);
  2852. if (type_hint != nullptr) {
  2853. Type *th = base_type(type_hint);
  2854. if (are_types_identical(th, xt)) {
  2855. return type_hint;
  2856. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2857. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2858. // ignore
  2859. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2860. return type_hint;
  2861. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2862. return type_hint;
  2863. }
  2864. }
  2865. }
  2866. return matrix;
  2867. }
  2868. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2869. if (!check_binary_op(c, x, op)) {
  2870. x->mode = Addressing_Invalid;
  2871. return;
  2872. }
  2873. Type *xt = base_type(x->type);
  2874. Type *yt = base_type(y->type);
  2875. if (is_type_matrix(x->type)) {
  2876. GB_ASSERT(xt->kind == Type_Matrix);
  2877. if (op.kind == Token_Mul) {
  2878. if (yt->kind == Type_Matrix) {
  2879. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2880. goto matrix_error;
  2881. }
  2882. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2883. goto matrix_error;
  2884. }
  2885. x->mode = Addressing_Value;
  2886. if (are_types_identical(xt, yt)) {
  2887. if (!is_type_named(x->type) && is_type_named(y->type)) {
  2888. // prefer the named type
  2889. x->type = y->type;
  2890. }
  2891. } else {
  2892. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2893. }
  2894. goto matrix_success;
  2895. } else if (yt->kind == Type_Array) {
  2896. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2897. goto matrix_error;
  2898. }
  2899. if (xt->Matrix.column_count != yt->Array.count) {
  2900. goto matrix_error;
  2901. }
  2902. // Treat arrays as column vectors
  2903. x->mode = Addressing_Value;
  2904. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2905. x->type = y->type;
  2906. } else {
  2907. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2908. }
  2909. goto matrix_success;
  2910. }
  2911. }
  2912. if (!are_types_identical(xt, yt)) {
  2913. goto matrix_error;
  2914. }
  2915. x->mode = Addressing_Value;
  2916. x->type = xt;
  2917. goto matrix_success;
  2918. } else {
  2919. GB_ASSERT(!is_type_matrix(xt));
  2920. GB_ASSERT(is_type_matrix(yt));
  2921. if (op.kind == Token_Mul) {
  2922. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2923. if (xt->kind == Type_Array) {
  2924. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2925. goto matrix_error;
  2926. }
  2927. if (xt->Array.count != yt->Matrix.row_count) {
  2928. goto matrix_error;
  2929. }
  2930. // Treat arrays as row vectors
  2931. x->mode = Addressing_Value;
  2932. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2933. x->type = x->type;
  2934. } else {
  2935. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2936. }
  2937. goto matrix_success;
  2938. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  2939. x->type = check_matrix_type_hint(y->type, type_hint);
  2940. return;
  2941. }
  2942. }
  2943. if (!are_types_identical(xt, yt)) {
  2944. goto matrix_error;
  2945. }
  2946. x->mode = Addressing_Value;
  2947. x->type = xt;
  2948. goto matrix_success;
  2949. }
  2950. matrix_success:
  2951. x->type = check_matrix_type_hint(x->type, type_hint);
  2952. return;
  2953. matrix_error:
  2954. gbString xts = type_to_string(x->type);
  2955. gbString yts = type_to_string(y->type);
  2956. gbString expr_str = expr_to_string(x->expr);
  2957. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2958. gb_string_free(expr_str);
  2959. gb_string_free(yts);
  2960. gb_string_free(xts);
  2961. x->type = t_invalid;
  2962. x->mode = Addressing_Invalid;
  2963. return;
  2964. }
  2965. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2966. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2967. Operand y_ = {}, *y = &y_;
  2968. ast_node(be, BinaryExpr, node);
  2969. defer({
  2970. node->viral_state_flags |= be->left->viral_state_flags;
  2971. node->viral_state_flags |= be->right->viral_state_flags;
  2972. });
  2973. Token op = be->op;
  2974. switch (op.kind) {
  2975. case Token_CmpEq:
  2976. case Token_NotEq: {
  2977. // NOTE(bill): Allow comparisons between types
  2978. if (is_ise_expr(be->left)) {
  2979. // Evalute the right before the left for an '.X' expression
  2980. check_expr_or_type(c, y, be->right, type_hint);
  2981. check_expr_or_type(c, x, be->left, y->type);
  2982. } else {
  2983. check_expr_or_type(c, x, be->left, type_hint);
  2984. check_expr_or_type(c, y, be->right, x->type);
  2985. }
  2986. bool xt = x->mode == Addressing_Type;
  2987. bool yt = y->mode == Addressing_Type;
  2988. // If only one is a type, this is an error
  2989. if (xt ^ yt) {
  2990. GB_ASSERT(xt != yt);
  2991. if (xt) {
  2992. if (!is_type_typeid(y->type)) {
  2993. error_operand_not_expression(x);
  2994. }
  2995. }
  2996. if (yt) {
  2997. if (!is_type_typeid(x->type)) {
  2998. error_operand_not_expression(y);
  2999. }
  3000. }
  3001. }
  3002. break;
  3003. }
  3004. case Token_in:
  3005. case Token_not_in:
  3006. {
  3007. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3008. check_expr(c, y, be->right);
  3009. Type *rhs_type = type_deref(y->type);
  3010. if (is_type_bit_set(rhs_type)) {
  3011. Type *elem = base_type(rhs_type)->BitSet.elem;
  3012. check_expr_with_type_hint(c, x, be->left, elem);
  3013. } else if (is_type_map(rhs_type)) {
  3014. Type *key = base_type(rhs_type)->Map.key;
  3015. check_expr_with_type_hint(c, x, be->left, key);
  3016. } else {
  3017. check_expr(c, x, be->left);
  3018. }
  3019. if (x->mode == Addressing_Invalid) {
  3020. return;
  3021. }
  3022. if (y->mode == Addressing_Invalid) {
  3023. x->mode = Addressing_Invalid;
  3024. x->expr = y->expr;
  3025. return;
  3026. }
  3027. if (is_type_map(rhs_type)) {
  3028. Type *yt = base_type(rhs_type);
  3029. if (op.kind == Token_in) {
  3030. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3031. } else {
  3032. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3033. }
  3034. add_map_get_dependencies(c);
  3035. } else if (is_type_bit_set(rhs_type)) {
  3036. Type *yt = base_type(rhs_type);
  3037. if (op.kind == Token_in) {
  3038. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3039. } else {
  3040. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3041. }
  3042. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3043. ExactValue k = exact_value_to_integer(x->value);
  3044. ExactValue v = exact_value_to_integer(y->value);
  3045. GB_ASSERT(k.kind == ExactValue_Integer);
  3046. GB_ASSERT(v.kind == ExactValue_Integer);
  3047. i64 key = big_int_to_i64(&k.value_integer);
  3048. i64 lower = yt->BitSet.lower;
  3049. i64 upper = yt->BitSet.upper;
  3050. if (lower <= key && key <= upper) {
  3051. i64 bit = 1ll<<key;
  3052. i64 bits = big_int_to_i64(&v.value_integer);
  3053. x->mode = Addressing_Constant;
  3054. x->type = t_untyped_bool;
  3055. if (op.kind == Token_in) {
  3056. x->value = exact_value_bool((bit & bits) != 0);
  3057. } else {
  3058. x->value = exact_value_bool((bit & bits) == 0);
  3059. }
  3060. x->expr = node;
  3061. return;
  3062. } else {
  3063. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3064. x->mode = Addressing_Invalid;
  3065. }
  3066. }
  3067. } else {
  3068. gbString t = type_to_string(y->type);
  3069. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3070. gb_string_free(t);
  3071. x->expr = node;
  3072. x->mode = Addressing_Invalid;
  3073. return;
  3074. }
  3075. if (x->mode != Addressing_Invalid) {
  3076. x->mode = Addressing_Value;
  3077. x->type = t_untyped_bool;
  3078. }
  3079. x->expr = node;
  3080. return;
  3081. }
  3082. default:
  3083. if (is_ise_expr(be->left)) {
  3084. // Evalute the right before the left for an '.X' expression
  3085. check_expr_or_type(c, y, be->right, type_hint);
  3086. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3087. check_expr_or_type(c, x, be->left, y->type);
  3088. } else {
  3089. check_expr_with_type_hint(c, x, be->left, type_hint);
  3090. }
  3091. } else {
  3092. check_expr_with_type_hint(c, x, be->left, type_hint);
  3093. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3094. check_expr_with_type_hint(c, y, be->right, x->type);
  3095. } else {
  3096. check_expr_with_type_hint(c, y, be->right, type_hint);
  3097. }
  3098. }
  3099. break;
  3100. }
  3101. if (x->mode == Addressing_Invalid) {
  3102. return;
  3103. }
  3104. if (y->mode == Addressing_Invalid) {
  3105. x->mode = Addressing_Invalid;
  3106. x->expr = y->expr;
  3107. return;
  3108. }
  3109. if (x->mode == Addressing_Builtin) {
  3110. x->mode = Addressing_Invalid;
  3111. error(x->expr, "built-in expression in binary expression");
  3112. return;
  3113. }
  3114. if (y->mode == Addressing_Builtin) {
  3115. x->mode = Addressing_Invalid;
  3116. error(y->expr, "built-in expression in binary expression");
  3117. return;
  3118. }
  3119. if (x->mode == Addressing_ProcGroup) {
  3120. x->mode = Addressing_Invalid;
  3121. if (x->proc_group != nullptr) {
  3122. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3123. } else {
  3124. error(x->expr, "procedure group used in binary expression");
  3125. }
  3126. return;
  3127. }
  3128. if (y->mode == Addressing_ProcGroup) {
  3129. x->mode = Addressing_Invalid;
  3130. if (x->proc_group != nullptr) {
  3131. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3132. } else {
  3133. error(y->expr, "procedure group used in binary expression");
  3134. }
  3135. return;
  3136. }
  3137. if (token_is_shift(op.kind)) {
  3138. check_shift(c, x, y, node, type_hint);
  3139. return;
  3140. }
  3141. convert_to_typed(c, x, y->type);
  3142. if (x->mode == Addressing_Invalid) {
  3143. return;
  3144. }
  3145. convert_to_typed(c, y, x->type);
  3146. if (y->mode == Addressing_Invalid) {
  3147. x->mode = Addressing_Invalid;
  3148. return;
  3149. }
  3150. if (token_is_comparison(op.kind)) {
  3151. check_comparison(c, node, x, y, op.kind);
  3152. return;
  3153. }
  3154. if (check_binary_array_expr(c, op, x, y)) {
  3155. x->mode = Addressing_Value;
  3156. x->type = x->type;
  3157. return;
  3158. }
  3159. if (check_binary_array_expr(c, op, y, x)) {
  3160. x->mode = Addressing_Value;
  3161. x->type = y->type;
  3162. return;
  3163. }
  3164. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3165. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3166. x->expr = node;
  3167. return;
  3168. }
  3169. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3170. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3171. // NOTE(bill, 2022-06-26)
  3172. // Allow any boolean types within `&&` and `||`
  3173. // This is an exception to all other binary expressions since the result
  3174. // of a comparison will always be an untyped boolean, and allowing
  3175. // any boolean between these two simplifies a lot of expressions
  3176. } else if (!are_types_identical(x->type, y->type)) {
  3177. if (x->type != t_invalid &&
  3178. y->type != t_invalid) {
  3179. gbString xt = type_to_string(x->type);
  3180. gbString yt = type_to_string(y->type);
  3181. gbString expr_str = expr_to_string(node);
  3182. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3183. gb_string_free(expr_str);
  3184. gb_string_free(yt);
  3185. gb_string_free(xt);
  3186. }
  3187. x->mode = Addressing_Invalid;
  3188. return;
  3189. }
  3190. if (!check_binary_op(c, x, op)) {
  3191. x->mode = Addressing_Invalid;
  3192. return;
  3193. }
  3194. switch (op.kind) {
  3195. case Token_Quo:
  3196. case Token_Mod:
  3197. case Token_ModMod:
  3198. case Token_QuoEq:
  3199. case Token_ModEq:
  3200. case Token_ModModEq:
  3201. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3202. y->mode == Addressing_Constant) {
  3203. bool fail = false;
  3204. switch (y->value.kind) {
  3205. case ExactValue_Integer:
  3206. if (big_int_is_zero(&y->value.value_integer)) {
  3207. fail = true;
  3208. }
  3209. break;
  3210. case ExactValue_Float:
  3211. if (y->value.value_float == 0.0) {
  3212. fail = true;
  3213. }
  3214. break;
  3215. }
  3216. if (fail) {
  3217. error(y->expr, "Division by zero not allowed");
  3218. x->mode = Addressing_Invalid;
  3219. return;
  3220. }
  3221. }
  3222. break;
  3223. case Token_CmpAnd:
  3224. case Token_CmpOr:
  3225. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3226. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3227. }
  3228. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3229. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3230. }
  3231. break;
  3232. }
  3233. if (x->mode == Addressing_Constant &&
  3234. y->mode == Addressing_Constant) {
  3235. ExactValue a = x->value;
  3236. ExactValue b = y->value;
  3237. if (!is_type_constant_type(x->type)) {
  3238. x->mode = Addressing_Value;
  3239. return;
  3240. }
  3241. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3242. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3243. }
  3244. if (is_type_bit_set(x->type)) {
  3245. switch (op.kind) {
  3246. case Token_Add: op.kind = Token_Or; break;
  3247. case Token_Sub: op.kind = Token_AndNot; break;
  3248. }
  3249. }
  3250. x->value = exact_binary_operator_value(op.kind, a, b);
  3251. if (is_type_typed(x->type)) {
  3252. if (node != nullptr) {
  3253. x->expr = node;
  3254. }
  3255. check_is_expressible(c, x, x->type);
  3256. }
  3257. return;
  3258. } else if (is_type_string(x->type)) {
  3259. error(node, "String concatenation is only allowed with constant strings");
  3260. x->mode = Addressing_Invalid;
  3261. return;
  3262. }
  3263. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3264. Type *bt = base_type(x->type);
  3265. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3266. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3267. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3268. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3269. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3270. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3271. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3272. }
  3273. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3274. Type *bt = base_type(x->type);
  3275. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3276. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3277. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3278. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3279. }
  3280. }
  3281. x->mode = Addressing_Value;
  3282. }
  3283. gb_internal Operand make_operand_from_node(Ast *node) {
  3284. GB_ASSERT(node != nullptr);
  3285. Operand x = {};
  3286. x.expr = node;
  3287. x.mode = node->tav.mode;
  3288. x.type = node->tav.type;
  3289. x.value = node->tav.value;
  3290. return x;
  3291. }
  3292. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3293. GB_ASSERT(e != nullptr);
  3294. ExprInfo *old = check_get_expr_info(c, e);
  3295. if (old == nullptr) {
  3296. if (type != nullptr && type != t_invalid) {
  3297. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3298. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3299. if (e->kind == Ast_TernaryIfExpr) {
  3300. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3301. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3302. }
  3303. }
  3304. }
  3305. return;
  3306. }
  3307. switch (e->kind) {
  3308. case_ast_node(ue, UnaryExpr, e);
  3309. if (old->value.kind != ExactValue_Invalid) {
  3310. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3311. // They don't need to be updated as they will be updated later and
  3312. // checked at the end of general checking stage.
  3313. break;
  3314. }
  3315. update_untyped_expr_type(c, ue->expr, type, final);
  3316. case_end;
  3317. case_ast_node(be, BinaryExpr, e);
  3318. if (old->value.kind != ExactValue_Invalid) {
  3319. // See above note in UnaryExpr case
  3320. break;
  3321. }
  3322. if (token_is_comparison(be->op.kind)) {
  3323. // NOTE(bill): Do nothing as the types are fine
  3324. } else if (token_is_shift(be->op.kind)) {
  3325. update_untyped_expr_type(c, be->left, type, final);
  3326. } else {
  3327. update_untyped_expr_type(c, be->left, type, final);
  3328. update_untyped_expr_type(c, be->right, type, final);
  3329. }
  3330. case_end;
  3331. case_ast_node(te, TernaryIfExpr, e);
  3332. if (old->value.kind != ExactValue_Invalid) {
  3333. // See above note in UnaryExpr case
  3334. break;
  3335. }
  3336. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3337. // having an untyped value
  3338. Operand x = make_operand_from_node(te->x);
  3339. Operand y = make_operand_from_node(te->y);
  3340. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3341. update_untyped_expr_type(c, te->x, type, final);
  3342. }
  3343. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3344. update_untyped_expr_type(c, te->y, type, final);
  3345. }
  3346. case_end;
  3347. case_ast_node(te, TernaryWhenExpr, e);
  3348. if (old->value.kind != ExactValue_Invalid) {
  3349. // See above note in UnaryExpr case
  3350. break;
  3351. }
  3352. update_untyped_expr_type(c, te->x, type, final);
  3353. update_untyped_expr_type(c, te->y, type, final);
  3354. case_end;
  3355. case_ast_node(ore, OrReturnExpr, e);
  3356. if (old->value.kind != ExactValue_Invalid) {
  3357. // See above note in UnaryExpr case
  3358. break;
  3359. }
  3360. update_untyped_expr_type(c, ore->expr, type, final);
  3361. case_end;
  3362. case_ast_node(oee, OrElseExpr, e);
  3363. if (old->value.kind != ExactValue_Invalid) {
  3364. // See above note in UnaryExpr case
  3365. break;
  3366. }
  3367. update_untyped_expr_type(c, oee->x, type, final);
  3368. update_untyped_expr_type(c, oee->y, type, final);
  3369. case_end;
  3370. case_ast_node(pe, ParenExpr, e);
  3371. update_untyped_expr_type(c, pe->expr, type, final);
  3372. case_end;
  3373. }
  3374. if (!final && is_type_untyped(type)) {
  3375. old->type = base_type(type);
  3376. return;
  3377. }
  3378. // We need to remove it and then give it a new one
  3379. check_remove_expr_info(c, e);
  3380. if (old->is_lhs && !is_type_integer(type)) {
  3381. gbString expr_str = expr_to_string(e);
  3382. gbString type_str = type_to_string(type);
  3383. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3384. gb_string_free(type_str);
  3385. gb_string_free(expr_str);
  3386. return;
  3387. }
  3388. add_type_and_value(c, e, old->mode, type, old->value);
  3389. }
  3390. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3391. GB_ASSERT(e != nullptr);
  3392. ExprInfo *found = check_get_expr_info(c, e);
  3393. if (found) {
  3394. found->value = value;
  3395. }
  3396. }
  3397. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3398. gbString expr_str = expr_to_string(operand->expr);
  3399. gbString type_str = type_to_string(target_type);
  3400. gbString from_type_str = type_to_string(operand->type);
  3401. char const *extra_text = "";
  3402. if (operand->mode == Addressing_Constant) {
  3403. if (big_int_is_zero(&operand->value.value_integer)) {
  3404. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3405. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3406. extra_text = " - Did you want 'nil'?";
  3407. }
  3408. }
  3409. }
  3410. ERROR_BLOCK();
  3411. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3412. if (operand->value.kind == ExactValue_String) {
  3413. String key = operand->value.value_string;
  3414. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3415. Type *et = base_type(target_type);
  3416. check_did_you_mean_type(key, et->Enum.fields, ".");
  3417. }
  3418. }
  3419. gb_string_free(from_type_str);
  3420. gb_string_free(type_str);
  3421. gb_string_free(expr_str);
  3422. operand->mode = Addressing_Invalid;
  3423. }
  3424. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3425. Type *t = core_type(type);
  3426. if (is_type_boolean(t)) {
  3427. // v = exact_value_to_boolean(v);
  3428. } else if (is_type_float(t)) {
  3429. v = exact_value_to_float(v);
  3430. } else if (is_type_integer(t)) {
  3431. v = exact_value_to_integer(v);
  3432. } else if (is_type_pointer(t)) {
  3433. v = exact_value_to_integer(v);
  3434. } else if (is_type_complex(t)) {
  3435. v = exact_value_to_complex(v);
  3436. } else if (is_type_quaternion(t)) {
  3437. v = exact_value_to_quaternion(v);
  3438. }
  3439. return v;
  3440. }
  3441. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3442. GB_ASSERT_NOT_NULL(target_type);
  3443. if (operand->mode == Addressing_Invalid ||
  3444. operand->mode == Addressing_Type ||
  3445. is_type_typed(operand->type) ||
  3446. target_type == t_invalid) {
  3447. return;
  3448. }
  3449. if (is_type_untyped(target_type)) {
  3450. GB_ASSERT(operand->type->kind == Type_Basic);
  3451. GB_ASSERT(target_type->kind == Type_Basic);
  3452. BasicKind x_kind = operand->type->Basic.kind;
  3453. BasicKind y_kind = target_type->Basic.kind;
  3454. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3455. if (x_kind < y_kind) {
  3456. operand->type = target_type;
  3457. update_untyped_expr_type(c, operand->expr, target_type, false);
  3458. }
  3459. } else if (x_kind != y_kind) {
  3460. operand->mode = Addressing_Invalid;
  3461. convert_untyped_error(c, operand, target_type);
  3462. return;
  3463. }
  3464. return;
  3465. }
  3466. Type *t = base_type(target_type);
  3467. if (c->in_enum_type) {
  3468. t = core_type(target_type);
  3469. }
  3470. switch (t->kind) {
  3471. case Type_Basic:
  3472. if (operand->mode == Addressing_Constant) {
  3473. check_is_expressible(c, operand, t);
  3474. if (operand->mode == Addressing_Invalid) {
  3475. return;
  3476. }
  3477. update_untyped_expr_value(c, operand->expr, operand->value);
  3478. } else {
  3479. switch (operand->type->Basic.kind) {
  3480. case Basic_UntypedBool:
  3481. if (!is_type_boolean(target_type)) {
  3482. operand->mode = Addressing_Invalid;
  3483. convert_untyped_error(c, operand, target_type);
  3484. return;
  3485. }
  3486. break;
  3487. case Basic_UntypedInteger:
  3488. case Basic_UntypedFloat:
  3489. case Basic_UntypedComplex:
  3490. case Basic_UntypedQuaternion:
  3491. case Basic_UntypedRune:
  3492. if (!is_type_numeric(target_type)) {
  3493. operand->mode = Addressing_Invalid;
  3494. convert_untyped_error(c, operand, target_type);
  3495. return;
  3496. }
  3497. break;
  3498. case Basic_UntypedNil:
  3499. if (is_type_any(target_type)) {
  3500. // target_type = t_untyped_nil;
  3501. } else if (is_type_cstring(target_type)) {
  3502. // target_type = t_untyped_nil;
  3503. } else if (!type_has_nil(target_type)) {
  3504. operand->mode = Addressing_Invalid;
  3505. convert_untyped_error(c, operand, target_type);
  3506. return;
  3507. }
  3508. break;
  3509. }
  3510. }
  3511. break;
  3512. case Type_Array: {
  3513. Type *elem = base_array_type(t);
  3514. if (check_is_assignable_to(c, operand, elem)) {
  3515. operand->mode = Addressing_Value;
  3516. } else {
  3517. if (operand->value.kind == ExactValue_String) {
  3518. String s = operand->value.value_string;
  3519. if (is_type_u8_array(t)) {
  3520. if (s.len == t->Array.count) {
  3521. break;
  3522. }
  3523. } else if (is_type_rune_array(t)) {
  3524. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3525. if (rune_count == t->Array.count) {
  3526. break;
  3527. }
  3528. }
  3529. }
  3530. operand->mode = Addressing_Invalid;
  3531. convert_untyped_error(c, operand, target_type);
  3532. return;
  3533. }
  3534. break;
  3535. }
  3536. case Type_Matrix: {
  3537. Type *elem = base_array_type(t);
  3538. if (check_is_assignable_to(c, operand, elem)) {
  3539. if (t->Matrix.row_count != t->Matrix.column_count) {
  3540. operand->mode = Addressing_Invalid;
  3541. begin_error_block();
  3542. defer (end_error_block());
  3543. convert_untyped_error(c, operand, target_type);
  3544. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3545. return;
  3546. } else {
  3547. operand->mode = Addressing_Value;
  3548. }
  3549. } else {
  3550. operand->mode = Addressing_Invalid;
  3551. convert_untyped_error(c, operand, target_type);
  3552. return;
  3553. }
  3554. break;
  3555. }
  3556. case Type_Union:
  3557. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3558. TEMPORARY_ALLOCATOR_GUARD();
  3559. isize count = t->Union.variants.count;
  3560. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3561. isize valid_count = 0;
  3562. isize first_success_index = -1;
  3563. for_array(i, t->Union.variants) {
  3564. Type *vt = t->Union.variants[i];
  3565. i64 score = 0;
  3566. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3567. valids[valid_count].index = i;
  3568. valids[valid_count].score = score;
  3569. valid_count += 1;
  3570. if (first_success_index < 0) {
  3571. first_success_index = i;
  3572. }
  3573. }
  3574. }
  3575. if (valid_count > 1) {
  3576. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3577. i64 best_score = valids[0].score;
  3578. for (isize i = 1; i < valid_count; i++) {
  3579. auto v = valids[i];
  3580. if (best_score > v.score) {
  3581. valid_count = i;
  3582. break;
  3583. }
  3584. best_score = v.score;
  3585. }
  3586. first_success_index = valids[0].index;
  3587. }
  3588. gbString type_str = type_to_string(target_type);
  3589. defer (gb_string_free(type_str));
  3590. if (valid_count == 1) {
  3591. operand->mode = Addressing_Value;
  3592. operand->type = t->Union.variants[first_success_index];
  3593. target_type = t->Union.variants[first_success_index];
  3594. break;
  3595. } else if (valid_count > 1) {
  3596. begin_error_block();
  3597. defer (end_error_block());
  3598. GB_ASSERT(first_success_index >= 0);
  3599. operand->mode = Addressing_Invalid;
  3600. convert_untyped_error(c, operand, target_type);
  3601. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3602. i32 j = 0;
  3603. for (i32 i = 0; i < valid_count; i++) {
  3604. ValidIndexAndScore valid = valids[i];
  3605. if (j > 0 && valid_count > 2) error_line(", ");
  3606. if (j == valid_count-1) {
  3607. if (valid_count == 2) error_line(" ");
  3608. error_line("or ");
  3609. }
  3610. gbString str = type_to_string(t->Union.variants[valid.index]);
  3611. error_line("'%s'", str);
  3612. gb_string_free(str);
  3613. j++;
  3614. }
  3615. error_line("\n\n");
  3616. return;
  3617. } else if (is_type_untyped_uninit(operand->type)) {
  3618. target_type = t_untyped_uninit;
  3619. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3620. begin_error_block();
  3621. defer (end_error_block());
  3622. operand->mode = Addressing_Invalid;
  3623. convert_untyped_error(c, operand, target_type);
  3624. if (count > 0) {
  3625. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3626. error_line("\t");
  3627. for (i32 i = 0; i < count; i++) {
  3628. Type *v = t->Union.variants[i];
  3629. if (i > 0 && count > 2) error_line(", ");
  3630. if (i == count-1) {
  3631. if (count == 2) error_line(" ");
  3632. if (count > 1) {
  3633. error_line("or ");
  3634. }
  3635. }
  3636. gbString str = type_to_string(v);
  3637. error_line("'%s'", str);
  3638. gb_string_free(str);
  3639. }
  3640. error_line("\n\n");
  3641. }
  3642. return;
  3643. }
  3644. }
  3645. /* fallthrough */
  3646. default:
  3647. if (is_type_untyped_uninit(operand->type)) {
  3648. target_type = t_untyped_uninit;
  3649. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3650. target_type = t_untyped_nil;
  3651. } else {
  3652. operand->mode = Addressing_Invalid;
  3653. convert_untyped_error(c, operand, target_type);
  3654. return;
  3655. }
  3656. break;
  3657. }
  3658. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3659. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3660. } else {
  3661. target_type = default_type(operand->type);
  3662. }
  3663. }
  3664. update_untyped_expr_type(c, operand->expr, target_type, true);
  3665. operand->type = target_type;
  3666. }
  3667. 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) {
  3668. Operand operand = {Addressing_Invalid};
  3669. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3670. if (operand.mode == Addressing_Invalid) {
  3671. if (value) *value = 0;
  3672. return false;
  3673. }
  3674. Type *index_type = t_int;
  3675. if (type_hint != nullptr) {
  3676. index_type = type_hint;
  3677. }
  3678. convert_to_typed(c, &operand, index_type);
  3679. if (operand.mode == Addressing_Invalid) {
  3680. if (value) *value = 0;
  3681. return false;
  3682. }
  3683. if (type_hint != nullptr) {
  3684. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3685. gbString expr_str = expr_to_string(operand.expr);
  3686. gbString index_type_str = type_to_string(type_hint);
  3687. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3688. gb_string_free(index_type_str);
  3689. gb_string_free(expr_str);
  3690. if (value) *value = 0;
  3691. return false;
  3692. }
  3693. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3694. gbString expr_str = expr_to_string(operand.expr);
  3695. gbString type_str = type_to_string(operand.type);
  3696. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3697. gb_string_free(type_str);
  3698. gb_string_free(expr_str);
  3699. if (value) *value = 0;
  3700. return false;
  3701. }
  3702. if (operand.mode == Addressing_Constant &&
  3703. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3704. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3705. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3706. TEMPORARY_ALLOCATOR_GUARD();
  3707. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3708. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3709. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3710. if (value) *value = 0;
  3711. return false;
  3712. }
  3713. if (max_count >= 0) {
  3714. if (is_type_enum(index_type)) {
  3715. Type *bt = base_type(index_type);
  3716. GB_ASSERT(bt->kind == Type_Enum);
  3717. ExactValue const &lo = *bt->Enum.min_value;
  3718. ExactValue const &hi = *bt->Enum.max_value;
  3719. String lo_str = {};
  3720. String hi_str = {};
  3721. if (bt->Enum.fields.count > 0) {
  3722. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3723. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3724. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3725. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3726. }
  3727. bool out_of_bounds = false;
  3728. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3729. out_of_bounds = true;
  3730. }
  3731. if (out_of_bounds) {
  3732. gbString expr_str = expr_to_string(operand.expr);
  3733. if (lo_str.len > 0) {
  3734. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3735. } else {
  3736. gbString index_type_str = type_to_string(index_type);
  3737. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3738. gb_string_free(index_type_str);
  3739. }
  3740. gb_string_free(expr_str);
  3741. return false;
  3742. }
  3743. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3744. return true;
  3745. } else { // NOTE(bill): Do array bound checking
  3746. i64 v = -1;
  3747. if (i.used <= 1) {
  3748. v = big_int_to_i64(&i);
  3749. }
  3750. if (value) *value = v;
  3751. bool out_of_bounds = false;
  3752. if (v < 0) {
  3753. out_of_bounds = true;
  3754. } else if (open_range) {
  3755. out_of_bounds = v > max_count;
  3756. } else {
  3757. out_of_bounds = v >= max_count;
  3758. }
  3759. if (out_of_bounds) {
  3760. TEMPORARY_ALLOCATOR_GUARD();
  3761. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3762. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3763. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3764. return false;
  3765. }
  3766. return true;
  3767. }
  3768. } else {
  3769. if (value) *value = exact_value_to_i64(operand.value);
  3770. return true;
  3771. }
  3772. }
  3773. // NOTE(bill): It's alright :D
  3774. if (value) *value = -1;
  3775. return true;
  3776. }
  3777. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3778. if (value.kind == ExactValue_String) {
  3779. GB_ASSERT(0 <= index && index < value.value_string.len);
  3780. u8 val = value.value_string[index];
  3781. if (success_) *success_ = true;
  3782. if (finish_) *finish_ = true;
  3783. return exact_value_u64(val);
  3784. }
  3785. if (value.kind != ExactValue_Compound) {
  3786. if (success_) *success_ = true;
  3787. if (finish_) *finish_ = true;
  3788. return value;
  3789. }
  3790. Ast *node = value.value_compound;
  3791. switch (node->kind) {
  3792. case_ast_node(cl, CompoundLit, node);
  3793. if (cl->elems.count == 0) {
  3794. if (success_) *success_ = true;
  3795. if (finish_) *finish_ = true;
  3796. return empty_exact_value;
  3797. }
  3798. if (cl->elems[0]->kind == Ast_FieldValue) {
  3799. if (is_type_struct(node->tav.type)) {
  3800. bool found = false;
  3801. for (Ast *elem : cl->elems) {
  3802. if (elem->kind != Ast_FieldValue) {
  3803. continue;
  3804. }
  3805. ast_node(fv, FieldValue, elem);
  3806. String name = fv->field->Ident.token.string;
  3807. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3808. defer (array_free(&sub_sel.index));
  3809. if (sub_sel.index[0] == index) {
  3810. value = fv->value->tav.value;
  3811. found = true;
  3812. break;
  3813. }
  3814. }
  3815. if (!found) {
  3816. // Use the zero value if it is not found
  3817. value = {};
  3818. }
  3819. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3820. for (Ast *elem : cl->elems) {
  3821. if (elem->kind != Ast_FieldValue) {
  3822. continue;
  3823. }
  3824. ast_node(fv, FieldValue, elem);
  3825. if (is_ast_range(fv->field)) {
  3826. ast_node(ie, BinaryExpr, fv->field);
  3827. TypeAndValue lo_tav = ie->left->tav;
  3828. TypeAndValue hi_tav = ie->right->tav;
  3829. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3830. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3831. TokenKind op = ie->op.kind;
  3832. i64 lo = exact_value_to_i64(lo_tav.value);
  3833. i64 hi = exact_value_to_i64(hi_tav.value);
  3834. i64 corrected_index = index;
  3835. if (is_type_enumerated_array(node->tav.type)) {
  3836. Type *bt = base_type(node->tav.type);
  3837. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3838. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3839. }
  3840. if (op != Token_RangeHalf) {
  3841. if (lo <= corrected_index && corrected_index <= hi) {
  3842. TypeAndValue tav = fv->value->tav;
  3843. if (success_) *success_ = true;
  3844. if (finish_) *finish_ = false;
  3845. return tav.value;
  3846. }
  3847. } else {
  3848. if (lo <= corrected_index && corrected_index < hi) {
  3849. TypeAndValue tav = fv->value->tav;
  3850. if (success_) *success_ = true;
  3851. if (finish_) *finish_ = false;
  3852. return tav.value;
  3853. }
  3854. }
  3855. } else {
  3856. TypeAndValue index_tav = fv->field->tav;
  3857. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3858. ExactValue index_value = index_tav.value;
  3859. if (is_type_enumerated_array(node->tav.type)) {
  3860. Type *bt = base_type(node->tav.type);
  3861. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3862. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3863. }
  3864. i64 field_index = exact_value_to_i64(index_value);
  3865. if (index == field_index) {
  3866. TypeAndValue tav = fv->value->tav;
  3867. if (success_) *success_ = true;
  3868. if (finish_) *finish_ = false;
  3869. return tav.value;;
  3870. }
  3871. }
  3872. }
  3873. }
  3874. } else {
  3875. i32 count = (i32)cl->elems.count;
  3876. if (count < index) {
  3877. if (success_) *success_ = false;
  3878. if (finish_) *finish_ = true;
  3879. return empty_exact_value;
  3880. }
  3881. if (cl->elems.count <= index) {
  3882. if (success_) *success_ = false;
  3883. if (finish_) *finish_ = false;
  3884. return value;
  3885. }
  3886. TypeAndValue tav = cl->elems[index]->tav;
  3887. if (tav.mode == Addressing_Constant) {
  3888. if (success_) *success_ = true;
  3889. if (finish_) *finish_ = false;
  3890. return tav.value;
  3891. } else {
  3892. GB_ASSERT(is_type_untyped_nil(tav.type));
  3893. if (success_) *success_ = true;
  3894. if (finish_) *finish_ = false;
  3895. return tav.value;
  3896. }
  3897. }
  3898. case_end;
  3899. default:
  3900. if (success_) *success_ = true;
  3901. if (finish_) *finish_ = true;
  3902. return empty_exact_value;
  3903. }
  3904. if (finish_) *finish_ = false;
  3905. return value;
  3906. }
  3907. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3908. if (operand->mode != Addressing_Constant) {
  3909. if (success_) *success_ = false;
  3910. return empty_exact_value;
  3911. }
  3912. if (sel.indirect) {
  3913. if (success_) *success_ = false;
  3914. return empty_exact_value;
  3915. }
  3916. if (sel.index.count == 0) {
  3917. if (success_) *success_ = false;
  3918. return empty_exact_value;
  3919. }
  3920. ExactValue value = operand->value;
  3921. if (value.kind == ExactValue_Compound) {
  3922. while (sel.index.count > 0) {
  3923. i32 index = sel.index[0];
  3924. sel = sub_selection(sel, 1);
  3925. bool finish = false;
  3926. value = get_constant_field_single(c, value, index, success_, &finish);
  3927. if (finish) {
  3928. return value;
  3929. }
  3930. }
  3931. if (success_) *success_ = true;
  3932. return value;
  3933. } else if (value.kind == ExactValue_Quaternion) {
  3934. // @QuaternionLayout
  3935. Quaternion256 q = *value.value_quaternion;
  3936. GB_ASSERT(sel.index.count == 1);
  3937. switch (sel.index[0]) {
  3938. case 3: // w
  3939. if (success_) *success_ = true;
  3940. return exact_value_float(q.real);
  3941. case 0: // x
  3942. if (success_) *success_ = true;
  3943. return exact_value_float(q.imag);
  3944. case 1: // y
  3945. if (success_) *success_ = true;
  3946. return exact_value_float(q.jmag);
  3947. case 2: // z
  3948. if (success_) *success_ = true;
  3949. return exact_value_float(q.kmag);
  3950. }
  3951. if (success_) *success_ = false;
  3952. return empty_exact_value;
  3953. } else if (value.kind == ExactValue_Complex) {
  3954. // @QuaternionLayout
  3955. Complex128 c = *value.value_complex;
  3956. GB_ASSERT(sel.index.count == 1);
  3957. switch (sel.index[0]) {
  3958. case 0: // real
  3959. if (success_) *success_ = true;
  3960. return exact_value_float(c.real);
  3961. case 1: // imag
  3962. if (success_) *success_ = true;
  3963. return exact_value_float(c.imag);
  3964. }
  3965. if (success_) *success_ = false;
  3966. return empty_exact_value;
  3967. }
  3968. if (success_) *success_ = true;
  3969. return empty_exact_value;
  3970. }
  3971. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  3972. Type *array_type = base_type(type_deref(original_type));
  3973. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  3974. if (array_type->kind == Type_SimdVector) {
  3975. Type *elem_type = array_type->SimdVector.elem;
  3976. return alloc_type_simd_vector(new_count, elem_type);
  3977. }
  3978. Type *elem_type = array_type->Array.elem;
  3979. Type *swizzle_array_type = nullptr;
  3980. Type *bth = base_type(type_deref(type_hint));
  3981. if (bth != nullptr && bth->kind == Type_Array &&
  3982. bth->Array.count == new_count &&
  3983. are_types_identical(bth->Array.elem, elem_type)) {
  3984. swizzle_array_type = type_hint;
  3985. } else {
  3986. i64 max_count = array_type->Array.count;
  3987. if (new_count == max_count) {
  3988. swizzle_array_type = original_type;
  3989. } else {
  3990. swizzle_array_type = alloc_type_array(elem_type, new_count);
  3991. }
  3992. }
  3993. return swizzle_array_type;
  3994. }
  3995. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  3996. bool is_declared = entity != nullptr;
  3997. if (is_declared) {
  3998. if (entity->kind == Entity_Builtin) {
  3999. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4000. // This means that we should just ignore the found result through it
  4001. *allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  4002. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4003. is_declared = false;
  4004. }
  4005. }
  4006. return is_declared;
  4007. }
  4008. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4009. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4010. if (node->kind == Ast_Ident) {
  4011. String name = node->Ident.token.string;
  4012. return scope_lookup(c->scope, name);
  4013. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4014. ast_node(se, SelectorExpr, node);
  4015. if (se->token.kind == Token_ArrowRight) {
  4016. return nullptr;
  4017. }
  4018. Ast *op_expr = se->expr;
  4019. Ast *selector = unparen_expr(se->selector);
  4020. if (selector == nullptr) {
  4021. return nullptr;
  4022. }
  4023. if (selector->kind != Ast_Ident) {
  4024. return nullptr;
  4025. }
  4026. Entity *entity = nullptr;
  4027. Entity *expr_entity = nullptr;
  4028. bool check_op_expr = true;
  4029. if (op_expr->kind == Ast_Ident) {
  4030. String op_name = op_expr->Ident.token.string;
  4031. Entity *e = scope_lookup(c->scope, op_name);
  4032. if (e == nullptr) {
  4033. return nullptr;
  4034. }
  4035. add_entity_use(c, op_expr, e);
  4036. expr_entity = e;
  4037. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4038. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4039. // It pretty much needs to be in this order and this way
  4040. // If you can clean this up, please do but be really careful
  4041. String import_name = op_name;
  4042. Scope *import_scope = e->ImportName.scope;
  4043. String entity_name = selector->Ident.token.string;
  4044. check_op_expr = false;
  4045. entity = scope_lookup_current(import_scope, entity_name);
  4046. bool allow_builtin = false;
  4047. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4048. return nullptr;
  4049. }
  4050. check_entity_decl(c, entity, nullptr, nullptr);
  4051. if (entity->kind == Entity_ProcGroup) {
  4052. return entity;
  4053. }
  4054. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4055. }
  4056. }
  4057. Operand operand = {};
  4058. if (check_op_expr) {
  4059. check_expr_base(c, &operand, op_expr, nullptr);
  4060. if (operand.mode == Addressing_Invalid) {
  4061. return nullptr;
  4062. }
  4063. }
  4064. if (entity == nullptr && selector->kind == Ast_Ident) {
  4065. String field_name = selector->Ident.token.string;
  4066. if (is_type_dynamic_array(type_deref(operand.type))) {
  4067. init_mem_allocator(c->checker);
  4068. }
  4069. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4070. entity = sel.entity;
  4071. }
  4072. if (entity != nullptr) {
  4073. return entity;
  4074. }
  4075. }
  4076. return nullptr;
  4077. }
  4078. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4079. ast_node(se, SelectorExpr, node);
  4080. bool check_op_expr = true;
  4081. Entity *expr_entity = nullptr;
  4082. Entity *entity = nullptr;
  4083. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4084. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4085. error(node, "Illegal use of -> selector shorthand outside of a call");
  4086. operand->mode = Addressing_Invalid;
  4087. operand->expr = node;
  4088. return nullptr;
  4089. }
  4090. operand->expr = node;
  4091. Ast *op_expr = se->expr;
  4092. Ast *selector = unparen_expr(se->selector);
  4093. if (selector == nullptr) {
  4094. operand->mode = Addressing_Invalid;
  4095. operand->expr = node;
  4096. return nullptr;
  4097. }
  4098. if (selector->kind != Ast_Ident) {
  4099. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4100. operand->mode = Addressing_Invalid;
  4101. operand->expr = node;
  4102. return nullptr;
  4103. }
  4104. if (op_expr->kind == Ast_Ident) {
  4105. String op_name = op_expr->Ident.token.string;
  4106. Entity *e = scope_lookup(c->scope, op_name);
  4107. add_entity_use(c, op_expr, e);
  4108. expr_entity = e;
  4109. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4110. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4111. // It pretty much needs to be in this order and this way
  4112. // If you can clean this up, please do but be really careful
  4113. String import_name = op_name;
  4114. Scope *import_scope = e->ImportName.scope;
  4115. String entity_name = selector->Ident.token.string;
  4116. check_op_expr = false;
  4117. entity = scope_lookup_current(import_scope, entity_name);
  4118. bool allow_builtin = false;
  4119. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4120. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4121. operand->mode = Addressing_Invalid;
  4122. operand->expr = node;
  4123. check_did_you_mean_scope(entity_name, import_scope);
  4124. return nullptr;
  4125. }
  4126. check_entity_decl(c, entity, nullptr, nullptr);
  4127. if (entity->kind == Entity_ProcGroup) {
  4128. operand->mode = Addressing_ProcGroup;
  4129. operand->proc_group = entity;
  4130. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4131. return entity;
  4132. }
  4133. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4134. if (!is_entity_exported(entity, allow_builtin)) {
  4135. gbString sel_str = expr_to_string(selector);
  4136. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4137. gb_string_free(sel_str);
  4138. // NOTE(bill): make the state valid still, even if it's "invalid"
  4139. // operand->mode = Addressing_Invalid;
  4140. // operand->expr = node;
  4141. // return nullptr;
  4142. }
  4143. if (entity->kind == Entity_ProcGroup) {
  4144. Array<Entity *> procs = entity->ProcGroup.entities;
  4145. bool skip = false;
  4146. for (Entity *p : procs) {
  4147. Type *t = base_type(p->type);
  4148. if (t == t_invalid) {
  4149. continue;
  4150. }
  4151. Operand x = {};
  4152. x.mode = Addressing_Value;
  4153. x.type = t;
  4154. if (type_hint != nullptr) {
  4155. if (check_is_assignable_to(c, &x, type_hint)) {
  4156. entity = p;
  4157. skip = true;
  4158. break;
  4159. }
  4160. }
  4161. }
  4162. if (!skip) {
  4163. GB_ASSERT(entity != nullptr);
  4164. operand->mode = Addressing_ProcGroup;
  4165. operand->type = t_invalid;
  4166. operand->expr = node;
  4167. operand->proc_group = entity;
  4168. return entity;
  4169. }
  4170. }
  4171. }
  4172. }
  4173. if (check_op_expr) {
  4174. check_expr_base(c, operand, op_expr, nullptr);
  4175. if (operand->mode == Addressing_Invalid) {
  4176. operand->mode = Addressing_Invalid;
  4177. operand->expr = node;
  4178. return nullptr;
  4179. }
  4180. }
  4181. if (entity == nullptr && selector->kind == Ast_Ident) {
  4182. String field_name = selector->Ident.token.string;
  4183. Type *t = type_deref(operand->type);
  4184. if (t == nullptr) {
  4185. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4186. } else if (is_type_dynamic_array(t)) {
  4187. init_mem_allocator(c->checker);
  4188. }
  4189. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4190. entity = sel.entity;
  4191. // NOTE(bill): Add type info needed for fields like 'names'
  4192. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4193. add_type_info_type(c, operand->type);
  4194. }
  4195. if (is_type_enum(operand->type)) {
  4196. add_type_info_type(c, operand->type);
  4197. }
  4198. }
  4199. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  4200. String field_name = selector->Ident.token.string;
  4201. if (1 < field_name.len && field_name.len <= 4) {
  4202. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4203. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4204. bool found_xyzw = false;
  4205. bool found_rgba = false;
  4206. for (isize i = 0; i < field_name.len; i++) {
  4207. bool valid = false;
  4208. for (isize j = 0; j < 4; j++) {
  4209. if (field_name.text[i] == swizzles_xyzw[j]) {
  4210. found_xyzw = true;
  4211. valid = true;
  4212. break;
  4213. }
  4214. if (field_name.text[i] == swizzles_rgba[j]) {
  4215. found_rgba = true;
  4216. valid = true;
  4217. break;
  4218. }
  4219. }
  4220. if (!valid) {
  4221. goto end_of_array_selector_swizzle;
  4222. }
  4223. }
  4224. u8 *swizzles = nullptr;
  4225. u8 index_count = cast(u8)field_name.len;
  4226. if (found_xyzw && found_rgba) {
  4227. gbString op_str = expr_to_string(op_expr);
  4228. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4229. gb_string_free(op_str);
  4230. operand->mode = Addressing_Invalid;
  4231. operand->expr = node;
  4232. return nullptr;
  4233. }
  4234. u8 indices = 0;
  4235. if (found_xyzw) {
  4236. swizzles = swizzles_xyzw;
  4237. } else if (found_rgba) {
  4238. swizzles = swizzles_rgba;
  4239. }
  4240. for (isize i = 0; i < field_name.len; i++) {
  4241. for (isize j = 0; j < 4; j++) {
  4242. if (field_name.text[i] == swizzles[j]) {
  4243. indices |= cast(u8)(j)<<(i*2);
  4244. break;
  4245. }
  4246. }
  4247. }
  4248. Type *original_type = operand->type;
  4249. Type *array_type = base_type(type_deref(original_type));
  4250. GB_ASSERT(array_type->kind == Type_Array);
  4251. i64 array_count = array_type->Array.count;
  4252. for (u8 i = 0; i < index_count; i++) {
  4253. u8 idx = indices>>(i*2) & 3;
  4254. if (idx >= array_count) {
  4255. char c = 0;
  4256. if (found_xyzw) {
  4257. c = swizzles_xyzw[idx];
  4258. } else if (found_rgba) {
  4259. c = swizzles_rgba[idx];
  4260. } else {
  4261. GB_PANIC("unknown swizzle kind");
  4262. }
  4263. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4264. break;
  4265. }
  4266. }
  4267. se->swizzle_count = index_count;
  4268. se->swizzle_indices = indices;
  4269. AddressingMode prev_mode = operand->mode;
  4270. operand->mode = Addressing_SwizzleValue;
  4271. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4272. operand->expr = node;
  4273. switch (prev_mode) {
  4274. case Addressing_Variable:
  4275. case Addressing_SoaVariable:
  4276. case Addressing_SwizzleVariable:
  4277. operand->mode = Addressing_SwizzleVariable;
  4278. break;
  4279. }
  4280. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4281. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4282. return swizzle_entity;
  4283. }
  4284. end_of_array_selector_swizzle:;
  4285. }
  4286. if (entity == nullptr) {
  4287. gbString op_str = expr_to_string(op_expr);
  4288. gbString type_str = type_to_string_shorthand(operand->type);
  4289. gbString sel_str = expr_to_string(selector);
  4290. if (operand->mode == Addressing_Type) {
  4291. if (is_type_polymorphic(operand->type, true)) {
  4292. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4293. } else {
  4294. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4295. }
  4296. } else {
  4297. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4298. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4299. String const &name = selector->Ident.token.string;
  4300. Type *bt = base_type(operand->type);
  4301. if (operand->type->kind == Type_Named &&
  4302. operand->type->Named.type_name &&
  4303. operand->type->Named.type_name->kind == Entity_TypeName &&
  4304. operand->type->Named.type_name->TypeName.objc_metadata) {
  4305. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4306. } else if (bt->kind == Type_Struct) {
  4307. check_did_you_mean_type(name, bt->Struct.fields);
  4308. } else if (bt->kind == Type_Enum) {
  4309. check_did_you_mean_type(name, bt->Enum.fields);
  4310. }
  4311. }
  4312. }
  4313. gb_string_free(sel_str);
  4314. gb_string_free(type_str);
  4315. gb_string_free(op_str);
  4316. operand->mode = Addressing_Invalid;
  4317. operand->expr = node;
  4318. return nullptr;
  4319. }
  4320. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4321. bool success = false;
  4322. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4323. if (success) {
  4324. operand->mode = Addressing_Constant;
  4325. operand->expr = node;
  4326. operand->value = field_value;
  4327. operand->type = entity->type;
  4328. add_entity_use(c, selector, entity);
  4329. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4330. return entity;
  4331. }
  4332. gbString op_str = expr_to_string(op_expr);
  4333. gbString type_str = type_to_string_shorthand(operand->type);
  4334. gbString sel_str = expr_to_string(selector);
  4335. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4336. gb_string_free(sel_str);
  4337. gb_string_free(type_str);
  4338. gb_string_free(op_str);
  4339. operand->mode = Addressing_Invalid;
  4340. operand->expr = node;
  4341. return nullptr;
  4342. }
  4343. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4344. bool success = false;
  4345. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4346. if (success) {
  4347. operand->mode = Addressing_Constant;
  4348. operand->expr = node;
  4349. operand->value = field_value;
  4350. operand->type = entity->type;
  4351. add_entity_use(c, selector, entity);
  4352. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4353. return entity;
  4354. }
  4355. gbString op_str = expr_to_string(op_expr);
  4356. gbString type_str = type_to_string_shorthand(operand->type);
  4357. gbString sel_str = expr_to_string(selector);
  4358. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4359. gb_string_free(sel_str);
  4360. gb_string_free(type_str);
  4361. gb_string_free(op_str);
  4362. operand->mode = Addressing_Invalid;
  4363. operand->expr = node;
  4364. return nullptr;
  4365. }
  4366. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4367. gbString op_str = expr_to_string(op_expr);
  4368. gbString type_str = type_to_string_shorthand(operand->type);
  4369. gbString sel_str = expr_to_string(selector);
  4370. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4371. gb_string_free(sel_str);
  4372. gb_string_free(type_str);
  4373. gb_string_free(op_str);
  4374. operand->mode = Addressing_Invalid;
  4375. operand->expr = node;
  4376. return nullptr;
  4377. }
  4378. add_entity_use(c, selector, entity);
  4379. operand->type = entity->type;
  4380. operand->expr = node;
  4381. switch (entity->kind) {
  4382. case Entity_Constant:
  4383. operand->value = entity->Constant.value;
  4384. operand->mode = Addressing_Constant;
  4385. if (operand->value.kind == ExactValue_Procedure) {
  4386. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4387. if (proc != nullptr) {
  4388. operand->mode = Addressing_Value;
  4389. operand->type = proc->type;
  4390. }
  4391. }
  4392. break;
  4393. case Entity_Variable:
  4394. if (sel.indirect) {
  4395. operand->mode = Addressing_Variable;
  4396. } else if (operand->mode == Addressing_Context) {
  4397. // Do nothing
  4398. } else if (operand->mode == Addressing_MapIndex) {
  4399. operand->mode = Addressing_Value;
  4400. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4401. operand->mode = Addressing_SoaVariable;
  4402. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4403. operand->mode = Addressing_Value;
  4404. } else if (operand->mode == Addressing_SoaVariable) {
  4405. operand->mode = Addressing_Variable;
  4406. } else if (operand->mode != Addressing_Value) {
  4407. operand->mode = Addressing_Variable;
  4408. } else {
  4409. operand->mode = Addressing_Value;
  4410. }
  4411. break;
  4412. case Entity_TypeName:
  4413. operand->mode = Addressing_Type;
  4414. break;
  4415. case Entity_Procedure:
  4416. operand->mode = Addressing_Value;
  4417. operand->value = exact_value_procedure(node);
  4418. break;
  4419. case Entity_Builtin:
  4420. operand->mode = Addressing_Builtin;
  4421. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4422. break;
  4423. case Entity_ProcGroup:
  4424. operand->mode = Addressing_ProcGroup;
  4425. operand->proc_group = entity;
  4426. break;
  4427. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4428. case Entity_Nil:
  4429. operand->mode = Addressing_Value;
  4430. break;
  4431. }
  4432. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4433. return entity;
  4434. }
  4435. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4436. ptr = base_type(ptr);
  4437. if (is_type_pointer(ptr)) {
  4438. if (is_type_rawptr(ptr)) {
  4439. return false;
  4440. }
  4441. if (elem) *elem = ptr->Pointer.elem;
  4442. return true;
  4443. }
  4444. return false;
  4445. }
  4446. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4447. elem = core_type(elem);
  4448. if (is_type_internally_pointer_like(elem)) {
  4449. return true;
  4450. }
  4451. if (elem->kind == Type_BitSet) {
  4452. elem = bit_set_to_int(elem);
  4453. }
  4454. if (elem->kind != Type_Basic) {
  4455. return false;
  4456. }
  4457. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4458. }
  4459. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4460. switch (node->kind) {
  4461. case_ast_node(i, Ident, node);
  4462. String name = i->token.string;
  4463. if (nested) {
  4464. Entity *e = scope_lookup_current(s, name);
  4465. if (e != nullptr) {
  4466. if (out_scope) *out_scope = e->scope;
  4467. return true;
  4468. }
  4469. } else {
  4470. Entity *e = scope_lookup(s, name);
  4471. if (e != nullptr) {
  4472. if (out_scope) *out_scope = e->scope;
  4473. return true;
  4474. }
  4475. }
  4476. case_end;
  4477. case_ast_node(se, SelectorExpr, node);
  4478. Ast *lhs = se->expr;
  4479. Ast *rhs = se->selector;
  4480. Scope *lhs_scope = nullptr;
  4481. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4482. return check_identifier_exists(lhs_scope, rhs, true);
  4483. }
  4484. case_end;
  4485. }
  4486. return false;
  4487. }
  4488. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4489. if (o.type && is_type_no_copy(o.type)) {
  4490. Ast *expr = unparen_expr(o.expr);
  4491. if (expr && o.mode != Addressing_Constant) {
  4492. if (expr->kind == Ast_CallExpr) {
  4493. // Okay
  4494. } else {
  4495. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4496. return true;
  4497. }
  4498. }
  4499. }
  4500. return false;
  4501. }
  4502. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4503. bool optional_ok = false;
  4504. isize tuple_index = 0;
  4505. for (Ast *rhs_expr : rhs) {
  4506. CheckerContext c_ = *ctx;
  4507. CheckerContext *c = &c_;
  4508. Operand o = {};
  4509. Type *type_hint = nullptr;
  4510. if (tuple_index < lhs.count) {
  4511. type_hint = lhs[tuple_index].type;
  4512. }
  4513. check_expr_base(c, &o, rhs_expr, type_hint);
  4514. if (o.mode == Addressing_NoValue) {
  4515. error_operand_no_value(&o);
  4516. o.mode = Addressing_Invalid;
  4517. }
  4518. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4519. if (lhs.count == 2 && rhs.count == 1 &&
  4520. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4521. Ast *expr = unparen_expr(o.expr);
  4522. Operand val0 = o;
  4523. Operand val1 = o;
  4524. val0.mode = Addressing_Value;
  4525. val1.mode = Addressing_Value;
  4526. val1.type = t_untyped_bool;
  4527. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4528. if (expr->kind == Ast_TypeAssertion &&
  4529. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4530. // NOTE(bill): Used only for optimizations in the backend
  4531. if (is_blank_ident(lhs[0].expr)) {
  4532. expr->TypeAssertion.ignores[0] = true;
  4533. }
  4534. if (is_blank_ident(lhs[1].expr)) {
  4535. expr->TypeAssertion.ignores[1] = true;
  4536. }
  4537. }
  4538. array_add(operands, val0);
  4539. array_add(operands, val1);
  4540. optional_ok = true;
  4541. tuple_index += 2;
  4542. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4543. Type *tuple = o.type;
  4544. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4545. Ast *expr = unparen_expr(o.expr);
  4546. if (expr->kind == Ast_CallExpr) {
  4547. expr->CallExpr.optional_ok_one = true;
  4548. }
  4549. Operand val = o;
  4550. val.type = tuple->Tuple.variables[0]->type;
  4551. val.mode = Addressing_Value;
  4552. array_add(operands, val);
  4553. tuple_index += tuple->Tuple.variables.count;
  4554. } else {
  4555. array_add(operands, o);
  4556. tuple_index += 1;
  4557. }
  4558. } else {
  4559. TypeTuple *tuple = &o.type->Tuple;
  4560. for (Entity *e : tuple->variables) {
  4561. o.type = e->type;
  4562. array_add(operands, o);
  4563. check_no_copy_assignment(o, str_lit("assignment"));
  4564. }
  4565. tuple_index += tuple->variables.count;
  4566. }
  4567. }
  4568. return optional_ok;
  4569. }
  4570. typedef u32 UnpackFlags;
  4571. enum UnpackFlag : u32 {
  4572. UnpackFlag_None = 0,
  4573. UnpackFlag_AllowOk = 1<<0,
  4574. UnpackFlag_IsVariadic = 1<<1,
  4575. UnpackFlag_AllowUndef = 1<<2,
  4576. };
  4577. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4578. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4579. if (lhs == nullptr || c->decl == nullptr) {
  4580. return tuple_count;
  4581. }
  4582. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4583. Entity *e = lhs[tuple_index + j];
  4584. if (e == nullptr) {
  4585. continue;
  4586. }
  4587. DeclInfo *decl = decl_info_of_entity(e);
  4588. if (decl == nullptr) {
  4589. continue;
  4590. }
  4591. rw_mutex_shared_lock(&decl->deps_mutex);
  4592. rw_mutex_lock(&c->decl->deps_mutex);
  4593. for (Entity *dep : decl->deps) {
  4594. ptr_set_add(&c->decl->deps, dep);
  4595. }
  4596. rw_mutex_unlock(&c->decl->deps_mutex);
  4597. rw_mutex_shared_unlock(&decl->deps_mutex);
  4598. }
  4599. return tuple_count;
  4600. };
  4601. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4602. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4603. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4604. bool optional_ok = false;
  4605. isize tuple_index = 0;
  4606. for (Ast *rhs : rhs_arguments) {
  4607. if (rhs->kind == Ast_FieldValue) {
  4608. error(rhs, "Invalid use of 'field = value'");
  4609. rhs = rhs->FieldValue.value;
  4610. }
  4611. CheckerContext c_ = *ctx;
  4612. CheckerContext *c = &c_;
  4613. Operand o = {};
  4614. Type *type_hint = nullptr;
  4615. if (lhs != nullptr && tuple_index < lhs_count) {
  4616. // NOTE(bill): override DeclInfo for dependency
  4617. Entity *e = lhs[tuple_index];
  4618. if (e != nullptr) {
  4619. type_hint = e->type;
  4620. if (e->flags & EntityFlag_Ellipsis) {
  4621. GB_ASSERT(is_type_slice(e->type));
  4622. GB_ASSERT(e->type->kind == Type_Slice);
  4623. type_hint = e->type->Slice.elem;
  4624. }
  4625. }
  4626. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4627. // NOTE(bill): override DeclInfo for dependency
  4628. Entity *e = lhs[lhs_count-1];
  4629. if (e != nullptr) {
  4630. type_hint = e->type;
  4631. if (e->flags & EntityFlag_Ellipsis) {
  4632. GB_ASSERT(is_type_slice(e->type));
  4633. GB_ASSERT(e->type->kind == Type_Slice);
  4634. type_hint = e->type->Slice.elem;
  4635. }
  4636. }
  4637. }
  4638. Ast *rhs_expr = unparen_expr(rhs);
  4639. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4640. // NOTE(bill): Just handle this very specific logic here
  4641. o.type = t_untyped_uninit;
  4642. o.mode = Addressing_Value;
  4643. o.expr = rhs;
  4644. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4645. } else {
  4646. check_expr_base(c, &o, rhs, type_hint);
  4647. }
  4648. if (o.mode == Addressing_NoValue) {
  4649. error_operand_no_value(&o);
  4650. o.mode = Addressing_Invalid;
  4651. }
  4652. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4653. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4654. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4655. Ast *expr = unparen_expr(o.expr);
  4656. Operand val0 = o;
  4657. Operand val1 = o;
  4658. val0.mode = Addressing_Value;
  4659. val1.mode = Addressing_Value;
  4660. val1.type = t_untyped_bool;
  4661. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4662. if (expr->kind == Ast_TypeAssertion &&
  4663. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4664. // NOTE(bill): Used only for optimizations in the backend
  4665. if (is_blank_ident(lhs[0]->token)) {
  4666. expr->TypeAssertion.ignores[0] = true;
  4667. }
  4668. if (is_blank_ident(lhs[1]->token)) {
  4669. expr->TypeAssertion.ignores[1] = true;
  4670. }
  4671. }
  4672. array_add(operands, val0);
  4673. array_add(operands, val1);
  4674. optional_ok = true;
  4675. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4676. } else {
  4677. array_add(operands, o);
  4678. tuple_index += 1;
  4679. }
  4680. } else {
  4681. TypeTuple *tuple = &o.type->Tuple;
  4682. for (Entity *e : tuple->variables) {
  4683. o.type = e->type;
  4684. array_add(operands, o);
  4685. }
  4686. isize count = tuple->variables.count;
  4687. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4688. }
  4689. }
  4690. return optional_ok;
  4691. }
  4692. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4693. GB_ASSERT(pt != nullptr);
  4694. GB_ASSERT(pt->kind == Type_Proc);
  4695. isize param_count = 0;
  4696. isize param_count_excluding_defaults = 0;
  4697. bool variadic = pt->Proc.variadic;
  4698. TypeTuple *param_tuple = nullptr;
  4699. if (pt->Proc.params != nullptr) {
  4700. param_tuple = &pt->Proc.params->Tuple;
  4701. param_count = param_tuple->variables.count;
  4702. if (variadic) {
  4703. for (isize i = param_count-1; i >= 0; i--) {
  4704. Entity *e = param_tuple->variables[i];
  4705. if (e->kind == Entity_TypeName) {
  4706. break;
  4707. }
  4708. if (e->kind == Entity_Variable) {
  4709. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4710. param_count--;
  4711. continue;
  4712. }
  4713. }
  4714. break;
  4715. }
  4716. param_count--;
  4717. }
  4718. }
  4719. param_count_excluding_defaults = param_count;
  4720. if (param_tuple != nullptr) {
  4721. for (isize i = param_count-1; i >= 0; i--) {
  4722. Entity *e = param_tuple->variables[i];
  4723. if (e->kind == Entity_TypeName) {
  4724. break;
  4725. }
  4726. if (e->kind == Entity_Variable) {
  4727. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4728. param_count_excluding_defaults--;
  4729. continue;
  4730. }
  4731. }
  4732. break;
  4733. }
  4734. }
  4735. if (param_count_) *param_count_ = param_count;
  4736. return param_count_excluding_defaults;
  4737. }
  4738. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4739. isize param_count = pt->param_count;
  4740. for (isize i = 0; i < param_count; i++) {
  4741. Entity *e = pt->params->Tuple.variables[i];
  4742. String name = e->token.string;
  4743. if (is_blank_ident(name)) {
  4744. continue;
  4745. }
  4746. if (name == parameter_name) {
  4747. return i;
  4748. }
  4749. }
  4750. return -1;
  4751. }
  4752. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4753. type = base_type(type);
  4754. GB_ASSERT(type->kind == Type_Proc);
  4755. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4756. }
  4757. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  4758. Entity *entity, Type *proc_type,
  4759. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  4760. CallArgumentErrorMode show_error_mode,
  4761. CallArgumentData *data) {
  4762. TEMPORARY_ALLOCATOR_GUARD();
  4763. CallArgumentError err = CallArgumentError_None;
  4764. ast_node(ce, CallExpr, call);
  4765. GB_ASSERT(is_type_proc(proc_type));
  4766. proc_type = base_type(proc_type);
  4767. TypeProc *pt = &proc_type->Proc;
  4768. isize param_count = 0;
  4769. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4770. bool variadic = pt->variadic;
  4771. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4772. i64 score = 0;
  4773. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  4774. Type *final_proc_type = proc_type;
  4775. Entity *gen_entity = nullptr;
  4776. if (vari_expand && !variadic) {
  4777. if (show_error) {
  4778. error(ce->ellipsis,
  4779. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4780. LIT(ce->proc->Ident.token.string));
  4781. }
  4782. err = CallArgumentError_NonVariadicExpand;
  4783. } else if (vari_expand && pt->c_vararg) {
  4784. if (show_error) {
  4785. error(ce->ellipsis,
  4786. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4787. LIT(ce->proc->Ident.token.string));
  4788. }
  4789. err = CallArgumentError_NonVariadicExpand;
  4790. }
  4791. GB_ASSERT(ce->split_args);
  4792. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  4793. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  4794. defer ({
  4795. for (Operand const &o : ordered_operands) {
  4796. if (o.expr != nullptr) {
  4797. call->viral_state_flags |= o.expr->viral_state_flags;
  4798. }
  4799. }
  4800. });
  4801. isize positional_operand_count = positional_operands.count;
  4802. if (variadic) {
  4803. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  4804. } else if (positional_operand_count > pt->param_count) {
  4805. err = CallArgumentError_TooManyArguments;
  4806. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4807. if (show_error) {
  4808. gbString proc_str = expr_to_string(ce->proc);
  4809. defer (gb_string_free(proc_str));
  4810. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  4811. }
  4812. return err;
  4813. }
  4814. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  4815. for (isize i = 0; i < positional_operand_count; i++) {
  4816. ordered_operands[i] = positional_operands[i];
  4817. visited[i] = true;
  4818. }
  4819. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  4820. bool named_variadic_param = false;
  4821. if (named_operands.count != 0) {
  4822. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  4823. for_array(i, ce->split_args->named) {
  4824. Ast *arg = ce->split_args->named[i];
  4825. Operand operand = named_operands[i];
  4826. ast_node(fv, FieldValue, arg);
  4827. if (fv->field->kind != Ast_Ident) {
  4828. if (show_error) {
  4829. gbString expr_str = expr_to_string(fv->field);
  4830. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4831. gb_string_free(expr_str);
  4832. }
  4833. err = CallArgumentError_InvalidFieldValue;
  4834. continue;
  4835. }
  4836. String name = fv->field->Ident.token.string;
  4837. isize param_index = lookup_procedure_parameter(pt, name);
  4838. if (param_index < 0) {
  4839. if (show_error) {
  4840. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4841. }
  4842. err = CallArgumentError_ParameterNotFound;
  4843. continue;
  4844. }
  4845. if (pt->variadic && param_index == pt->variadic_index) {
  4846. named_variadic_param = true;
  4847. }
  4848. if (visited[param_index]) {
  4849. if (show_error) {
  4850. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4851. }
  4852. err = CallArgumentError_DuplicateParameter;
  4853. continue;
  4854. }
  4855. visited[param_index] = true;
  4856. ordered_operands[param_index] = operand;
  4857. }
  4858. }
  4859. isize dummy_argument_count = 0;
  4860. bool actually_variadic = false;
  4861. if (variadic) {
  4862. if (visited[pt->variadic_index] &&
  4863. positional_operand_count < positional_operands.count) {
  4864. if (show_error) {
  4865. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  4866. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  4867. }
  4868. err = CallArgumentError_DuplicateParameter;
  4869. } else if (!visited[pt->variadic_index]) {
  4870. visited[pt->variadic_index] = true;
  4871. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  4872. if (vari_expand) {
  4873. GB_ASSERT(variadic_operands.count != 0);
  4874. *variadic_operand = variadic_operands[0];
  4875. variadic_operand->type = default_type(variadic_operand->type);
  4876. actually_variadic = true;
  4877. } else {
  4878. AstFile *f = call->file();
  4879. // HACK(bill): this is an awful hack
  4880. Operand o = {};
  4881. o.mode = Addressing_Value;
  4882. o.expr = ast_ident(f, make_token_ident("nil"));
  4883. o.expr->Ident.token.pos = ast_token(call).pos;
  4884. if (variadic_operands.count != 0) {
  4885. actually_variadic = true;
  4886. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  4887. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  4888. o.type = vt->type;
  4889. } else {
  4890. dummy_argument_count += 1;
  4891. o.type = t_untyped_nil;
  4892. }
  4893. *variadic_operand = o;
  4894. }
  4895. }
  4896. }
  4897. for (Operand const &o : ordered_operands) {
  4898. if (o.mode != Addressing_Invalid) {
  4899. check_no_copy_assignment(o, str_lit("procedure call expression"));
  4900. }
  4901. }
  4902. for (isize i = 0; i < pt->param_count; i++) {
  4903. if (!visited[i]) {
  4904. Entity *e = pt->params->Tuple.variables[i];
  4905. if (is_blank_ident(e->token)) {
  4906. continue;
  4907. }
  4908. if (e->kind == Entity_Variable) {
  4909. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4910. ordered_operands[i].mode = Addressing_Value;
  4911. ordered_operands[i].type = e->type;
  4912. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  4913. dummy_argument_count += 1;
  4914. score += assign_score_function(1);
  4915. continue;
  4916. }
  4917. }
  4918. if (show_error) {
  4919. if (e->kind == Entity_TypeName) {
  4920. error(call, "Type parameter '%.*s' is missing in procedure call",
  4921. LIT(e->token.string));
  4922. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4923. // Ignore
  4924. } else {
  4925. gbString str = type_to_string(e->type);
  4926. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4927. LIT(e->token.string), str);
  4928. gb_string_free(str);
  4929. }
  4930. }
  4931. err = CallArgumentError_ParameterMissing;
  4932. }
  4933. }
  4934. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  4935. i64 s = 0;
  4936. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic)) {
  4937. bool ok = false;
  4938. if (e && e->flags & EntityFlag_AnyInt) {
  4939. if (is_type_integer(param_type)) {
  4940. ok = check_is_castable_to(c, o, param_type);
  4941. }
  4942. }
  4943. if (ok) {
  4944. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4945. } else {
  4946. if (show_error) {
  4947. check_assignment(c, o, param_type, str_lit("procedure argument"));
  4948. }
  4949. err = CallArgumentError_WrongTypes;
  4950. }
  4951. } else if (show_error) {
  4952. check_assignment(c, o, param_type, str_lit("procedure argument"));
  4953. }
  4954. if (e && e->flags & EntityFlag_ConstInput) {
  4955. if (o->mode != Addressing_Constant) {
  4956. if (show_error) {
  4957. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4958. }
  4959. err = CallArgumentError_NoneConstantParameter;
  4960. }
  4961. }
  4962. if (!err && is_type_any(param_type)) {
  4963. add_type_info_type(c, o->type);
  4964. }
  4965. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  4966. add_type_info_type(c, o->type);
  4967. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  4968. } else if (show_error && is_type_untyped(o->type)) {
  4969. update_untyped_expr_type(c, o->expr, param_type, true);
  4970. }
  4971. return s;
  4972. };
  4973. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  4974. err = CallArgumentError_None;
  4975. if (variadic) {
  4976. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  4977. Type *t = pt->params->Tuple.variables[0]->type;
  4978. if (is_type_polymorphic(t)) {
  4979. if (show_error) {
  4980. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4981. }
  4982. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4983. }
  4984. }
  4985. } else {
  4986. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  4987. PolyProcData poly_proc_data = {};
  4988. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  4989. gen_entity = poly_proc_data.gen_entity;
  4990. Type *gept = base_type(gen_entity->type);
  4991. GB_ASSERT(is_type_proc(gept));
  4992. final_proc_type = gen_entity->type;
  4993. pt = &gept->Proc;
  4994. } else {
  4995. err = CallArgumentError_WrongTypes;
  4996. }
  4997. }
  4998. for (isize i = 0; i < pt->param_count; i++) {
  4999. Operand *o = &ordered_operands[i];
  5000. if (o->mode == Addressing_Invalid) {
  5001. continue;
  5002. }
  5003. Entity *e = pt->params->Tuple.variables[i];
  5004. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5005. if (e->kind == Entity_TypeName) {
  5006. GB_ASSERT(pt->is_polymorphic);
  5007. if (o->mode != Addressing_Type) {
  5008. if (show_error) {
  5009. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5010. }
  5011. err = CallArgumentError_WrongTypes;
  5012. }
  5013. if (are_types_identical(e->type, o->type)) {
  5014. score += assign_score_function(1);
  5015. } else {
  5016. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5017. }
  5018. continue;
  5019. }
  5020. if (param_is_variadic) {
  5021. continue;
  5022. }
  5023. score += eval_param_and_score(c, o, e->type, err, param_is_variadic, e, show_error);
  5024. }
  5025. }
  5026. if (variadic) {
  5027. Type *slice = pt->params->Tuple.variables[pt->variadic_index]->type;
  5028. GB_ASSERT(is_type_slice(slice));
  5029. Type *elem = base_type(slice)->Slice.elem;
  5030. Type *t = elem;
  5031. if (is_type_polymorphic(t)) {
  5032. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5033. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5034. }
  5035. for_array(operand_index, variadic_operands) {
  5036. Operand *o = &variadic_operands[operand_index];
  5037. if (vari_expand) {
  5038. t = slice;
  5039. if (operand_index > 0) {
  5040. if (show_error) {
  5041. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5042. }
  5043. if (data) {
  5044. data->score = score;
  5045. data->result_type = final_proc_type->Proc.results;
  5046. data->gen_entity = gen_entity;
  5047. }
  5048. return CallArgumentError_MultipleVariadicExpand;
  5049. }
  5050. }
  5051. score += eval_param_and_score(c, o, t, err, true, nullptr, show_error);
  5052. }
  5053. }
  5054. if (data) {
  5055. data->score = score;
  5056. data->result_type = final_proc_type->Proc.results;
  5057. data->gen_entity = gen_entity;
  5058. Ast *proc_lit = nullptr;
  5059. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5060. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5061. if (vp && vp->kind == Ast_ProcLit) {
  5062. proc_lit = vp;
  5063. }
  5064. }
  5065. if (proc_lit == nullptr) {
  5066. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5067. }
  5068. }
  5069. return err;
  5070. }
  5071. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5072. GB_ASSERT(ce != nullptr);
  5073. if (ce->args.count == 0) {
  5074. return false;
  5075. }
  5076. return ce->args[0]->kind == Ast_FieldValue;
  5077. }
  5078. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5079. Entity **lhs = nullptr;
  5080. isize lhs_count = -1;
  5081. if (proc_type == nullptr) {
  5082. return nullptr;
  5083. }
  5084. GB_ASSERT(is_type_proc(proc_type));
  5085. TypeProc *pt = &base_type(proc_type)->Proc;
  5086. *is_variadic = pt->variadic;
  5087. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5088. if (pt->params != nullptr) {
  5089. lhs = pt->params->Tuple.variables.data;
  5090. lhs_count = pt->params->Tuple.variables.count;
  5091. }
  5092. } else {
  5093. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5094. if (pt->params == nullptr) {
  5095. lhs_count = 0;
  5096. } else {
  5097. lhs_count = pt->params->Tuple.variables.count;
  5098. }
  5099. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5100. for (isize i = 0; i < lhs_count; i++) {
  5101. Entity *e = pt->params->Tuple.variables[i];
  5102. if (!is_type_polymorphic(e->type)) {
  5103. lhs[i] = e;
  5104. }
  5105. }
  5106. }
  5107. if (lhs_count_) *lhs_count_ = lhs_count;
  5108. return lhs;
  5109. }
  5110. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5111. if (clauses != nullptr) {
  5112. for (Ast *clause : *clauses) {
  5113. Operand o = {};
  5114. check_expr(ctx, &o, clause);
  5115. if (o.mode != Addressing_Constant) {
  5116. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5117. if (print_err && call_expr) error(call_expr, "at caller location");
  5118. return false;
  5119. } else if (o.value.kind != ExactValue_Bool) {
  5120. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5121. if (print_err && call_expr) error(call_expr, "at caller location");
  5122. return false;
  5123. } else if (!o.value.value_bool) {
  5124. if (print_err) {
  5125. ERROR_BLOCK();
  5126. gbString str = expr_to_string(clause);
  5127. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5128. gb_string_free(str);
  5129. if (scope != nullptr) {
  5130. isize print_count = 0;
  5131. for (auto const &entry : scope->elements) {
  5132. Entity *e = entry.value;
  5133. switch (e->kind) {
  5134. case Entity_TypeName: {
  5135. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5136. gbString str = type_to_string(e->type);
  5137. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5138. gb_string_free(str);
  5139. print_count += 1;
  5140. break;
  5141. }
  5142. case Entity_Constant: {
  5143. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5144. gbString str = exact_value_to_string(e->Constant.value);
  5145. if (is_type_untyped(e->type)) {
  5146. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5147. } else {
  5148. gbString t = type_to_string(e->type);
  5149. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5150. gb_string_free(t);
  5151. }
  5152. gb_string_free(str);
  5153. print_count += 1;
  5154. break;
  5155. }
  5156. }
  5157. }
  5158. }
  5159. if (call_expr) error(call_expr, "at caller location");
  5160. }
  5161. return false;
  5162. }
  5163. }
  5164. }
  5165. return true;
  5166. }
  5167. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5168. bool success = true;
  5169. type = base_type(type);
  5170. if (named_args.count > 0) {
  5171. TypeProc *pt = nullptr;
  5172. if (is_type_proc(type)) {
  5173. pt = &type->Proc;
  5174. }
  5175. for_array(i, named_args) {
  5176. Ast *arg = named_args[i];
  5177. if (arg->kind != Ast_FieldValue) {
  5178. if (show_error) {
  5179. error(arg, "Expected a 'field = value'");
  5180. }
  5181. return false;
  5182. }
  5183. ast_node(fv, FieldValue, arg);
  5184. if (fv->field->kind != Ast_Ident) {
  5185. if (show_error) {
  5186. gbString expr_str = expr_to_string(fv->field);
  5187. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5188. gb_string_free(expr_str);
  5189. }
  5190. success = false;
  5191. continue;
  5192. }
  5193. String key = fv->field->Ident.token.string;
  5194. Ast *value = fv->value;
  5195. Type *type_hint = nullptr;
  5196. if (pt) {
  5197. isize param_index = lookup_procedure_parameter(pt, key);
  5198. if (param_index < 0) {
  5199. if (show_error) {
  5200. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5201. }
  5202. success = false;
  5203. continue;
  5204. }
  5205. Entity *e = pt->params->Tuple.variables[param_index];
  5206. if (!is_type_polymorphic(e->type)) {
  5207. type_hint = e->type;
  5208. }
  5209. }
  5210. Operand o = {};
  5211. check_expr_with_type_hint(c, &o, value, type_hint);
  5212. if (o.mode == Addressing_Invalid) {
  5213. success = false;
  5214. }
  5215. array_add(named_operands, o);
  5216. }
  5217. }
  5218. return success;
  5219. }
  5220. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5221. Entity *e, Type *proc_type,
  5222. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5223. CallArgumentErrorMode show_error_mode,
  5224. CallArgumentData *data) {
  5225. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5226. Ast *ident = operand->expr;
  5227. while (ident->kind == Ast_SelectorExpr) {
  5228. Ast *s = ident->SelectorExpr.selector;
  5229. ident = s;
  5230. }
  5231. if (e == nullptr) {
  5232. e = entity_of_node(ident);
  5233. if (e != nullptr) {
  5234. proc_type = e->type;
  5235. }
  5236. }
  5237. GB_ASSERT(proc_type != nullptr);
  5238. proc_type = base_type(proc_type);
  5239. GB_ASSERT(proc_type->kind == Type_Proc);
  5240. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5241. if (return_on_failure && err != CallArgumentError_None) {
  5242. return false;
  5243. }
  5244. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5245. if (!return_on_failure && entity_to_use != nullptr) {
  5246. add_entity_use(c, ident, entity_to_use);
  5247. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5248. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5249. }
  5250. if (data->gen_entity != nullptr) {
  5251. Entity *e = data->gen_entity;
  5252. DeclInfo *decl = data->gen_entity->decl_info;
  5253. CheckerContext ctx = *c;
  5254. ctx.scope = decl->scope;
  5255. ctx.decl = decl;
  5256. ctx.proc_name = e->token.string;
  5257. ctx.curr_proc_decl = decl;
  5258. ctx.curr_proc_sig = e->type;
  5259. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5260. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5261. if (return_on_failure) {
  5262. if (!ok) {
  5263. return false;
  5264. }
  5265. } else {
  5266. decl->where_clauses_evaluated = true;
  5267. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5268. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5269. }
  5270. if (is_type_proc(data->gen_entity->type)) {
  5271. Type *t = base_type(entity_to_use->type);
  5272. data->result_type = t->Proc.results;
  5273. }
  5274. }
  5275. }
  5276. return true;
  5277. }
  5278. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5279. ast_node(ce, CallExpr, call);
  5280. GB_ASSERT(ce->split_args != nullptr);
  5281. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5282. Slice<Ast *> const &named_args = ce->split_args->named;
  5283. CallArgumentData data = {};
  5284. data.result_type = t_invalid;
  5285. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5286. auto procs = proc_group_entities_cloned(c, *operand);
  5287. if (procs.count > 1) {
  5288. isize max_arg_count = positional_args.count + named_args.count;
  5289. for (Ast *arg : positional_args) {
  5290. // NOTE(bill): The only thing that may have multiple values
  5291. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5292. arg = strip_or_return_expr(arg);
  5293. if (arg && arg->kind == Ast_CallExpr) {
  5294. max_arg_count = ISIZE_MAX;
  5295. break;
  5296. }
  5297. }
  5298. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5299. // NOTE(bill): The only thing that may have multiple values
  5300. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5301. if (arg->kind == Ast_FieldValue) {
  5302. arg = strip_or_return_expr(arg->FieldValue.value);
  5303. if (arg && arg->kind == Ast_CallExpr) {
  5304. max_arg_count = ISIZE_MAX;
  5305. break;
  5306. }
  5307. }
  5308. }
  5309. // ignore named arguments first
  5310. for (Ast *arg : named_args) {
  5311. if (arg->kind != Ast_FieldValue) {
  5312. continue;
  5313. }
  5314. ast_node(fv, FieldValue, arg);
  5315. if (fv->field->kind != Ast_Ident) {
  5316. continue;
  5317. }
  5318. String key = fv->field->Ident.token.string;
  5319. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5320. Type *t = procs[proc_index]->type;
  5321. if (is_type_proc(t)) {
  5322. isize param_index = lookup_procedure_parameter(t, key);
  5323. if (param_index < 0) {
  5324. array_unordered_remove(&procs, proc_index);
  5325. }
  5326. }
  5327. }
  5328. }
  5329. if (procs.count == 0) {
  5330. // if any of the named arguments are wrong, the `procs` will be empty
  5331. // just start from scratch
  5332. array_free(&procs);
  5333. procs = proc_group_entities_cloned(c, *operand);
  5334. }
  5335. // filter by positional argument length
  5336. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5337. Entity *proc = procs[proc_index];
  5338. Type *pt = base_type(proc->type);
  5339. if (!(pt != nullptr && is_type_proc(pt))) {
  5340. proc_index++;
  5341. continue;
  5342. }
  5343. isize param_count = 0;
  5344. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5345. if (param_count_excluding_defaults > max_arg_count) {
  5346. array_unordered_remove(&procs, proc_index);
  5347. continue;
  5348. }
  5349. proc_index++;
  5350. }
  5351. }
  5352. Entity **lhs = nullptr;
  5353. isize lhs_count = -1;
  5354. bool is_variadic = false;
  5355. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5356. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5357. defer (array_free(&positional_operands));
  5358. defer (array_free(&named_operands));
  5359. if (procs.count == 1) {
  5360. Entity *e = procs[0];
  5361. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5362. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5363. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5364. check_call_arguments_single(c, call, operand,
  5365. e, e->type,
  5366. positional_operands, named_operands,
  5367. CallArgumentErrorMode::ShowErrors,
  5368. &data);
  5369. }
  5370. return data;
  5371. }
  5372. {
  5373. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5374. // where the same positional parameter has the same type value (and ellipsis)
  5375. isize proc_arg_count = -1;
  5376. for (Entity *p : procs) {
  5377. Type *pt = base_type(p->type);
  5378. if (pt != nullptr && is_type_proc(pt)) {
  5379. if (proc_arg_count < 0) {
  5380. proc_arg_count = pt->Proc.param_count;
  5381. } else {
  5382. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5383. }
  5384. }
  5385. }
  5386. if (proc_arg_count >= 0) {
  5387. lhs_count = proc_arg_count;
  5388. if (lhs_count > 0) {
  5389. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5390. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5391. Entity *e = nullptr;
  5392. for (Entity *p : procs) {
  5393. Type *pt = base_type(p->type);
  5394. if (!(pt != nullptr && is_type_proc(pt))) {
  5395. continue;
  5396. }
  5397. if (e == nullptr) {
  5398. e = pt->Proc.params->Tuple.variables[param_index];
  5399. } else {
  5400. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5401. if (e == f) {
  5402. continue;
  5403. }
  5404. if (are_types_identical(e->type, f->type)) {
  5405. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5406. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5407. if (ee == fe) {
  5408. continue;
  5409. }
  5410. }
  5411. // NOTE(bill): Entities are not close enough to be used
  5412. e = nullptr;
  5413. break;
  5414. }
  5415. }
  5416. lhs[param_index] = e;
  5417. }
  5418. }
  5419. }
  5420. }
  5421. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5422. for_array(i, named_args) {
  5423. Ast *arg = named_args[i];
  5424. if (arg->kind != Ast_FieldValue) {
  5425. error(arg, "Expected a 'field = value'");
  5426. return data;
  5427. }
  5428. ast_node(fv, FieldValue, arg);
  5429. if (fv->field->kind != Ast_Ident) {
  5430. gbString expr_str = expr_to_string(fv->field);
  5431. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5432. gb_string_free(expr_str);
  5433. return data;
  5434. }
  5435. String key = fv->field->Ident.token.string;
  5436. Ast *value = fv->value;
  5437. Type *type_hint = nullptr;
  5438. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5439. Entity *e = lhs[lhs_idx];
  5440. if (e != nullptr && e->token.string == key &&
  5441. !is_type_polymorphic(e->type)) {
  5442. type_hint = e->type;
  5443. break;
  5444. }
  5445. }
  5446. Operand o = {};
  5447. check_expr_with_type_hint(c, &o, value, type_hint);
  5448. array_add(&named_operands, o);
  5449. }
  5450. gb_free(heap_allocator(), lhs);
  5451. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5452. defer (array_free(&valids));
  5453. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5454. defer (array_free(&proc_entities));
  5455. for (Entity *proc : procs) {
  5456. array_add(&proc_entities, proc);
  5457. }
  5458. gbString expr_name = expr_to_string(operand->expr);
  5459. defer (gb_string_free(expr_name));
  5460. for_array(i, procs) {
  5461. Entity *p = procs[i];
  5462. Type *pt = base_type(p->type);
  5463. if (pt != nullptr && is_type_proc(pt)) {
  5464. CallArgumentData data = {};
  5465. CheckerContext ctx = *c;
  5466. ctx.no_polymorphic_errors = true;
  5467. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5468. ctx.hide_polymorphic_errors = true;
  5469. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5470. p, pt,
  5471. positional_operands, named_operands,
  5472. CallArgumentErrorMode::NoErrors,
  5473. &data);
  5474. if (!is_a_candidate) {
  5475. continue;
  5476. }
  5477. isize index = i;
  5478. ValidIndexAndScore item = {};
  5479. item.score = data.score;
  5480. if (data.gen_entity != nullptr) {
  5481. array_add(&proc_entities, data.gen_entity);
  5482. index = proc_entities.count-1;
  5483. // prefer non-polymorphic procedures over polymorphic
  5484. item.score += assign_score_function(1);
  5485. }
  5486. item.index = index;
  5487. array_add(&valids, item);
  5488. }
  5489. }
  5490. if (valids.count > 1) {
  5491. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  5492. i64 best_score = valids[0].score;
  5493. Entity *best_entity = proc_entities[valids[0].index];
  5494. GB_ASSERT(best_entity != nullptr);
  5495. for (isize i = 1; i < valids.count; i++) {
  5496. if (best_score > valids[i].score) {
  5497. valids.count = i;
  5498. break;
  5499. }
  5500. if (best_entity == proc_entities[valids[i].index]) {
  5501. valids.count = i;
  5502. break;
  5503. }
  5504. }
  5505. }
  5506. auto print_argument_types = [&]() {
  5507. error_line("\tGiven argument types: (");
  5508. isize i = 0;
  5509. for (Operand const &o : positional_operands) {
  5510. if (i++ > 0) error_line(", ");
  5511. gbString type = type_to_string(o.type);
  5512. defer (gb_string_free(type));
  5513. error_line("%s", type);
  5514. }
  5515. for (Operand const &o : named_operands) {
  5516. if (i++ > 0) error_line(", ");
  5517. gbString type = type_to_string(o.type);
  5518. defer (gb_string_free(type));
  5519. if (i < ce->split_args->named.count) {
  5520. Ast *named_field = ce->split_args->named[i];
  5521. ast_node(fv, FieldValue, named_field);
  5522. gbString field = expr_to_string(fv->field);
  5523. defer (gb_string_free(field));
  5524. error_line("%s = %s", field, type);
  5525. } else {
  5526. error_line("%s", type);
  5527. }
  5528. }
  5529. error_line(")\n");
  5530. };
  5531. if (valids.count == 0) {
  5532. begin_error_block();
  5533. defer (end_error_block());
  5534. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5535. if (positional_operands.count == 0 && named_operands.count == 0) {
  5536. error_line("\tNo given arguments\n");
  5537. } else {
  5538. print_argument_types();
  5539. }
  5540. if (procs.count == 0) {
  5541. procs = proc_group_entities_cloned(c, *operand);
  5542. }
  5543. if (procs.count > 0) {
  5544. error_line("Did you mean to use one of the following:\n");
  5545. }
  5546. isize max_name_length = 0;
  5547. isize max_type_length = 0;
  5548. for (Entity *proc : procs) {
  5549. Type *t = base_type(proc->type);
  5550. if (t == t_invalid) continue;
  5551. String prefix = {};
  5552. String prefix_sep = {};
  5553. if (proc->pkg) {
  5554. prefix = proc->pkg->name;
  5555. prefix_sep = str_lit(".");
  5556. }
  5557. String name = proc->token.string;
  5558. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5559. gbString pt;
  5560. if (t->Proc.node != nullptr) {
  5561. pt = expr_to_string(t->Proc.node);
  5562. } else {
  5563. pt = type_to_string(t);
  5564. }
  5565. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5566. gb_string_free(pt);
  5567. }
  5568. isize max_spaces = gb_max(max_name_length, max_type_length);
  5569. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5570. for (isize i = 0; i < max_spaces; i++) {
  5571. spaces[i] = ' ';
  5572. }
  5573. spaces[max_spaces] = 0;
  5574. for (Entity *proc : procs) {
  5575. TokenPos pos = proc->token.pos;
  5576. Type *t = base_type(proc->type);
  5577. if (t == t_invalid) continue;
  5578. GB_ASSERT(t->kind == Type_Proc);
  5579. gbString pt;
  5580. defer (gb_string_free(pt));
  5581. if (t->Proc.node != nullptr) {
  5582. pt = expr_to_string(t->Proc.node);
  5583. } else {
  5584. pt = type_to_string(t);
  5585. }
  5586. String prefix = {};
  5587. String prefix_sep = {};
  5588. if (proc->pkg) {
  5589. prefix = proc->pkg->name;
  5590. prefix_sep = str_lit(".");
  5591. }
  5592. String name = proc->token.string;
  5593. isize len = prefix.len + prefix_sep.len + name.len;
  5594. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5595. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5596. char const *sep = "::";
  5597. if (proc->kind == Entity_Variable) {
  5598. sep = ":=";
  5599. }
  5600. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5601. LIT(prefix), LIT(prefix_sep), LIT(name),
  5602. name_padding, spaces,
  5603. sep,
  5604. pt,
  5605. type_padding, spaces,
  5606. token_pos_to_string(pos)
  5607. );
  5608. }
  5609. if (procs.count > 0) {
  5610. error_line("\n");
  5611. }
  5612. data.result_type = t_invalid;
  5613. } else if (valids.count > 1) {
  5614. begin_error_block();
  5615. defer (end_error_block());
  5616. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5617. print_argument_types();
  5618. for (auto const &valid : valids) {
  5619. Entity *proc = proc_entities[valid.index];
  5620. GB_ASSERT(proc != nullptr);
  5621. TokenPos pos = proc->token.pos;
  5622. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5623. gbString pt = nullptr;
  5624. defer (gb_string_free(pt));
  5625. if (t->Proc.node != nullptr) {
  5626. pt = expr_to_string(t->Proc.node);
  5627. } else {
  5628. pt = type_to_string(t);
  5629. }
  5630. String name = proc->token.string;
  5631. char const *sep = "::";
  5632. if (proc->kind == Entity_Variable) {
  5633. sep = ":=";
  5634. }
  5635. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5636. if (proc->decl_info->proc_lit != nullptr) {
  5637. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5638. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5639. if (pl->where_token.kind != Token_Invalid) {
  5640. error_line("\n\t\twhere ");
  5641. for_array(j, pl->where_clauses) {
  5642. Ast *clause = pl->where_clauses[j];
  5643. if (j != 0) {
  5644. error_line("\t\t ");
  5645. }
  5646. gbString str = expr_to_string(clause);
  5647. error_line("%s", str);
  5648. gb_string_free(str);
  5649. if (j != pl->where_clauses.count-1) {
  5650. error_line(",");
  5651. }
  5652. }
  5653. error_line("\n\t");
  5654. }
  5655. }
  5656. error_line("at %s\n", token_pos_to_string(pos));
  5657. }
  5658. data.result_type = t_invalid;
  5659. } else {
  5660. GB_ASSERT(valids.count == 1);
  5661. Ast *ident = operand->expr;
  5662. while (ident->kind == Ast_SelectorExpr) {
  5663. Ast *s = ident->SelectorExpr.selector;
  5664. ident = s;
  5665. }
  5666. Entity *e = proc_entities[valids[0].index];
  5667. GB_ASSERT(e != nullptr);
  5668. Array<Operand> named_operands = {};
  5669. check_call_arguments_single(c, call, operand,
  5670. e, e->type,
  5671. positional_operands, named_operands,
  5672. CallArgumentErrorMode::ShowErrors,
  5673. &data);
  5674. return data;
  5675. }
  5676. return data;
  5677. }
  5678. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5679. Type *proc_type = nullptr;
  5680. CallArgumentData data = {};
  5681. data.result_type = t_invalid;
  5682. proc_type = base_type(operand->type);
  5683. TypeProc *pt = nullptr;
  5684. if (proc_type) {
  5685. pt = &proc_type->Proc;
  5686. }
  5687. TEMPORARY_ALLOCATOR_GUARD();
  5688. ast_node(ce, CallExpr, call);
  5689. bool any_failure = false;
  5690. // Split positional and named args into separate arrays/slices
  5691. Slice<Ast *> positional_args = {};
  5692. Slice<Ast *> named_args = {};
  5693. if (ce->split_args == nullptr) {
  5694. positional_args = ce->args;
  5695. for (isize i = 0; i < ce->args.count; i++) {
  5696. Ast *arg = ce->args.data[i];
  5697. if (arg->kind == Ast_FieldValue) {
  5698. positional_args.count = i;
  5699. break;
  5700. }
  5701. }
  5702. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5703. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5704. split_args->positional = positional_args;
  5705. split_args->named = named_args;
  5706. ce->split_args = split_args;
  5707. } else {
  5708. positional_args = ce->split_args->positional;
  5709. named_args = ce->split_args->named;
  5710. }
  5711. if (operand->mode == Addressing_ProcGroup) {
  5712. return check_call_arguments_proc_group(c, operand, call);
  5713. }
  5714. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5715. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5716. defer (array_free(&positional_operands));
  5717. defer (array_free(&named_operands));
  5718. if (positional_args.count > 0) {
  5719. isize lhs_count = -1;
  5720. bool is_variadic = false;
  5721. Entity **lhs = nullptr;
  5722. if (pt != nullptr) {
  5723. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5724. }
  5725. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5726. }
  5727. if (named_args.count > 0) {
  5728. for_array(i, named_args) {
  5729. Ast *arg = named_args[i];
  5730. if (arg->kind != Ast_FieldValue) {
  5731. error(arg, "Expected a 'field = value'");
  5732. return data;
  5733. }
  5734. ast_node(fv, FieldValue, arg);
  5735. if (fv->field->kind != Ast_Ident) {
  5736. gbString expr_str = expr_to_string(fv->field);
  5737. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5738. any_failure = true;
  5739. gb_string_free(expr_str);
  5740. continue;
  5741. }
  5742. String key = fv->field->Ident.token.string;
  5743. Ast *value = fv->value;
  5744. isize param_index = lookup_procedure_parameter(pt, key);
  5745. Type *type_hint = nullptr;
  5746. if (param_index >= 0) {
  5747. Entity *e = pt->params->Tuple.variables[param_index];
  5748. type_hint = e->type;
  5749. }
  5750. Operand o = {};
  5751. check_expr_with_type_hint(c, &o, value, type_hint);
  5752. if (o.mode == Addressing_Invalid) {
  5753. any_failure = true;
  5754. }
  5755. array_add(&named_operands, o);
  5756. }
  5757. }
  5758. if (!any_failure) {
  5759. check_call_arguments_single(c, call, operand,
  5760. nullptr, proc_type,
  5761. positional_operands, named_operands,
  5762. CallArgumentErrorMode::ShowErrors,
  5763. &data);
  5764. } else if (pt) {
  5765. data.result_type = pt->results;
  5766. }
  5767. return data;
  5768. }
  5769. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5770. if (!is_type_polymorphic_record(t)) {
  5771. return -1;
  5772. }
  5773. TypeTuple *params = get_record_polymorphic_params(t);
  5774. if (params == nullptr) {
  5775. return -1;
  5776. }
  5777. for_array(i, params->variables) {
  5778. Entity *e = params->variables[i];
  5779. String name = e->token.string;
  5780. if (is_blank_ident(name)) {
  5781. continue;
  5782. }
  5783. if (name == parameter_name) {
  5784. return i;
  5785. }
  5786. }
  5787. return -1;
  5788. }
  5789. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5790. ast_node(ce, CallExpr, call);
  5791. Type *original_type = operand->type;
  5792. GB_ASSERT(is_type_polymorphic_record(original_type));
  5793. bool show_error = true;
  5794. Array<Operand> operands = {};
  5795. defer (array_free(&operands));
  5796. bool named_fields = false;
  5797. {
  5798. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5799. auto prev_type_path = c->type_path;
  5800. c->type_path = new_checker_type_path();
  5801. defer ({
  5802. destroy_checker_type_path(c->type_path);
  5803. c->type_path = prev_type_path;
  5804. });
  5805. if (is_call_expr_field_value(ce)) {
  5806. named_fields = true;
  5807. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5808. for_array(i, ce->args) {
  5809. Ast *arg = ce->args[i];
  5810. ast_node(fv, FieldValue, arg);
  5811. if (fv->field->kind == Ast_Ident) {
  5812. String name = fv->field->Ident.token.string;
  5813. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5814. if (index >= 0) {
  5815. TypeTuple *params = get_record_polymorphic_params(original_type);
  5816. Entity *e = params->variables[i];
  5817. if (e->kind == Entity_Constant) {
  5818. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5819. continue;
  5820. }
  5821. }
  5822. }
  5823. check_expr_or_type(c, &operands[i], fv->value);
  5824. }
  5825. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5826. if (vari_expand) {
  5827. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5828. }
  5829. } else {
  5830. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5831. Entity **lhs = nullptr;
  5832. isize lhs_count = -1;
  5833. TypeTuple *params = get_record_polymorphic_params(original_type);
  5834. if (params != nullptr) {
  5835. lhs = params->variables.data;
  5836. lhs_count = params->variables.count;
  5837. }
  5838. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  5839. }
  5840. }
  5841. CallArgumentError err = CallArgumentError_None;
  5842. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5843. isize param_count = tuple->variables.count;
  5844. isize minimum_param_count = param_count;
  5845. for (; minimum_param_count > 0; minimum_param_count--) {
  5846. Entity *e = tuple->variables[minimum_param_count-1];
  5847. if (e->kind != Entity_Constant) {
  5848. break;
  5849. }
  5850. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5851. break;
  5852. }
  5853. }
  5854. Array<Operand> ordered_operands = operands;
  5855. if (!named_fields) {
  5856. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5857. array_copy(&ordered_operands, operands, 0);
  5858. } else {
  5859. TEMPORARY_ALLOCATOR_GUARD();
  5860. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5861. // LEAK(bill)
  5862. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5863. for_array(i, ce->args) {
  5864. Ast *arg = ce->args[i];
  5865. ast_node(fv, FieldValue, arg);
  5866. if (fv->field->kind != Ast_Ident) {
  5867. if (show_error) {
  5868. gbString expr_str = expr_to_string(fv->field);
  5869. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5870. gb_string_free(expr_str);
  5871. }
  5872. err = CallArgumentError_InvalidFieldValue;
  5873. continue;
  5874. }
  5875. String name = fv->field->Ident.token.string;
  5876. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5877. if (index < 0) {
  5878. if (show_error) {
  5879. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5880. }
  5881. err = CallArgumentError_ParameterNotFound;
  5882. continue;
  5883. }
  5884. if (visited[index]) {
  5885. if (show_error) {
  5886. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5887. }
  5888. err = CallArgumentError_DuplicateParameter;
  5889. continue;
  5890. }
  5891. visited[index] = true;
  5892. ordered_operands[index] = operands[i];
  5893. }
  5894. for (isize i = 0; i < param_count; i++) {
  5895. if (!visited[i]) {
  5896. Entity *e = tuple->variables[i];
  5897. if (is_blank_ident(e->token)) {
  5898. continue;
  5899. }
  5900. if (show_error) {
  5901. if (e->kind == Entity_TypeName) {
  5902. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5903. LIT(e->token.string));
  5904. } else {
  5905. gbString str = type_to_string(e->type);
  5906. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5907. LIT(e->token.string), str);
  5908. gb_string_free(str);
  5909. }
  5910. }
  5911. err = CallArgumentError_ParameterMissing;
  5912. }
  5913. }
  5914. }
  5915. if (err != 0) {
  5916. operand->mode = Addressing_Invalid;
  5917. return err;
  5918. }
  5919. while (ordered_operands.count > 0) {
  5920. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5921. break;
  5922. }
  5923. array_pop(&ordered_operands);
  5924. }
  5925. if (minimum_param_count != param_count) {
  5926. if (param_count < ordered_operands.count) {
  5927. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  5928. err = CallArgumentError_TooManyArguments;
  5929. } else if (minimum_param_count > ordered_operands.count) {
  5930. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  5931. err = CallArgumentError_TooFewArguments;
  5932. }
  5933. } else {
  5934. if (param_count < ordered_operands.count) {
  5935. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5936. err = CallArgumentError_TooManyArguments;
  5937. } else if (param_count > ordered_operands.count) {
  5938. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5939. err = CallArgumentError_TooFewArguments;
  5940. }
  5941. }
  5942. if (err != 0) {
  5943. return err;
  5944. }
  5945. if (minimum_param_count != param_count) {
  5946. array_resize(&ordered_operands, param_count);
  5947. isize missing_count = 0;
  5948. // NOTE(bill): Replace missing operands with the default values (if possible)
  5949. for_array(i, ordered_operands) {
  5950. Operand *o = &ordered_operands[i];
  5951. if (o->expr == nullptr) {
  5952. Entity *e = tuple->variables[i];
  5953. if (e->kind == Entity_Constant) {
  5954. missing_count += 1;
  5955. o->mode = Addressing_Constant;
  5956. o->type = default_type(e->type);
  5957. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  5958. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  5959. o->value = e->Constant.param_value.value;
  5960. }
  5961. } else if (e->kind == Entity_TypeName) {
  5962. missing_count += 1;
  5963. o->mode = Addressing_Type;
  5964. o->type = e->type;
  5965. o->expr = e->identifier;
  5966. }
  5967. }
  5968. }
  5969. }
  5970. isize oo_count = gb_min(param_count, ordered_operands.count);
  5971. i64 score = 0;
  5972. for (isize i = 0; i < oo_count; i++) {
  5973. Entity *e = tuple->variables[i];
  5974. Operand *o = &ordered_operands[i];
  5975. if (o->mode == Addressing_Invalid) {
  5976. continue;
  5977. }
  5978. if (e->kind == Entity_TypeName) {
  5979. if (o->mode != Addressing_Type) {
  5980. if (show_error) {
  5981. gbString expr = expr_to_string(o->expr);
  5982. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  5983. gb_string_free(expr);
  5984. }
  5985. err = CallArgumentError_WrongTypes;
  5986. }
  5987. if (are_types_identical(e->type, o->type)) {
  5988. score += assign_score_function(1);
  5989. } else {
  5990. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5991. }
  5992. } else {
  5993. i64 s = 0;
  5994. if (o->type->kind == Type_Generic) {
  5995. // Polymorphic name!
  5996. score += assign_score_function(1);
  5997. continue;
  5998. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  5999. if (show_error) {
  6000. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6001. }
  6002. err = CallArgumentError_WrongTypes;
  6003. }
  6004. o->type = e->type;
  6005. if (o->mode != Addressing_Constant) {
  6006. bool valid = false;
  6007. if (is_type_proc(o->type)) {
  6008. Entity *proc_entity = entity_from_expr(o->expr);
  6009. valid = proc_entity != nullptr;
  6010. }
  6011. if (!valid) {
  6012. if (show_error) {
  6013. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6014. }
  6015. err = CallArgumentError_NoneConstantParameter;
  6016. }
  6017. }
  6018. score += s;
  6019. }
  6020. // NOTE(bill): Add type info the parameters
  6021. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6022. // add_type_info_type(c, o->type);
  6023. }
  6024. if (show_error && err) {
  6025. return err;
  6026. }
  6027. {
  6028. bool failure = false;
  6029. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  6030. if (found_entity) {
  6031. operand->mode = Addressing_Type;
  6032. operand->type = found_entity->type;
  6033. return err;
  6034. }
  6035. CheckerContext ctx = *c;
  6036. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6037. ctx.scope = polymorphic_record_parent_scope(original_type);
  6038. GB_ASSERT(ctx.scope != nullptr);
  6039. Type *bt = base_type(original_type);
  6040. String generated_name = make_string_c(expr_to_string(call));
  6041. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6042. if (bt->kind == Type_Struct) {
  6043. Ast *node = clone_ast(bt->Struct.node);
  6044. Type *struct_type = alloc_type_struct();
  6045. struct_type->Struct.node = node;
  6046. struct_type->Struct.polymorphic_parent = original_type;
  6047. set_base_type(named_type, struct_type);
  6048. check_open_scope(&ctx, node);
  6049. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6050. check_close_scope(&ctx);
  6051. } else if (bt->kind == Type_Union) {
  6052. Ast *node = clone_ast(bt->Union.node);
  6053. Type *union_type = alloc_type_union();
  6054. union_type->Union.node = node;
  6055. union_type->Union.polymorphic_parent = original_type;
  6056. set_base_type(named_type, union_type);
  6057. check_open_scope(&ctx, node);
  6058. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6059. check_close_scope(&ctx);
  6060. } else {
  6061. GB_PANIC("Unsupported parametric polymorphic record type");
  6062. }
  6063. bt = base_type(named_type);
  6064. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6065. GB_ASSERT(original_type->kind == Type_Named);
  6066. Entity *e = original_type->Named.type_name;
  6067. GB_ASSERT(e->kind == Entity_TypeName);
  6068. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6069. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6070. Type *params = nullptr;
  6071. switch (bt->kind) {
  6072. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6073. case Type_Union: params = bt->Union.polymorphic_params; break;
  6074. }
  6075. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6076. Entity *v = params->Tuple.variables[i];
  6077. String name = v->token.string;
  6078. if (i > 0) {
  6079. s = gb_string_append_fmt(s, ", ");
  6080. }
  6081. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6082. if (v->kind == Entity_TypeName) {
  6083. if (v->type->kind != Type_Generic) {
  6084. s = gb_string_append_fmt(s, "=");
  6085. s = write_type_to_string(s, v->type, false);
  6086. }
  6087. } else if (v->kind == Entity_Constant) {
  6088. s = gb_string_append_fmt(s, "=");
  6089. s = write_exact_value_to_string(s, v->Constant.value);
  6090. }
  6091. }
  6092. s = gb_string_append_fmt(s, ")");
  6093. String new_name = make_string_c(s);
  6094. named_type->Named.name = new_name;
  6095. if (named_type->Named.type_name) {
  6096. named_type->Named.type_name->token.string = new_name;
  6097. }
  6098. }
  6099. operand->mode = Addressing_Type;
  6100. operand->type = named_type;
  6101. }
  6102. return err;
  6103. }
  6104. // returns true on success
  6105. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6106. bool success = true;
  6107. if (args.count > 0) {
  6108. if (allow_mixed) {
  6109. bool was_named = false;
  6110. for (Ast *arg : args) {
  6111. if (was_named && arg->kind != Ast_FieldValue) {
  6112. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6113. success = false;
  6114. break;
  6115. }
  6116. was_named = was_named || arg->kind == Ast_FieldValue;
  6117. }
  6118. } else {
  6119. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6120. for (Ast *arg : args) {
  6121. bool mix = false;
  6122. if (first_is_field_value) {
  6123. mix = arg->kind != Ast_FieldValue;
  6124. } else {
  6125. mix = arg->kind == Ast_FieldValue;
  6126. }
  6127. if (mix) {
  6128. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6129. success = false;
  6130. }
  6131. }
  6132. }
  6133. }
  6134. return success;
  6135. }
  6136. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6137. operand->mode = Addressing_Invalid; \
  6138. operand->expr = call; \
  6139. return Expr_Stmt; \
  6140. }
  6141. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6142. if (proc != nullptr &&
  6143. proc->kind == Ast_BasicDirective) {
  6144. ast_node(bd, BasicDirective, proc);
  6145. String name = bd->name.string;
  6146. if (
  6147. name == "location" ||
  6148. name == "assert" ||
  6149. name == "panic" ||
  6150. name == "defined" ||
  6151. name == "config" ||
  6152. name == "load" ||
  6153. name == "load_hash" ||
  6154. name == "load_or"
  6155. ) {
  6156. operand->mode = Addressing_Builtin;
  6157. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6158. operand->expr = proc;
  6159. operand->type = t_invalid;
  6160. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6161. } else {
  6162. error(proc, "Unknown directive: #%.*s", LIT(name));
  6163. operand->expr = proc;
  6164. operand->type = t_invalid;
  6165. operand->mode = Addressing_Invalid;
  6166. return Expr_Expr;
  6167. }
  6168. if (inlining != ProcInlining_none) {
  6169. error(call, "Inlining operators are not allowed on built-in procedures");
  6170. }
  6171. } else {
  6172. if (proc != nullptr) {
  6173. check_expr_or_type(c, operand, proc);
  6174. } else {
  6175. GB_ASSERT(operand->expr != nullptr);
  6176. }
  6177. }
  6178. if (operand->mode == Addressing_Invalid) {
  6179. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6180. for (Ast *arg : args) {
  6181. if (arg->kind == Ast_FieldValue) {
  6182. arg = arg->FieldValue.value;
  6183. }
  6184. check_expr_base(c, operand, arg, nullptr);
  6185. }
  6186. operand->mode = Addressing_Invalid;
  6187. operand->expr = call;
  6188. return Expr_Stmt;
  6189. }
  6190. if (operand->mode == Addressing_Type) {
  6191. Type *t = operand->type;
  6192. if (is_type_polymorphic_record(t)) {
  6193. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6194. if (!is_type_named(t)) {
  6195. gbString s = expr_to_string(operand->expr);
  6196. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6197. gb_string_free(s);
  6198. operand->mode = Addressing_Invalid;
  6199. operand->type = t_invalid;;
  6200. return Expr_Expr;
  6201. }
  6202. auto err = check_polymorphic_record_type(c, operand, call);
  6203. if (err == 0) {
  6204. Ast *ident = operand->expr;
  6205. while (ident->kind == Ast_SelectorExpr) {
  6206. Ast *s = ident->SelectorExpr.selector;
  6207. ident = s;
  6208. }
  6209. Type *ot = operand->type;
  6210. GB_ASSERT(ot->kind == Type_Named);
  6211. Entity *e = ot->Named.type_name;
  6212. add_entity_use(c, ident, e);
  6213. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6214. } else {
  6215. operand->mode = Addressing_Invalid;
  6216. operand->type = t_invalid;
  6217. }
  6218. } else {
  6219. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6220. operand->mode = Addressing_Invalid;
  6221. isize arg_count = args.count;
  6222. switch (arg_count) {
  6223. case 0:
  6224. {
  6225. gbString str = type_to_string(t);
  6226. error(call, "Missing argument in conversion to '%s'", str);
  6227. gb_string_free(str);
  6228. } break;
  6229. default:
  6230. {
  6231. gbString str = type_to_string(t);
  6232. error(call, "Too many arguments in conversion to '%s'", str);
  6233. gb_string_free(str);
  6234. } break;
  6235. case 1: {
  6236. Ast *arg = args[0];
  6237. if (arg->kind == Ast_FieldValue) {
  6238. error(call, "'field = value' cannot be used in a type conversion");
  6239. arg = arg->FieldValue.value;
  6240. // NOTE(bill): Carry on the cast regardless
  6241. }
  6242. check_expr_with_type_hint(c, operand, arg, t);
  6243. if (operand->mode != Addressing_Invalid) {
  6244. if (is_type_polymorphic(t)) {
  6245. error(call, "A polymorphic type cannot be used in a type conversion");
  6246. } else {
  6247. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6248. // as it assumes it is determining the type
  6249. check_cast(c, operand, t);
  6250. }
  6251. }
  6252. operand->type = t;
  6253. operand->expr = call;
  6254. if (operand->mode != Addressing_Invalid) {
  6255. update_untyped_expr_type(c, arg, t, false);
  6256. }
  6257. break;
  6258. }
  6259. }
  6260. }
  6261. return Expr_Expr;
  6262. }
  6263. if (operand->mode == Addressing_Builtin) {
  6264. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6265. i32 id = operand->builtin_id;
  6266. Entity *e = entity_of_node(operand->expr);
  6267. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6268. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6269. }
  6270. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6271. operand->mode = Addressing_Invalid;
  6272. operand->type = t_invalid;
  6273. }
  6274. operand->expr = call;
  6275. return builtin_procs[id].kind;
  6276. }
  6277. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6278. Entity *initial_entity = entity_of_node(operand->expr);
  6279. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6280. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6281. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6282. if (c->decl) {
  6283. c->decl->defer_used += 1;
  6284. }
  6285. }
  6286. add_entity_use(c, operand->expr, initial_entity);
  6287. }
  6288. if (operand->mode != Addressing_ProcGroup) {
  6289. Type *proc_type = base_type(operand->type);
  6290. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6291. bool valid_mode = is_operand_value(*operand);
  6292. if (!valid_type || !valid_mode) {
  6293. Ast *e = operand->expr;
  6294. gbString str = expr_to_string(e);
  6295. gbString type_str = type_to_string(operand->type);
  6296. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6297. gb_string_free(type_str);
  6298. gb_string_free(str);
  6299. operand->mode = Addressing_Invalid;
  6300. operand->expr = call;
  6301. return Expr_Stmt;
  6302. }
  6303. }
  6304. CallArgumentData data = check_call_arguments(c, operand, call);
  6305. Type *result_type = data.result_type;
  6306. gb_zero_item(operand);
  6307. operand->expr = call;
  6308. if (result_type == t_invalid) {
  6309. operand->mode = Addressing_Invalid;
  6310. operand->type = t_invalid;
  6311. return Expr_Stmt;
  6312. }
  6313. Type *pt = base_type(operand->type);
  6314. if (pt == nullptr) {
  6315. pt = t_invalid;
  6316. }
  6317. if (pt == t_invalid) {
  6318. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6319. pt = type_of_expr(operand->expr->CallExpr.proc);
  6320. }
  6321. if (pt == t_invalid && data.gen_entity) {
  6322. pt = data.gen_entity->type;
  6323. }
  6324. }
  6325. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6326. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6327. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6328. }
  6329. }
  6330. if (result_type == nullptr) {
  6331. operand->mode = Addressing_NoValue;
  6332. } else {
  6333. GB_ASSERT(is_type_tuple(result_type));
  6334. isize count = result_type->Tuple.variables.count;
  6335. switch (count) {
  6336. case 0:
  6337. operand->mode = Addressing_NoValue;
  6338. break;
  6339. case 1:
  6340. operand->mode = Addressing_Value;
  6341. operand->type = result_type->Tuple.variables[0]->type;
  6342. break;
  6343. default:
  6344. operand->mode = Addressing_Value;
  6345. operand->type = result_type;
  6346. break;
  6347. }
  6348. }
  6349. switch (inlining) {
  6350. case ProcInlining_inline:
  6351. if (proc != nullptr) {
  6352. Entity *e = entity_from_expr(proc);
  6353. if (e != nullptr && e->kind == Entity_Procedure) {
  6354. DeclInfo *decl = e->decl_info;
  6355. if (decl->proc_lit) {
  6356. ast_node(pl, ProcLit, decl->proc_lit);
  6357. if (pl->inlining == ProcInlining_no_inline) {
  6358. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6359. }
  6360. }
  6361. }
  6362. }
  6363. break;
  6364. case ProcInlining_no_inline:
  6365. break;
  6366. }
  6367. operand->expr = call;
  6368. {
  6369. Type *type = nullptr;
  6370. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6371. type = type_of_expr(operand->expr->CallExpr.proc);
  6372. }
  6373. if (type == nullptr) {
  6374. type = pt;
  6375. }
  6376. type = base_type(type);
  6377. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6378. operand->mode = Addressing_OptionalOk;
  6379. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6380. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6381. operand->expr->CallExpr.optional_ok_one = true;
  6382. }
  6383. }
  6384. }
  6385. return Expr_Expr;
  6386. }
  6387. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6388. check_expr_base(c, o, e, t);
  6389. check_not_tuple(c, o);
  6390. char const *err_str = nullptr;
  6391. switch (o->mode) {
  6392. case Addressing_NoValue:
  6393. err_str = "used as a value";
  6394. break;
  6395. case Addressing_Type:
  6396. if (t == nullptr || !is_type_typeid(t)) {
  6397. err_str = "is not an expression but a type, in this context it is ambiguous";
  6398. }
  6399. break;
  6400. case Addressing_Builtin:
  6401. err_str = "must be called";
  6402. break;
  6403. }
  6404. if (err_str != nullptr) {
  6405. gbString str = expr_to_string(e);
  6406. error(e, "'%s' %s", str, err_str);
  6407. gb_string_free(str);
  6408. o->mode = Addressing_Invalid;
  6409. }
  6410. }
  6411. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6412. switch (t->kind) {
  6413. case Type_Basic:
  6414. if (t->Basic.kind == Basic_string) {
  6415. if (o->mode == Addressing_Constant) {
  6416. *max_count = o->value.value_string.len;
  6417. }
  6418. if (o->mode != Addressing_Constant) {
  6419. o->mode = Addressing_Value;
  6420. }
  6421. o->type = t_u8;
  6422. return true;
  6423. } else if (t->Basic.kind == Basic_UntypedString) {
  6424. if (o->mode == Addressing_Constant) {
  6425. *max_count = o->value.value_string.len;
  6426. o->type = t_u8;
  6427. return true;
  6428. }
  6429. return false;
  6430. }
  6431. break;
  6432. case Type_MultiPointer:
  6433. o->type = t->MultiPointer.elem;
  6434. if (o->mode != Addressing_Constant) {
  6435. o->mode = Addressing_Variable;
  6436. }
  6437. return true;
  6438. case Type_Array:
  6439. *max_count = t->Array.count;
  6440. if (indirection) {
  6441. o->mode = Addressing_Variable;
  6442. } else if (o->mode != Addressing_Variable &&
  6443. o->mode != Addressing_Constant) {
  6444. o->mode = Addressing_Value;
  6445. }
  6446. o->type = t->Array.elem;
  6447. return true;
  6448. case Type_EnumeratedArray:
  6449. *max_count = t->EnumeratedArray.count;
  6450. if (indirection) {
  6451. o->mode = Addressing_Variable;
  6452. } else if (o->mode != Addressing_Variable &&
  6453. o->mode != Addressing_Constant) {
  6454. o->mode = Addressing_Value;
  6455. }
  6456. o->type = t->EnumeratedArray.elem;
  6457. return true;
  6458. case Type_Matrix:
  6459. *max_count = t->Matrix.column_count;
  6460. if (indirection) {
  6461. o->mode = Addressing_Variable;
  6462. } else if (o->mode != Addressing_Variable) {
  6463. o->mode = Addressing_Value;
  6464. }
  6465. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6466. return true;
  6467. case Type_Slice:
  6468. o->type = t->Slice.elem;
  6469. if (o->mode != Addressing_Constant) {
  6470. o->mode = Addressing_Variable;
  6471. }
  6472. return true;
  6473. case Type_RelativeMultiPointer:
  6474. {
  6475. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6476. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6477. o->type = pointer_type->MultiPointer.elem;
  6478. if (o->mode != Addressing_Constant) {
  6479. o->mode = Addressing_Variable;
  6480. }
  6481. }
  6482. return true;
  6483. case Type_DynamicArray:
  6484. o->type = t->DynamicArray.elem;
  6485. if (o->mode != Addressing_Constant) {
  6486. o->mode = Addressing_Variable;
  6487. }
  6488. return true;
  6489. case Type_Struct:
  6490. if (t->Struct.soa_kind != StructSoa_None) {
  6491. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6492. *max_count = t->Struct.soa_count;
  6493. }
  6494. o->type = t->Struct.soa_elem;
  6495. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  6496. o->mode = Addressing_SoaVariable;
  6497. } else {
  6498. o->mode = Addressing_Value;
  6499. }
  6500. return true;
  6501. }
  6502. return false;
  6503. }
  6504. if (is_type_pointer(original_type) && indirection) {
  6505. Type *ptr = base_type(original_type);
  6506. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6507. o->type = ptr->Pointer.elem;
  6508. o->mode = Addressing_Value;
  6509. return true;
  6510. }
  6511. }
  6512. return false;
  6513. }
  6514. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6515. if (is_type_untyped_uninit(x)) {
  6516. return true;
  6517. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6518. return true;
  6519. } else if (is_type_untyped_uninit(y)) {
  6520. return true;
  6521. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6522. return true;
  6523. }
  6524. return are_types_identical(x, y);
  6525. }
  6526. 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) {
  6527. if (!is_ast_range(node)) {
  6528. return false;
  6529. }
  6530. ast_node(ie, BinaryExpr, node);
  6531. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6532. if (x->mode == Addressing_Invalid) {
  6533. return false;
  6534. }
  6535. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6536. if (y->mode == Addressing_Invalid) {
  6537. return false;
  6538. }
  6539. convert_to_typed(c, x, y->type);
  6540. if (x->mode == Addressing_Invalid) {
  6541. return false;
  6542. }
  6543. convert_to_typed(c, y, x->type);
  6544. if (y->mode == Addressing_Invalid) {
  6545. return false;
  6546. }
  6547. convert_to_typed(c, x, default_type(y->type));
  6548. if (x->mode == Addressing_Invalid) {
  6549. return false;
  6550. }
  6551. convert_to_typed(c, y, default_type(x->type));
  6552. if (y->mode == Addressing_Invalid) {
  6553. return false;
  6554. }
  6555. if (!are_types_identical(x->type, y->type)) {
  6556. if (x->type != t_invalid &&
  6557. y->type != t_invalid) {
  6558. gbString xt = type_to_string(x->type);
  6559. gbString yt = type_to_string(y->type);
  6560. gbString expr_str = expr_to_string(x->expr);
  6561. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6562. gb_string_free(expr_str);
  6563. gb_string_free(yt);
  6564. gb_string_free(xt);
  6565. }
  6566. return false;
  6567. }
  6568. Type *type = x->type;
  6569. if (is_for_loop) {
  6570. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6571. error(ie->op, "Only numerical types are allowed within interval expressions");
  6572. return false;
  6573. }
  6574. } else {
  6575. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6576. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6577. return false;
  6578. }
  6579. }
  6580. if (x->mode == Addressing_Constant &&
  6581. y->mode == Addressing_Constant) {
  6582. ExactValue a = x->value;
  6583. ExactValue b = y->value;
  6584. GB_ASSERT(are_types_identical(x->type, y->type));
  6585. TokenKind op = Token_Lt;
  6586. switch (ie->op.kind) {
  6587. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6588. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6589. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6590. default: error(ie->op, "Invalid range operator"); break;
  6591. }
  6592. bool ok = compare_exact_values(op, a, b);
  6593. if (!ok) {
  6594. // TODO(bill): Better error message
  6595. error(ie->op, "Invalid interval range");
  6596. return false;
  6597. }
  6598. ExactValue inline_for_depth = exact_value_sub(b, a);
  6599. if (ie->op.kind != Token_RangeHalf) {
  6600. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6601. }
  6602. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6603. } else if (inline_for_depth_ != nullptr) {
  6604. error(ie->op, "Interval expressions must be constant");
  6605. return false;
  6606. }
  6607. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6608. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6609. return true;
  6610. }
  6611. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6612. if (is_operand_nil(*o)) {
  6613. return true;
  6614. }
  6615. Ast *expr = unparen_expr(o->expr);
  6616. if (expr != nullptr) {
  6617. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6618. if (e != nullptr && e->kind == Entity_Procedure) {
  6619. return true;
  6620. }
  6621. if (expr->kind == Ast_ProcLit) {
  6622. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6623. return true;
  6624. }
  6625. }
  6626. return o->mode == Addressing_Constant;
  6627. }
  6628. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6629. if (is_type_enum(th)) {
  6630. Type *enum_type = base_type(th);
  6631. GB_ASSERT(enum_type->kind == Type_Enum);
  6632. String name = ise->selector->Ident.token.string;
  6633. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6634. if (e == nullptr) {
  6635. return false;
  6636. }
  6637. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6638. GB_ASSERT(e->kind == Entity_Constant);
  6639. o->value = e->Constant.value;
  6640. o->mode = Addressing_Constant;
  6641. o->type = e->type;
  6642. return true;
  6643. }
  6644. if (is_type_union(th)) {
  6645. TEMPORARY_ALLOCATOR_GUARD();
  6646. Type *union_type = base_type(th);
  6647. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6648. for (Type *vt : union_type->Union.variants) {
  6649. Operand x = {};
  6650. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6651. array_add(&operands, x);
  6652. }
  6653. }
  6654. if (operands.count == 1) {
  6655. *o = operands[0];
  6656. return true;
  6657. }
  6658. }
  6659. return false;
  6660. }
  6661. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6662. ast_node(ise, ImplicitSelectorExpr, node);
  6663. o->type = t_invalid;
  6664. o->expr = node;
  6665. o->mode = Addressing_Invalid;
  6666. Type *th = type_hint;
  6667. if (th == nullptr) {
  6668. gbString str = expr_to_string(node);
  6669. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6670. gb_string_free(str);
  6671. return Expr_Expr;
  6672. }
  6673. o->type = th;
  6674. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6675. if (!ok) {
  6676. String name = ise->selector->Ident.token.string;
  6677. if (is_type_enum(th)) {
  6678. Type *bt = base_type(th);
  6679. GB_ASSERT(bt->kind == Type_Enum);
  6680. gbString typ = type_to_string(th);
  6681. defer (gb_string_free(typ));
  6682. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6683. check_did_you_mean_type(name, bt->Enum.fields);
  6684. } else {
  6685. gbString typ = type_to_string(th);
  6686. gbString str = expr_to_string(node);
  6687. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6688. gb_string_free(str);
  6689. gb_string_free(typ);
  6690. }
  6691. }
  6692. o->expr = node;
  6693. return Expr_Expr;
  6694. }
  6695. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  6696. switch (x->mode) {
  6697. case Addressing_MapIndex:
  6698. case Addressing_OptionalOk:
  6699. case Addressing_OptionalOkPtr:
  6700. if (val_type_) *val_type_ = x->type;
  6701. break;
  6702. default:
  6703. if (ok_type_) *ok_type_ = x->type;
  6704. return;
  6705. }
  6706. Ast *expr = unparen_expr(x->expr);
  6707. if (expr->kind == Ast_CallExpr) {
  6708. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6709. if (is_type_proc(pt)) {
  6710. Type *tuple = pt->Proc.results;
  6711. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6712. if (pt->Proc.result_count >= 2) {
  6713. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6714. }
  6715. expr->CallExpr.optional_ok_one = false;
  6716. x->type = tuple;
  6717. return;
  6718. }
  6719. }
  6720. Type *tuple = make_optional_ok_type(x->type);
  6721. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6722. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6723. x->type = tuple;
  6724. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6725. }
  6726. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6727. ast_node(ie, MatrixIndexExpr, node);
  6728. check_expr(c, o, ie->expr);
  6729. node->viral_state_flags |= ie->expr->viral_state_flags;
  6730. if (o->mode == Addressing_Invalid) {
  6731. o->expr = node;
  6732. return;
  6733. }
  6734. Type *t = base_type(type_deref(o->type));
  6735. bool is_ptr = is_type_pointer(o->type);
  6736. bool is_const = o->mode == Addressing_Constant;
  6737. if (t->kind != Type_Matrix) {
  6738. gbString str = expr_to_string(o->expr);
  6739. gbString type_str = type_to_string(o->type);
  6740. defer (gb_string_free(str));
  6741. defer (gb_string_free(type_str));
  6742. if (is_const) {
  6743. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6744. } else {
  6745. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6746. }
  6747. o->mode = Addressing_Invalid;
  6748. o->expr = node;
  6749. return;
  6750. }
  6751. o->type = t->Matrix.elem;
  6752. if (is_ptr) {
  6753. o->mode = Addressing_Variable;
  6754. } else if (o->mode != Addressing_Variable) {
  6755. o->mode = Addressing_Value;
  6756. }
  6757. if (ie->row_index == nullptr) {
  6758. gbString str = expr_to_string(o->expr);
  6759. error(o->expr, "Missing row index for '%s'", str);
  6760. gb_string_free(str);
  6761. o->mode = Addressing_Invalid;
  6762. o->expr = node;
  6763. return;
  6764. }
  6765. if (ie->column_index == nullptr) {
  6766. gbString str = expr_to_string(o->expr);
  6767. error(o->expr, "Missing column index for '%s'", str);
  6768. gb_string_free(str);
  6769. o->mode = Addressing_Invalid;
  6770. o->expr = node;
  6771. return;
  6772. }
  6773. i64 row_count = t->Matrix.row_count;
  6774. i64 column_count = t->Matrix.column_count;
  6775. i64 row_index = 0;
  6776. i64 column_index = 0;
  6777. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6778. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6779. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  6780. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  6781. }
  6782. gb_unused(row_ok);
  6783. gb_unused(column_ok);
  6784. }
  6785. struct TypeAndToken {
  6786. Type *type;
  6787. Token token;
  6788. };
  6789. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  6790. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  6791. if (operand.mode != Addressing_Constant) {
  6792. return;
  6793. }
  6794. if (operand.value.kind == ExactValue_Invalid) {
  6795. return;
  6796. }
  6797. uintptr key = hash_exact_value(operand.value);
  6798. TypeAndToken *found = map_get(seen, key);
  6799. if (found != nullptr) {
  6800. TEMPORARY_ALLOCATOR_GUARD();
  6801. isize count = multi_map_count(seen, key);
  6802. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  6803. multi_map_get_all(seen, key, taps);
  6804. for (isize i = 0; i < count; i++) {
  6805. TypeAndToken tap = taps[i];
  6806. Operand to = {};
  6807. to.mode = Addressing_Value;
  6808. to.type = tap.type;
  6809. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  6810. continue;
  6811. }
  6812. TokenPos pos = tap.token.pos;
  6813. if (use_expr) {
  6814. gbString expr_str = expr_to_string(operand.expr);
  6815. error(operand.expr,
  6816. "Duplicate case '%s'\n"
  6817. "\tprevious case at %s",
  6818. expr_str,
  6819. token_pos_to_string(pos));
  6820. gb_string_free(expr_str);
  6821. } else {
  6822. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  6823. }
  6824. return;
  6825. }
  6826. }
  6827. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  6828. multi_map_insert(seen, key, tap);
  6829. }
  6830. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  6831. if (is_type_enum(x.type)) {
  6832. // TODO(bill): Fix this logic so it's fast!!!
  6833. i64 v0 = exact_value_to_i64(lhs.value);
  6834. i64 v1 = exact_value_to_i64(rhs.value);
  6835. Operand v = {};
  6836. v.mode = Addressing_Constant;
  6837. v.type = x.type;
  6838. v.expr = x.expr;
  6839. Type *bt = base_type(x.type);
  6840. GB_ASSERT(bt->kind == Type_Enum);
  6841. for (i64 vi = v0; vi <= v1; vi++) {
  6842. if (upper_op != Token_LtEq && vi == v1) {
  6843. break;
  6844. }
  6845. v.value = exact_value_i64(vi);
  6846. add_constant_switch_case(ctx, seen, v);
  6847. }
  6848. } else {
  6849. add_constant_switch_case(ctx, seen, lhs);
  6850. if (upper_op == Token_LtEq) {
  6851. add_constant_switch_case(ctx, seen, rhs);
  6852. }
  6853. }
  6854. }
  6855. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  6856. add_constant_switch_case(ctx, seen, x);
  6857. }
  6858. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6859. ast_node(bd, BasicDirective, node);
  6860. ExprKind kind = Expr_Expr;
  6861. o->mode = Addressing_Constant;
  6862. String name = bd->name.string;
  6863. if (name == "file") {
  6864. o->type = t_untyped_string;
  6865. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6866. } else if (name == "line") {
  6867. o->type = t_untyped_integer;
  6868. o->value = exact_value_i64(bd->token.pos.line);
  6869. } else if (name == "procedure") {
  6870. if (c->curr_proc_decl == nullptr) {
  6871. error(node, "#procedure may only be used within procedures");
  6872. o->type = t_untyped_string;
  6873. o->value = exact_value_string(str_lit(""));
  6874. } else {
  6875. o->type = t_untyped_string;
  6876. o->value = exact_value_string(c->proc_name);
  6877. }
  6878. } else if (name == "caller_location") {
  6879. init_core_source_code_location(c->checker);
  6880. error(node, "#caller_location may only be used as a default argument parameter");
  6881. o->type = t_source_code_location;
  6882. o->mode = Addressing_Value;
  6883. } else {
  6884. if (name == "location") {
  6885. init_core_source_code_location(c->checker);
  6886. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  6887. o->type = t_source_code_location;
  6888. o->mode = Addressing_Value;
  6889. } else if (
  6890. name == "assert" ||
  6891. name == "defined" ||
  6892. name == "config" ||
  6893. name == "load" ||
  6894. name == "load_hash" ||
  6895. name == "load_or"
  6896. ) {
  6897. error(node, "'#%.*s' must be used as a call", LIT(name));
  6898. o->type = t_invalid;
  6899. o->mode = Addressing_Invalid;
  6900. } else {
  6901. error(node, "Unknown directive: #%.*s", LIT(name));
  6902. o->type = t_invalid;
  6903. o->mode = Addressing_Invalid;
  6904. }
  6905. }
  6906. return kind;
  6907. }
  6908. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6909. ExprKind kind = Expr_Expr;
  6910. Operand cond = {Addressing_Invalid};
  6911. ast_node(te, TernaryIfExpr, node);
  6912. check_expr(c, &cond, te->cond);
  6913. node->viral_state_flags |= te->cond->viral_state_flags;
  6914. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6915. error(te->cond, "Non-boolean condition in ternary if expression");
  6916. }
  6917. Operand x = {Addressing_Invalid};
  6918. Operand y = {Addressing_Invalid};
  6919. check_expr_or_type(c, &x, te->x, type_hint);
  6920. node->viral_state_flags |= te->x->viral_state_flags;
  6921. if (te->y != nullptr) {
  6922. Type *th = type_hint;
  6923. if (type_hint == nullptr && is_type_typed(x.type)) {
  6924. th = x.type;
  6925. }
  6926. check_expr_or_type(c, &y, te->y, th);
  6927. node->viral_state_flags |= te->y->viral_state_flags;
  6928. } else {
  6929. error(node, "A ternary expression must have an else clause");
  6930. return kind;
  6931. }
  6932. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  6933. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  6934. gbString type_string = expr_to_string(type_expr);
  6935. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  6936. gb_string_free(type_string);
  6937. return kind;
  6938. }
  6939. if (x.type == nullptr || x.type == t_invalid ||
  6940. y.type == nullptr || y.type == t_invalid) {
  6941. return kind;
  6942. }
  6943. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  6944. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  6945. if (x.mode == Addressing_Invalid) {
  6946. return kind;
  6947. }
  6948. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  6949. if (y.mode == Addressing_Invalid) {
  6950. x.mode = Addressing_Invalid;
  6951. return kind;
  6952. }
  6953. // NOTE(bill, 2023-01-30): Allow for expression like this:
  6954. // x: union{f32} = f32(123) if cond else nil
  6955. if (type_hint && !is_type_any(type_hint)) {
  6956. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  6957. check_cast(c, &x, type_hint);
  6958. check_cast(c, &y, type_hint);
  6959. }
  6960. }
  6961. if (!ternary_compare_types(x.type, y.type)) {
  6962. gbString its = type_to_string(x.type);
  6963. gbString ets = type_to_string(y.type);
  6964. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  6965. gb_string_free(ets);
  6966. gb_string_free(its);
  6967. return kind;
  6968. }
  6969. o->type = x.type;
  6970. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  6971. o->type = y.type;
  6972. }
  6973. o->mode = Addressing_Value;
  6974. o->expr = node;
  6975. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  6976. if (check_cast_internal(c, &x, type_hint) &&
  6977. check_cast_internal(c, &y, type_hint)) {
  6978. convert_to_typed(c, o, type_hint);
  6979. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  6980. o->type = type_hint;
  6981. }
  6982. }
  6983. return kind;
  6984. }
  6985. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6986. ExprKind kind = Expr_Expr;
  6987. Operand cond = {};
  6988. ast_node(te, TernaryWhenExpr, node);
  6989. check_expr(c, &cond, te->cond);
  6990. node->viral_state_flags |= te->cond->viral_state_flags;
  6991. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  6992. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  6993. return kind;
  6994. }
  6995. if (cond.value.value_bool) {
  6996. check_expr_or_type(c, o, te->x, type_hint);
  6997. node->viral_state_flags |= te->x->viral_state_flags;
  6998. } else {
  6999. if (te->y != nullptr) {
  7000. check_expr_or_type(c, o, te->y, type_hint);
  7001. node->viral_state_flags |= te->y->viral_state_flags;
  7002. } else {
  7003. error(node, "A ternary when expression must have an else clause");
  7004. return kind;
  7005. }
  7006. }
  7007. return kind;
  7008. }
  7009. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7010. ast_node(oe, OrElseExpr, node);
  7011. String name = oe->token.string;
  7012. Ast *arg = oe->x;
  7013. Ast *default_value = oe->y;
  7014. Operand x = {};
  7015. Operand y = {};
  7016. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7017. if (is_load_directive_call(arg)) {
  7018. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7019. // Allow for chaining of '#load(path) or_else #load(path)'
  7020. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7021. bool y_is_diverging = false;
  7022. check_expr_base(c, &y, default_value, x.type);
  7023. switch (y.mode) {
  7024. case Addressing_NoValue:
  7025. if (is_diverging_expr(y.expr)) {
  7026. // Allow
  7027. y.mode = Addressing_Value;
  7028. y_is_diverging = true;
  7029. } else {
  7030. error_operand_no_value(&y);
  7031. y.mode = Addressing_Invalid;
  7032. }
  7033. break;
  7034. case Addressing_Type:
  7035. error_operand_not_expression(&y);
  7036. y.mode = Addressing_Invalid;
  7037. break;
  7038. }
  7039. if (y.mode == Addressing_Invalid) {
  7040. o->mode = Addressing_Value;
  7041. o->type = t_invalid;
  7042. o->expr = node;
  7043. return Expr_Expr;
  7044. }
  7045. if (!y_is_diverging) {
  7046. check_assignment(c, &y, x.type, name);
  7047. if (y.mode != Addressing_Constant) {
  7048. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7049. }
  7050. }
  7051. }
  7052. if (res == LoadDirective_Success) {
  7053. *o = x;
  7054. } else {
  7055. *o = y;
  7056. }
  7057. o->expr = node;
  7058. return Expr_Expr;
  7059. }
  7060. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7061. if (x.mode == Addressing_Invalid) {
  7062. o->mode = Addressing_Value;
  7063. o->type = t_invalid;
  7064. o->expr = node;
  7065. return Expr_Expr;
  7066. }
  7067. bool y_is_diverging = false;
  7068. check_expr_base(c, &y, default_value, x.type);
  7069. switch (y.mode) {
  7070. case Addressing_NoValue:
  7071. if (is_diverging_expr(y.expr)) {
  7072. // Allow
  7073. y.mode = Addressing_Value;
  7074. y_is_diverging = true;
  7075. } else {
  7076. error_operand_no_value(&y);
  7077. y.mode = Addressing_Invalid;
  7078. }
  7079. break;
  7080. case Addressing_Type:
  7081. error_operand_not_expression(&y);
  7082. y.mode = Addressing_Invalid;
  7083. break;
  7084. }
  7085. if (y.mode == Addressing_Invalid) {
  7086. o->mode = Addressing_Value;
  7087. o->type = t_invalid;
  7088. o->expr = node;
  7089. return Expr_Expr;
  7090. }
  7091. Type *left_type = nullptr;
  7092. Type *right_type = nullptr;
  7093. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7094. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7095. if (left_type != nullptr) {
  7096. if (!y_is_diverging) {
  7097. check_assignment(c, &y, left_type, name);
  7098. }
  7099. } else {
  7100. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7101. }
  7102. if (left_type == nullptr) {
  7103. left_type = t_invalid;
  7104. }
  7105. o->mode = Addressing_Value;
  7106. o->type = left_type;
  7107. o->expr = node;
  7108. return Expr_Expr;
  7109. }
  7110. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7111. ast_node(re, OrReturnExpr, node);
  7112. String name = re->token.string;
  7113. Operand x = {};
  7114. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7115. if (x.mode == Addressing_Invalid) {
  7116. o->mode = Addressing_Value;
  7117. o->type = t_invalid;
  7118. o->expr = node;
  7119. return Expr_Expr;
  7120. }
  7121. Type *left_type = nullptr;
  7122. Type *right_type = nullptr;
  7123. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7124. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7125. if (right_type == nullptr) {
  7126. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7127. } else {
  7128. Type *proc_type = base_type(c->curr_proc_sig);
  7129. GB_ASSERT(proc_type->kind == Type_Proc);
  7130. Type *result_type = proc_type->Proc.results;
  7131. if (result_type == nullptr) {
  7132. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7133. } else {
  7134. GB_ASSERT(result_type->kind == Type_Tuple);
  7135. auto const &vars = result_type->Tuple.variables;
  7136. Type *end_type = vars[vars.count-1]->type;
  7137. if (vars.count > 1) {
  7138. if (!proc_type->Proc.has_named_results) {
  7139. 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));
  7140. }
  7141. }
  7142. Operand rhs = {};
  7143. rhs.type = right_type;
  7144. rhs.mode = Addressing_Value;
  7145. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7146. // NOTE(bill): allow implicit conversion between boolean types
  7147. // within 'or_return' to improve the experience using third-party code
  7148. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7149. // TODO(bill): better error message
  7150. gbString a = type_to_string(right_type);
  7151. gbString b = type_to_string(end_type);
  7152. gbString ret_type = type_to_string(result_type);
  7153. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7154. if (vars.count == 1) {
  7155. error_line("\tProcedure return value type: %s\n", ret_type);
  7156. } else {
  7157. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7158. }
  7159. gb_string_free(ret_type);
  7160. gb_string_free(b);
  7161. gb_string_free(a);
  7162. }
  7163. }
  7164. }
  7165. o->expr = node;
  7166. o->type = left_type;
  7167. if (left_type != nullptr) {
  7168. o->mode = Addressing_Value;
  7169. } else {
  7170. o->mode = Addressing_NoValue;
  7171. }
  7172. if (c->curr_proc_sig == nullptr) {
  7173. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7174. }
  7175. if (c->in_defer) {
  7176. error(node, "'or_return' cannot be used within a defer statement");
  7177. }
  7178. return Expr_Expr;
  7179. }
  7180. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7181. Type *bt = base_type(type);
  7182. StringSet fields_visited = {};
  7183. defer (string_set_destroy(&fields_visited));
  7184. StringMap<String> fields_visited_through_raw_union = {};
  7185. defer (string_map_destroy(&fields_visited_through_raw_union));
  7186. for (Ast *elem : elems) {
  7187. if (elem->kind != Ast_FieldValue) {
  7188. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7189. continue;
  7190. }
  7191. ast_node(fv, FieldValue, elem);
  7192. if (fv->field->kind != Ast_Ident) {
  7193. gbString expr_str = expr_to_string(fv->field);
  7194. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7195. gb_string_free(expr_str);
  7196. continue;
  7197. }
  7198. String name = fv->field->Ident.token.string;
  7199. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7200. bool is_unknown = sel.entity == nullptr;
  7201. if (is_unknown) {
  7202. error(fv->field, "Unknown field '%.*s' in structure literal", LIT(name));
  7203. continue;
  7204. }
  7205. Entity *field = bt->Struct.fields[sel.index[0]];
  7206. add_entity_use(c, fv->field, field);
  7207. if (string_set_update(&fields_visited, name)) {
  7208. if (sel.index.count > 1) {
  7209. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7210. 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));
  7211. } else {
  7212. error(fv->field, "Duplicate or reused field '%.*s' in structure literal", LIT(sel.entity->token.string));
  7213. }
  7214. } else {
  7215. error(fv->field, "Duplicate field '%.*s' in structure literal", LIT(field->token.string));
  7216. }
  7217. continue;
  7218. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7219. 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));
  7220. continue;
  7221. }
  7222. if (sel.indirect) {
  7223. 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));
  7224. continue;
  7225. }
  7226. if (sel.index.count > 1) {
  7227. if (is_constant) {
  7228. Type *ft = type;
  7229. for (i32 index : sel.index) {
  7230. Type *bt = base_type(ft);
  7231. switch (bt->kind) {
  7232. case Type_Struct:
  7233. if (bt->Struct.is_raw_union) {
  7234. is_constant = false;
  7235. break;
  7236. }
  7237. ft = bt->Struct.fields[index]->type;
  7238. break;
  7239. case Type_Array:
  7240. ft = bt->Array.elem;
  7241. break;
  7242. default:
  7243. GB_PANIC("invalid type: %s", type_to_string(ft));
  7244. break;
  7245. }
  7246. }
  7247. if (is_constant &&
  7248. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7249. is_constant = false;
  7250. }
  7251. }
  7252. Type *nested_ft = bt;
  7253. for (i32 index : sel.index) {
  7254. Type *bt = base_type(nested_ft);
  7255. switch (bt->kind) {
  7256. case Type_Struct:
  7257. if (bt->Struct.is_raw_union) {
  7258. for (Entity *re : bt->Struct.fields) {
  7259. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7260. }
  7261. }
  7262. nested_ft = bt->Struct.fields[index]->type;
  7263. break;
  7264. case Type_Array:
  7265. nested_ft = bt->Array.elem;
  7266. break;
  7267. default:
  7268. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7269. break;
  7270. }
  7271. }
  7272. field = sel.entity;
  7273. }
  7274. Operand o = {};
  7275. check_expr_or_type(c, &o, fv->value, field->type);
  7276. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7277. is_constant = false;
  7278. }
  7279. if (is_constant) {
  7280. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7281. }
  7282. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7283. }
  7284. }
  7285. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7286. ExprKind kind = Expr_Expr;
  7287. ast_node(cl, CompoundLit, node);
  7288. Type *type = type_hint;
  7289. if (type != nullptr && is_type_untyped(type)) {
  7290. type = nullptr;
  7291. }
  7292. bool is_to_be_determined_array_count = false;
  7293. bool is_constant = true;
  7294. if (cl->type != nullptr) {
  7295. type = nullptr;
  7296. // [?]Type
  7297. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  7298. Ast *count = cl->type->ArrayType.count;
  7299. if (count->kind == Ast_UnaryExpr &&
  7300. count->UnaryExpr.op.kind == Token_Question) {
  7301. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  7302. is_to_be_determined_array_count = true;
  7303. }
  7304. if (cl->elems.count > 0) {
  7305. if (cl->type->ArrayType.tag != nullptr) {
  7306. Ast *tag = cl->type->ArrayType.tag;
  7307. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7308. String name = tag->BasicDirective.name.string;
  7309. if (name == "soa") {
  7310. error(node, "#soa arrays are not supported for compound literals");
  7311. return kind;
  7312. }
  7313. }
  7314. }
  7315. }
  7316. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  7317. if (cl->elems.count > 0) {
  7318. Ast *tag = cl->type->DynamicArrayType.tag;
  7319. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7320. String name = tag->BasicDirective.name.string;
  7321. if (name == "soa") {
  7322. error(node, "#soa arrays are not supported for compound literals");
  7323. return kind;
  7324. }
  7325. }
  7326. }
  7327. if (type == nullptr) {
  7328. type = check_type(c, cl->type);
  7329. }
  7330. }
  7331. if (type == nullptr) {
  7332. error(node, "Missing type in compound literal");
  7333. return kind;
  7334. }
  7335. Type *t = base_type(type);
  7336. if (is_type_polymorphic(t)) {
  7337. gbString str = type_to_string(type);
  7338. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7339. o->expr = node;
  7340. o->type = type;
  7341. gb_string_free(str);
  7342. return kind;
  7343. }
  7344. switch (t->kind) {
  7345. case Type_Struct: {
  7346. if (cl->elems.count == 0) {
  7347. break; // NOTE(bill): No need to init
  7348. }
  7349. if (t->Struct.is_raw_union) {
  7350. if (cl->elems.count > 0) {
  7351. // NOTE: unions cannot be constant
  7352. is_constant = false;
  7353. if (cl->elems[0]->kind != Ast_FieldValue) {
  7354. gbString type_str = type_to_string(type);
  7355. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7356. gb_string_free(type_str);
  7357. } else {
  7358. if (cl->elems.count != 1) {
  7359. gbString type_str = type_to_string(type);
  7360. 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);
  7361. gb_string_free(type_str);
  7362. } else {
  7363. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7364. }
  7365. }
  7366. }
  7367. break;
  7368. }
  7369. isize field_count = t->Struct.fields.count;
  7370. isize min_field_count = t->Struct.fields.count;
  7371. for (isize i = min_field_count-1; i >= 0; i--) {
  7372. Entity *e = t->Struct.fields[i];
  7373. GB_ASSERT(e->kind == Entity_Variable);
  7374. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7375. min_field_count--;
  7376. } else {
  7377. break;
  7378. }
  7379. }
  7380. if (cl->elems[0]->kind == Ast_FieldValue) {
  7381. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7382. } else {
  7383. bool seen_field_value = false;
  7384. for_array(index, cl->elems) {
  7385. Entity *field = nullptr;
  7386. Ast *elem = cl->elems[index];
  7387. if (elem->kind == Ast_FieldValue) {
  7388. seen_field_value = true;
  7389. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7390. continue;
  7391. } else if (seen_field_value) {
  7392. error(elem, "Value elements cannot be used after a 'field = value'");
  7393. continue;
  7394. }
  7395. if (index >= field_count) {
  7396. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7397. break;
  7398. }
  7399. if (field == nullptr) {
  7400. field = t->Struct.fields[index];
  7401. }
  7402. Operand o = {};
  7403. check_expr_or_type(c, &o, elem, field->type);
  7404. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7405. is_constant = false;
  7406. }
  7407. if (is_constant) {
  7408. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7409. }
  7410. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7411. }
  7412. if (cl->elems.count < field_count) {
  7413. if (min_field_count < field_count) {
  7414. if (cl->elems.count < min_field_count) {
  7415. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7416. }
  7417. } else {
  7418. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7419. }
  7420. }
  7421. }
  7422. break;
  7423. }
  7424. case Type_Slice:
  7425. case Type_Array:
  7426. case Type_DynamicArray:
  7427. case Type_SimdVector:
  7428. case Type_Matrix:
  7429. {
  7430. Type *elem_type = nullptr;
  7431. String context_name = {};
  7432. i64 max_type_count = -1;
  7433. if (t->kind == Type_Slice) {
  7434. elem_type = t->Slice.elem;
  7435. context_name = str_lit("slice literal");
  7436. } else if (t->kind == Type_Array) {
  7437. elem_type = t->Array.elem;
  7438. context_name = str_lit("array literal");
  7439. if (!is_to_be_determined_array_count) {
  7440. max_type_count = t->Array.count;
  7441. }
  7442. } else if (t->kind == Type_DynamicArray) {
  7443. elem_type = t->DynamicArray.elem;
  7444. context_name = str_lit("dynamic array literal");
  7445. is_constant = false;
  7446. if (!build_context.no_dynamic_literals) {
  7447. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7448. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7449. }
  7450. } else if (t->kind == Type_SimdVector) {
  7451. elem_type = t->SimdVector.elem;
  7452. context_name = str_lit("simd vector literal");
  7453. max_type_count = t->SimdVector.count;
  7454. } else if (t->kind == Type_Matrix) {
  7455. elem_type = t->Matrix.elem;
  7456. context_name = str_lit("matrix literal");
  7457. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7458. } else {
  7459. GB_PANIC("unreachable");
  7460. }
  7461. i64 max = 0;
  7462. Type *bet = base_type(elem_type);
  7463. if (!elem_type_can_be_constant(bet)) {
  7464. is_constant = false;
  7465. }
  7466. if (bet == t_invalid) {
  7467. break;
  7468. }
  7469. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7470. RangeCache rc = range_cache_make(heap_allocator());
  7471. defer (range_cache_destroy(&rc));
  7472. for (Ast *elem : cl->elems) {
  7473. if (elem->kind != Ast_FieldValue) {
  7474. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7475. continue;
  7476. }
  7477. ast_node(fv, FieldValue, elem);
  7478. if (is_ast_range(fv->field)) {
  7479. Token op = fv->field->BinaryExpr.op;
  7480. Operand x = {};
  7481. Operand y = {};
  7482. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7483. if (!ok) {
  7484. continue;
  7485. }
  7486. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7487. error(x.expr, "Expected a constant integer as an array field");
  7488. continue;
  7489. }
  7490. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7491. error(y.expr, "Expected a constant integer as an array field");
  7492. continue;
  7493. }
  7494. i64 lo = exact_value_to_i64(x.value);
  7495. i64 hi = exact_value_to_i64(y.value);
  7496. i64 max_index = hi;
  7497. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7498. hi -= 1;
  7499. } else { // .. (inclusive)
  7500. max_index += 1;
  7501. }
  7502. bool new_range = range_cache_add_range(&rc, lo, hi);
  7503. if (!new_range) {
  7504. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7505. continue;
  7506. }
  7507. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7508. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7509. continue;
  7510. }
  7511. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7512. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7513. continue;
  7514. }
  7515. if (max < hi) {
  7516. max = max_index;
  7517. }
  7518. Operand operand = {};
  7519. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7520. check_assignment(c, &operand, elem_type, context_name);
  7521. is_constant = is_constant && operand.mode == Addressing_Constant;
  7522. } else {
  7523. Operand op_index = {};
  7524. check_expr(c, &op_index, fv->field);
  7525. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7526. error(elem, "Expected a constant integer as an array field");
  7527. continue;
  7528. }
  7529. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7530. i64 index = exact_value_to_i64(op_index.value);
  7531. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7532. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7533. continue;
  7534. }
  7535. bool new_index = range_cache_add_index(&rc, index);
  7536. if (!new_index) {
  7537. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7538. continue;
  7539. }
  7540. if (max < index+1) {
  7541. max = index+1;
  7542. }
  7543. Operand operand = {};
  7544. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7545. check_assignment(c, &operand, elem_type, context_name);
  7546. is_constant = is_constant && operand.mode == Addressing_Constant;
  7547. }
  7548. }
  7549. cl->max_count = max;
  7550. } else {
  7551. isize index = 0;
  7552. for (; index < cl->elems.count; index++) {
  7553. Ast *e = cl->elems[index];
  7554. if (e == nullptr) {
  7555. error(node, "Invalid literal element");
  7556. continue;
  7557. }
  7558. if (e->kind == Ast_FieldValue) {
  7559. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7560. continue;
  7561. }
  7562. if (0 <= max_type_count && max_type_count <= index) {
  7563. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7564. }
  7565. Operand operand = {};
  7566. check_expr_with_type_hint(c, &operand, e, elem_type);
  7567. check_assignment(c, &operand, elem_type, context_name);
  7568. is_constant = is_constant && operand.mode == Addressing_Constant;
  7569. }
  7570. if (max < index) {
  7571. max = index;
  7572. }
  7573. }
  7574. if (t->kind == Type_Array) {
  7575. if (is_to_be_determined_array_count) {
  7576. t->Array.count = max;
  7577. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7578. if (0 < max && max < t->Array.count) {
  7579. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7580. }
  7581. }
  7582. }
  7583. if (t->kind == Type_SimdVector) {
  7584. if (!is_constant) {
  7585. // error(node, "Expected all constant elements for a simd vector");
  7586. }
  7587. }
  7588. if (t->kind == Type_DynamicArray) {
  7589. if (build_context.no_dynamic_literals && cl->elems.count) {
  7590. error(node, "Compound literals of dynamic types have been disabled");
  7591. }
  7592. }
  7593. if (t->kind == Type_Matrix) {
  7594. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7595. if (0 < max && max < max_type_count) {
  7596. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7597. }
  7598. }
  7599. }
  7600. break;
  7601. }
  7602. case Type_EnumeratedArray:
  7603. {
  7604. Type *elem_type = t->EnumeratedArray.elem;
  7605. Type *index_type = t->EnumeratedArray.index;
  7606. String context_name = str_lit("enumerated array literal");
  7607. i64 max_type_count = t->EnumeratedArray.count;
  7608. gbString index_type_str = type_to_string(index_type);
  7609. defer (gb_string_free(index_type_str));
  7610. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7611. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7612. String total_lo_string = {};
  7613. String total_hi_string = {};
  7614. GB_ASSERT(is_type_enum(index_type));
  7615. {
  7616. Type *bt = base_type(index_type);
  7617. GB_ASSERT(bt->kind == Type_Enum);
  7618. for (Entity *f : bt->Enum.fields) {
  7619. if (f->kind != Entity_Constant) {
  7620. continue;
  7621. }
  7622. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7623. total_lo_string = f->token.string;
  7624. }
  7625. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7626. total_hi_string = f->token.string;
  7627. }
  7628. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  7629. break;
  7630. }
  7631. }
  7632. }
  7633. i64 max = 0;
  7634. Type *bet = base_type(elem_type);
  7635. if (!elem_type_can_be_constant(bet)) {
  7636. is_constant = false;
  7637. }
  7638. if (bet == t_invalid) {
  7639. break;
  7640. }
  7641. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  7642. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  7643. defer (map_destroy(&seen));
  7644. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7645. RangeCache rc = range_cache_make(heap_allocator());
  7646. defer (range_cache_destroy(&rc));
  7647. for (Ast *elem : cl->elems) {
  7648. if (elem->kind != Ast_FieldValue) {
  7649. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7650. continue;
  7651. }
  7652. ast_node(fv, FieldValue, elem);
  7653. if (is_ast_range(fv->field)) {
  7654. Token op = fv->field->BinaryExpr.op;
  7655. Operand x = {};
  7656. Operand y = {};
  7657. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  7658. if (!ok) {
  7659. continue;
  7660. }
  7661. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7662. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7663. continue;
  7664. }
  7665. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7666. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7667. continue;
  7668. }
  7669. i64 lo = exact_value_to_i64(x.value);
  7670. i64 hi = exact_value_to_i64(y.value);
  7671. i64 max_index = hi;
  7672. if (op.kind == Token_RangeHalf) {
  7673. hi -= 1;
  7674. }
  7675. bool new_range = range_cache_add_range(&rc, lo, hi);
  7676. if (!new_range) {
  7677. gbString lo_str = expr_to_string(x.expr);
  7678. gbString hi_str = expr_to_string(y.expr);
  7679. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  7680. gb_string_free(hi_str);
  7681. gb_string_free(lo_str);
  7682. continue;
  7683. }
  7684. // NOTE(bill): These are sanity checks for invalid enum values
  7685. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  7686. gbString lo_str = expr_to_string(x.expr);
  7687. 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));
  7688. gb_string_free(lo_str);
  7689. continue;
  7690. }
  7691. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  7692. gbString hi_str = expr_to_string(y.expr);
  7693. 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));
  7694. gb_string_free(hi_str);
  7695. continue;
  7696. }
  7697. if (max < hi) {
  7698. max = max_index;
  7699. }
  7700. Operand operand = {};
  7701. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7702. check_assignment(c, &operand, elem_type, context_name);
  7703. is_constant = is_constant && operand.mode == Addressing_Constant;
  7704. TokenKind upper_op = Token_LtEq;
  7705. if (op.kind == Token_RangeHalf) {
  7706. upper_op = Token_Lt;
  7707. }
  7708. add_to_seen_map(c, &seen, upper_op, x, x, y);
  7709. } else {
  7710. Operand op_index = {};
  7711. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  7712. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  7713. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7714. continue;
  7715. }
  7716. i64 index = exact_value_to_i64(op_index.value);
  7717. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  7718. gbString idx_str = expr_to_string(op_index.expr);
  7719. 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));
  7720. gb_string_free(idx_str);
  7721. continue;
  7722. }
  7723. bool new_index = range_cache_add_index(&rc, index);
  7724. if (!new_index) {
  7725. gbString idx_str = expr_to_string(op_index.expr);
  7726. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  7727. gb_string_free(idx_str);
  7728. continue;
  7729. }
  7730. if (max < index+1) {
  7731. max = index+1;
  7732. }
  7733. Operand operand = {};
  7734. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7735. check_assignment(c, &operand, elem_type, context_name);
  7736. is_constant = is_constant && operand.mode == Addressing_Constant;
  7737. add_to_seen_map(c, &seen, op_index);
  7738. }
  7739. }
  7740. cl->max_count = max;
  7741. } else {
  7742. isize index = 0;
  7743. for (; index < cl->elems.count; index++) {
  7744. Ast *e = cl->elems[index];
  7745. if (e == nullptr) {
  7746. error(node, "Invalid literal element");
  7747. continue;
  7748. }
  7749. if (e->kind == Ast_FieldValue) {
  7750. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7751. continue;
  7752. }
  7753. if (0 <= max_type_count && max_type_count <= index) {
  7754. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7755. }
  7756. Operand operand = {};
  7757. check_expr_with_type_hint(c, &operand, e, elem_type);
  7758. check_assignment(c, &operand, elem_type, context_name);
  7759. is_constant = is_constant && operand.mode == Addressing_Constant;
  7760. }
  7761. if (max < index) {
  7762. max = index;
  7763. }
  7764. }
  7765. bool was_error = false;
  7766. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7767. if (0 < max && max < t->EnumeratedArray.count) {
  7768. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  7769. was_error = true;
  7770. } else {
  7771. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  7772. was_error = true;
  7773. }
  7774. }
  7775. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  7776. if (cl->elems.count > 0 && !was_error && !is_partial) {
  7777. TEMPORARY_ALLOCATOR_GUARD();
  7778. Type *et = base_type(index_type);
  7779. GB_ASSERT(et->kind == Type_Enum);
  7780. auto fields = et->Enum.fields;
  7781. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  7782. for (Entity *f : fields) {
  7783. if (f->kind != Entity_Constant) {
  7784. continue;
  7785. }
  7786. ExactValue v = f->Constant.value;
  7787. auto found = map_get(&seen, hash_exact_value(v));
  7788. if (!found) {
  7789. array_add(&unhandled, f);
  7790. }
  7791. }
  7792. if (unhandled.count > 0) {
  7793. begin_error_block();
  7794. defer (end_error_block());
  7795. if (unhandled.count == 1) {
  7796. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  7797. } else {
  7798. error(node, "Unhandled enumerated array cases:");
  7799. for_array(i, unhandled) {
  7800. Entity *f = unhandled[i];
  7801. error_line("\t%.*s\n", LIT(f->token.string));
  7802. }
  7803. }
  7804. error_line("\n");
  7805. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  7806. }
  7807. }
  7808. break;
  7809. }
  7810. case Type_Basic: {
  7811. if (!is_type_any(t)) {
  7812. if (cl->elems.count != 0) {
  7813. gbString s = type_to_string(t);
  7814. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  7815. gb_string_free(s);
  7816. is_constant = false;
  7817. }
  7818. break;
  7819. }
  7820. if (cl->elems.count == 0) {
  7821. break; // NOTE(bill): No need to init
  7822. }
  7823. { // Checker values
  7824. Type *field_types[2] = {t_rawptr, t_typeid};
  7825. isize field_count = 2;
  7826. if (cl->elems[0]->kind == Ast_FieldValue) {
  7827. bool fields_visited[2] = {};
  7828. for_array(i, cl->elems) {
  7829. Ast *elem = cl->elems[i];
  7830. if (elem->kind != Ast_FieldValue) {
  7831. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7832. continue;
  7833. }
  7834. ast_node(fv, FieldValue, elem);
  7835. if (fv->field->kind != Ast_Ident) {
  7836. gbString expr_str = expr_to_string(fv->field);
  7837. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  7838. gb_string_free(expr_str);
  7839. continue;
  7840. }
  7841. String name = fv->field->Ident.token.string;
  7842. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7843. if (sel.entity == nullptr) {
  7844. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  7845. continue;
  7846. }
  7847. isize index = sel.index[0];
  7848. if (fields_visited[index]) {
  7849. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  7850. continue;
  7851. }
  7852. fields_visited[index] = true;
  7853. check_expr(c, o, fv->value);
  7854. // NOTE(bill): 'any' literals can never be constant
  7855. is_constant = false;
  7856. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7857. }
  7858. } else {
  7859. for_array(index, cl->elems) {
  7860. Ast *elem = cl->elems[index];
  7861. if (elem->kind == Ast_FieldValue) {
  7862. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7863. continue;
  7864. }
  7865. check_expr(c, o, elem);
  7866. if (index >= field_count) {
  7867. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  7868. break;
  7869. }
  7870. // NOTE(bill): 'any' literals can never be constant
  7871. is_constant = false;
  7872. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7873. }
  7874. if (cl->elems.count < field_count) {
  7875. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  7876. }
  7877. }
  7878. }
  7879. break;
  7880. }
  7881. case Type_Map: {
  7882. if (cl->elems.count == 0) {
  7883. break;
  7884. }
  7885. is_constant = false;
  7886. { // Checker values
  7887. bool key_is_typeid = is_type_typeid(t->Map.key);
  7888. bool value_is_typeid = is_type_typeid(t->Map.value);
  7889. for (Ast *elem : cl->elems) {
  7890. if (elem->kind != Ast_FieldValue) {
  7891. error(elem, "Only 'field = value' elements are allowed in a map literal");
  7892. continue;
  7893. }
  7894. ast_node(fv, FieldValue, elem);
  7895. if (key_is_typeid) {
  7896. check_expr_or_type(c, o, fv->field, t->Map.key);
  7897. } else {
  7898. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  7899. }
  7900. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  7901. if (o->mode == Addressing_Invalid) {
  7902. continue;
  7903. }
  7904. if (value_is_typeid) {
  7905. check_expr_or_type(c, o, fv->value, t->Map.value);
  7906. } else {
  7907. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  7908. }
  7909. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  7910. }
  7911. }
  7912. if (build_context.no_dynamic_literals && cl->elems.count) {
  7913. error(node, "Compound literals of dynamic types have been disabled");
  7914. } else {
  7915. add_map_reserve_dependencies(c);
  7916. add_map_set_dependencies(c);
  7917. }
  7918. break;
  7919. }
  7920. case Type_BitSet: {
  7921. if (cl->elems.count == 0) {
  7922. break; // NOTE(bill): No need to init
  7923. }
  7924. Type *et = base_type(t->BitSet.elem);
  7925. isize field_count = 0;
  7926. if (et->kind == Type_Enum) {
  7927. field_count = et->Enum.fields.count;
  7928. }
  7929. if (cl->elems[0]->kind == Ast_FieldValue) {
  7930. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  7931. is_constant = false;
  7932. } else {
  7933. for (Ast *elem : cl->elems) {
  7934. if (elem->kind == Ast_FieldValue) {
  7935. error(elem, "'field = value' in a bit_set a literal is not allowed");
  7936. continue;
  7937. }
  7938. check_expr_with_type_hint(c, o, elem, et);
  7939. if (is_constant) {
  7940. is_constant = o->mode == Addressing_Constant;
  7941. }
  7942. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  7943. if (o->mode == Addressing_Constant) {
  7944. i64 lower = t->BitSet.lower;
  7945. i64 upper = t->BitSet.upper;
  7946. i64 v = exact_value_to_i64(o->value);
  7947. if (lower <= v && v <= upper) {
  7948. // okay
  7949. } else {
  7950. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  7951. continue;
  7952. }
  7953. }
  7954. }
  7955. }
  7956. break;
  7957. }
  7958. default: {
  7959. if (cl->elems.count == 0) {
  7960. break; // NOTE(bill): No need to init
  7961. }
  7962. gbString str = type_to_string(type);
  7963. error(node, "Invalid compound literal type '%s'", str);
  7964. gb_string_free(str);
  7965. return kind;
  7966. }
  7967. }
  7968. if (is_constant) {
  7969. o->mode = Addressing_Constant;
  7970. if (is_type_bit_set(type)) {
  7971. // NOTE(bill): Encode as an integer
  7972. Type *bt = base_type(type);
  7973. BigInt bits = {};
  7974. BigInt one = {};
  7975. big_int_from_u64(&one, 1);
  7976. for (Ast *e : cl->elems) {
  7977. GB_ASSERT(e->kind != Ast_FieldValue);
  7978. TypeAndValue tav = e->tav;
  7979. if (tav.mode != Addressing_Constant) {
  7980. continue;
  7981. }
  7982. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  7983. i64 v = big_int_to_i64(&tav.value.value_integer);
  7984. i64 lower = bt->BitSet.lower;
  7985. u64 index = cast(u64)(v-lower);
  7986. BigInt bit = {};
  7987. big_int_from_u64(&bit, index);
  7988. big_int_shl(&bit, &one, &bit);
  7989. big_int_or(&bits, &bits, &bit);
  7990. }
  7991. o->value.kind = ExactValue_Integer;
  7992. o->value.value_integer = bits;
  7993. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  7994. ExactValue value = exact_value_compound(node);
  7995. Type *bt = core_type(type);
  7996. if (bt->kind == Type_Basic) {
  7997. if (bt->Basic.flags & BasicFlag_Boolean) {
  7998. value = exact_value_bool(false);
  7999. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8000. value = exact_value_i64(0);
  8001. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8002. value = exact_value_i64(0);
  8003. } else if (bt->Basic.flags & BasicFlag_Float) {
  8004. value = exact_value_float(0);
  8005. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8006. value = exact_value_complex(0, 0);
  8007. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8008. value = exact_value_quaternion(0, 0, 0, 0);
  8009. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8010. value = exact_value_pointer(0);
  8011. } else if (bt->Basic.flags & BasicFlag_String) {
  8012. String empty_string = {};
  8013. value = exact_value_string(empty_string);
  8014. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8015. value = exact_value_i64(0);
  8016. }
  8017. }
  8018. o->value = value;
  8019. } else {
  8020. o->value = exact_value_compound(node);
  8021. }
  8022. } else {
  8023. o->mode = Addressing_Value;
  8024. }
  8025. o->type = type;
  8026. return kind;
  8027. }
  8028. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8029. ExprKind kind = Expr_Expr;
  8030. ast_node(ta, TypeAssertion, node);
  8031. check_expr(c, o, ta->expr);
  8032. node->viral_state_flags |= ta->expr->viral_state_flags;
  8033. if (o->mode == Addressing_Invalid) {
  8034. o->expr = node;
  8035. return kind;
  8036. }
  8037. if (o->mode == Addressing_Constant) {
  8038. gbString expr_str = expr_to_string(o->expr);
  8039. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8040. gb_string_free(expr_str);
  8041. o->mode = Addressing_Invalid;
  8042. o->expr = node;
  8043. return kind;
  8044. }
  8045. if (is_type_untyped(o->type)) {
  8046. gbString expr_str = expr_to_string(o->expr);
  8047. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8048. gb_string_free(expr_str);
  8049. o->mode = Addressing_Invalid;
  8050. o->expr = node;
  8051. return kind;
  8052. }
  8053. Type *src = type_deref(o->type);
  8054. Type *bsrc = base_type(src);
  8055. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8056. if (!is_type_union(src)) {
  8057. gbString str = type_to_string(o->type);
  8058. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8059. gb_string_free(str);
  8060. o->mode = Addressing_Invalid;
  8061. o->expr = node;
  8062. return kind;
  8063. }
  8064. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8065. bool allowed = false;
  8066. for (Type *vt : bsrc->Union.variants) {
  8067. if (are_types_identical(vt, type_hint)) {
  8068. allowed = true;
  8069. add_type_info_type(c, vt);
  8070. break;
  8071. }
  8072. }
  8073. if (allowed) {
  8074. add_type_info_type(c, o->type);
  8075. o->type = type_hint;
  8076. o->mode = Addressing_OptionalOk;
  8077. return kind;
  8078. }
  8079. }
  8080. if (bsrc->Union.variants.count != 1) {
  8081. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8082. o->mode = Addressing_Invalid;
  8083. o->expr = node;
  8084. return kind;
  8085. }
  8086. add_type_info_type(c, o->type);
  8087. add_type_info_type(c, bsrc->Union.variants[0]);
  8088. o->type = bsrc->Union.variants[0];
  8089. o->mode = Addressing_OptionalOk;
  8090. } else {
  8091. Type *t = check_type(c, ta->type);
  8092. Type *dst = t;
  8093. if (is_type_union(src)) {
  8094. bool ok = false;
  8095. for (Type *vt : bsrc->Union.variants) {
  8096. if (are_types_identical(vt, dst)) {
  8097. ok = true;
  8098. break;
  8099. }
  8100. }
  8101. if (!ok) {
  8102. gbString expr_str = expr_to_string(o->expr);
  8103. gbString dst_type_str = type_to_string(t);
  8104. defer (gb_string_free(expr_str));
  8105. defer (gb_string_free(dst_type_str));
  8106. if (bsrc->Union.variants.count == 0) {
  8107. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8108. } else {
  8109. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8110. }
  8111. o->mode = Addressing_Invalid;
  8112. o->expr = node;
  8113. return kind;
  8114. }
  8115. add_type_info_type(c, o->type);
  8116. add_type_info_type(c, t);
  8117. o->type = t;
  8118. o->mode = Addressing_OptionalOk;
  8119. } else if (is_type_any(src)) {
  8120. o->type = t;
  8121. o->mode = Addressing_OptionalOk;
  8122. add_type_info_type(c, o->type);
  8123. add_type_info_type(c, t);
  8124. } else {
  8125. gbString str = type_to_string(o->type);
  8126. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8127. gb_string_free(str);
  8128. o->mode = Addressing_Invalid;
  8129. o->expr = node;
  8130. return kind;
  8131. }
  8132. }
  8133. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8134. add_package_dependency(c, "runtime", "type_assertion_check");
  8135. add_package_dependency(c, "runtime", "type_assertion_check2");
  8136. }
  8137. return kind;
  8138. }
  8139. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8140. ast_node(se, SelectorCallExpr, node);
  8141. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8142. // COM APIs is a great example of where this kind of thing is extremely useful
  8143. // General idea:
  8144. //
  8145. // x->y(123) == x.y(x, 123)
  8146. //
  8147. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8148. // Just regenerating a new AST aids things
  8149. //
  8150. // TODO(bill): Is this a good hack or not?
  8151. //
  8152. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8153. if (se->modified_call) {
  8154. // Prevent double evaluation
  8155. o->expr = node;
  8156. o->type = node->tav.type;
  8157. o->value = node->tav.value;
  8158. o->mode = node->tav.mode;
  8159. return Expr_Expr;
  8160. }
  8161. bool allow_arrow_right_selector_expr;
  8162. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8163. c->allow_arrow_right_selector_expr = true;
  8164. Operand x = {};
  8165. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8166. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8167. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8168. o->mode = Addressing_Invalid;
  8169. o->type = t_invalid;
  8170. o->expr = node;
  8171. return kind;
  8172. }
  8173. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8174. gbString type_str = type_to_string(x.type);
  8175. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8176. gb_string_free(type_str);
  8177. o->mode = Addressing_Invalid;
  8178. o->type = t_invalid;
  8179. o->expr = node;
  8180. return Expr_Stmt;
  8181. }
  8182. ast_node(ce, CallExpr, se->call);
  8183. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8184. Ast *first_arg = x.expr->SelectorExpr.expr;
  8185. GB_ASSERT(first_arg != nullptr);
  8186. Entity *e = entity_of_node(se->expr);
  8187. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8188. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8189. }
  8190. if (e->kind != Entity_ProcGroup) {
  8191. Type *pt = base_type(x.type);
  8192. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8193. Type *first_type = nullptr;
  8194. String first_arg_name = {};
  8195. if (pt->Proc.param_count > 0) {
  8196. Entity *f = pt->Proc.params->Tuple.variables[0];
  8197. first_type = f->type;
  8198. first_arg_name = f->token.string;
  8199. }
  8200. if (first_arg_name.len == 0) {
  8201. first_arg_name = str_lit("_");
  8202. }
  8203. if (first_type == nullptr) {
  8204. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8205. o->mode = Addressing_Invalid;
  8206. o->type = t_invalid;
  8207. o->expr = node;
  8208. return Expr_Stmt;
  8209. }
  8210. Operand y = {};
  8211. y.mode = first_arg->tav.mode;
  8212. y.type = first_arg->tav.type;
  8213. y.value = first_arg->tav.value;
  8214. if (check_is_assignable_to(c, &y, first_type)) {
  8215. // Do nothing, it's valid
  8216. } else {
  8217. Operand z = y;
  8218. z.type = type_deref(y.type);
  8219. if (check_is_assignable_to(c, &z, first_type)) {
  8220. // NOTE(bill): AST GENERATION HACK!
  8221. Token op = {Token_Pointer};
  8222. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8223. } else if (y.mode == Addressing_Variable) {
  8224. Operand w = y;
  8225. w.type = alloc_type_pointer(y.type);
  8226. if (check_is_assignable_to(c, &w, first_type)) {
  8227. // NOTE(bill): AST GENERATION HACK!
  8228. Token op = {Token_And};
  8229. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8230. }
  8231. }
  8232. }
  8233. if (ce->args.count > 0) {
  8234. bool fail = false;
  8235. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8236. for (Ast *arg : ce->args) {
  8237. bool mix = false;
  8238. if (first_is_field_value) {
  8239. mix = arg->kind != Ast_FieldValue;
  8240. } else {
  8241. mix = arg->kind == Ast_FieldValue;
  8242. }
  8243. if (mix) {
  8244. fail = true;
  8245. break;
  8246. }
  8247. }
  8248. if (!fail && first_is_field_value) {
  8249. Token op = {Token_Eq};
  8250. AstFile *f = first_arg->file();
  8251. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8252. }
  8253. }
  8254. }
  8255. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8256. modified_args[0] = first_arg;
  8257. slice_copy(&modified_args, ce->args, 1);
  8258. ce->args = modified_args;
  8259. se->modified_call = true;
  8260. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8261. c->allow_arrow_right_selector_expr = true;
  8262. check_expr_base(c, o, se->call, type_hint);
  8263. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8264. o->expr = node;
  8265. return Expr_Expr;
  8266. }
  8267. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8268. ExprKind kind = Expr_Expr;
  8269. ast_node(ie, IndexExpr, node);
  8270. check_expr(c, o, ie->expr);
  8271. node->viral_state_flags |= ie->expr->viral_state_flags;
  8272. if (o->mode == Addressing_Invalid) {
  8273. o->expr = node;
  8274. return kind;
  8275. }
  8276. Type *t = base_type(type_deref(o->type));
  8277. bool is_ptr = is_type_pointer(o->type);
  8278. bool is_const = o->mode == Addressing_Constant;
  8279. if (is_type_map(t)) {
  8280. Operand key = {};
  8281. if (is_type_typeid(t->Map.key)) {
  8282. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8283. } else {
  8284. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8285. }
  8286. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8287. if (key.mode == Addressing_Invalid) {
  8288. o->mode = Addressing_Invalid;
  8289. o->expr = node;
  8290. return kind;
  8291. }
  8292. o->mode = Addressing_MapIndex;
  8293. o->type = t->Map.value;
  8294. o->expr = node;
  8295. add_map_get_dependencies(c);
  8296. add_map_set_dependencies(c);
  8297. return Expr_Expr;
  8298. }
  8299. i64 max_count = -1;
  8300. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8301. if (is_const) {
  8302. if (is_type_array(t)) {
  8303. // Okay
  8304. } else if (is_type_slice(t)) {
  8305. // Okay
  8306. } else if (is_type_enumerated_array(t)) {
  8307. // Okay
  8308. } else if (is_type_string(t)) {
  8309. // Okay
  8310. } else if (is_type_relative_multi_pointer(t)) {
  8311. // Okay
  8312. } else if (is_type_matrix(t)) {
  8313. // Okay
  8314. } else {
  8315. valid = false;
  8316. }
  8317. }
  8318. if (!valid) {
  8319. gbString str = expr_to_string(o->expr);
  8320. gbString type_str = type_to_string(o->type);
  8321. defer (gb_string_free(str));
  8322. defer (gb_string_free(type_str));
  8323. if (is_const) {
  8324. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8325. } else {
  8326. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8327. }
  8328. o->mode = Addressing_Invalid;
  8329. o->expr = node;
  8330. return kind;
  8331. }
  8332. if (ie->index == nullptr) {
  8333. gbString str = expr_to_string(o->expr);
  8334. error(o->expr, "Missing index for '%s'", str);
  8335. gb_string_free(str);
  8336. o->mode = Addressing_Invalid;
  8337. o->expr = node;
  8338. return kind;
  8339. }
  8340. Type *index_type_hint = nullptr;
  8341. if (is_type_enumerated_array(t)) {
  8342. Type *bt = base_type(t);
  8343. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8344. index_type_hint = bt->EnumeratedArray.index;
  8345. }
  8346. i64 index = 0;
  8347. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8348. if (is_const) {
  8349. if (index < 0) {
  8350. gbString str = expr_to_string(o->expr);
  8351. error(o->expr, "Cannot index a constant '%s'", str);
  8352. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8353. gb_string_free(str);
  8354. o->mode = Addressing_Invalid;
  8355. o->expr = node;
  8356. return kind;
  8357. } else if (ok) {
  8358. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8359. o->mode = Addressing_Constant;
  8360. bool success = false;
  8361. bool finish = false;
  8362. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8363. if (!success) {
  8364. gbString str = expr_to_string(o->expr);
  8365. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8366. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8367. gb_string_free(str);
  8368. o->mode = Addressing_Invalid;
  8369. o->expr = node;
  8370. return kind;
  8371. }
  8372. }
  8373. }
  8374. if (type_hint != nullptr && is_type_matrix(t)) {
  8375. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8376. // if a type hint exists
  8377. }
  8378. return kind;
  8379. }
  8380. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8381. ExprKind kind = Expr_Stmt;
  8382. ast_node(se, SliceExpr, node);
  8383. check_expr(c, o, se->expr);
  8384. node->viral_state_flags |= se->expr->viral_state_flags;
  8385. if (o->mode == Addressing_Invalid) {
  8386. o->mode = Addressing_Invalid;
  8387. o->expr = node;
  8388. return kind;
  8389. }
  8390. bool valid = false;
  8391. i64 max_count = -1;
  8392. Type *t = base_type(type_deref(o->type));
  8393. switch (t->kind) {
  8394. case Type_Basic:
  8395. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8396. valid = true;
  8397. if (o->mode == Addressing_Constant) {
  8398. max_count = o->value.value_string.len;
  8399. }
  8400. o->type = type_deref(o->type);
  8401. }
  8402. break;
  8403. case Type_Array:
  8404. valid = true;
  8405. max_count = t->Array.count;
  8406. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8407. gbString str = expr_to_string(node);
  8408. error(node, "Cannot slice array '%s', value is not addressable", str);
  8409. gb_string_free(str);
  8410. o->mode = Addressing_Invalid;
  8411. o->expr = node;
  8412. return kind;
  8413. }
  8414. o->type = alloc_type_slice(t->Array.elem);
  8415. break;
  8416. case Type_MultiPointer:
  8417. valid = true;
  8418. o->type = type_deref(o->type);
  8419. break;
  8420. case Type_Slice:
  8421. valid = true;
  8422. o->type = type_deref(o->type);
  8423. break;
  8424. case Type_DynamicArray:
  8425. valid = true;
  8426. o->type = alloc_type_slice(t->DynamicArray.elem);
  8427. break;
  8428. case Type_Struct:
  8429. if (is_type_soa_struct(t)) {
  8430. valid = true;
  8431. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8432. }
  8433. break;
  8434. case Type_RelativeMultiPointer:
  8435. valid = true;
  8436. o->type = type_deref(o->type);
  8437. break;
  8438. case Type_EnumeratedArray:
  8439. {
  8440. gbString str = expr_to_string(o->expr);
  8441. gbString type_str = type_to_string(o->type);
  8442. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8443. gb_string_free(type_str);
  8444. gb_string_free(str);
  8445. o->mode = Addressing_Invalid;
  8446. o->expr = node;
  8447. return kind;
  8448. }
  8449. break;
  8450. }
  8451. if (!valid) {
  8452. gbString str = expr_to_string(o->expr);
  8453. gbString type_str = type_to_string(o->type);
  8454. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8455. gb_string_free(type_str);
  8456. gb_string_free(str);
  8457. o->mode = Addressing_Invalid;
  8458. o->expr = node;
  8459. return kind;
  8460. }
  8461. if (se->low == nullptr && se->high != nullptr) {
  8462. // It is okay to continue as it will assume the 1st index is zero
  8463. }
  8464. i64 indices[2] = {};
  8465. Ast *nodes[2] = {se->low, se->high};
  8466. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8467. i64 index = max_count;
  8468. if (nodes[i] != nullptr) {
  8469. i64 capacity = -1;
  8470. if (max_count >= 0) {
  8471. capacity = max_count;
  8472. }
  8473. i64 j = 0;
  8474. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8475. index = j;
  8476. }
  8477. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8478. } else if (i == 0) {
  8479. index = 0;
  8480. }
  8481. indices[i] = index;
  8482. }
  8483. for (isize i = 0; i < gb_count_of(indices); i++) {
  8484. i64 a = indices[i];
  8485. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8486. i64 b = indices[j];
  8487. if (a > b && b >= 0) {
  8488. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8489. }
  8490. }
  8491. }
  8492. if (max_count < 0) {
  8493. if (o->mode == Addressing_Constant) {
  8494. gbString s = expr_to_string(se->expr);
  8495. error(se->expr, "Cannot slice constant value '%s'", s);
  8496. gb_string_free(s);
  8497. }
  8498. }
  8499. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8500. /*
  8501. x[:] -> [^]T
  8502. x[i:] -> [^]T
  8503. x[:n] -> []T
  8504. x[i:n] -> []T
  8505. */
  8506. o->type = alloc_type_slice(t->MultiPointer.elem);
  8507. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  8508. /*
  8509. x[:] -> [^]T
  8510. x[i:] -> [^]T
  8511. x[:n] -> []T
  8512. x[i:n] -> []T
  8513. */
  8514. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  8515. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  8516. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  8517. }
  8518. o->mode = Addressing_Value;
  8519. if (is_type_string(t) && max_count >= 0) {
  8520. bool all_constant = true;
  8521. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8522. if (nodes[i] != nullptr) {
  8523. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8524. if (tav.mode != Addressing_Constant) {
  8525. all_constant = false;
  8526. break;
  8527. }
  8528. }
  8529. }
  8530. if (!all_constant) {
  8531. gbString str = expr_to_string(o->expr);
  8532. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8533. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8534. gb_string_free(str);
  8535. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8536. o->expr = node;
  8537. return kind;
  8538. }
  8539. String s = {};
  8540. if (o->value.kind == ExactValue_String) {
  8541. s = o->value.value_string;
  8542. }
  8543. o->mode = Addressing_Constant;
  8544. o->type = t;
  8545. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8546. }
  8547. return kind;
  8548. }
  8549. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8550. u32 prev_state_flags = c->state_flags;
  8551. defer (c->state_flags = prev_state_flags);
  8552. if (node->state_flags != 0) {
  8553. u32 in = node->state_flags;
  8554. u32 out = c->state_flags;
  8555. if (in & StateFlag_no_bounds_check) {
  8556. out |= StateFlag_no_bounds_check;
  8557. out &= ~StateFlag_bounds_check;
  8558. } else if (in & StateFlag_bounds_check) {
  8559. out |= StateFlag_bounds_check;
  8560. out &= ~StateFlag_no_bounds_check;
  8561. }
  8562. if (in & StateFlag_no_type_assert) {
  8563. out |= StateFlag_no_type_assert;
  8564. out &= ~StateFlag_type_assert;
  8565. } else if (in & StateFlag_type_assert) {
  8566. out |= StateFlag_type_assert;
  8567. out &= ~StateFlag_no_type_assert;
  8568. }
  8569. c->state_flags = out;
  8570. }
  8571. ExprKind kind = Expr_Stmt;
  8572. o->mode = Addressing_Invalid;
  8573. o->type = t_invalid;
  8574. o->value = {ExactValue_Invalid};
  8575. switch (node->kind) {
  8576. default:
  8577. return kind;
  8578. case_ast_node(be, BadExpr, node)
  8579. return kind;
  8580. case_end;
  8581. case_ast_node(i, Implicit, node)
  8582. switch (i->kind) {
  8583. case Token_context:
  8584. {
  8585. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8586. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8587. return kind;
  8588. }
  8589. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8590. c->scope->flags |= ScopeFlag_ContextDefined;
  8591. }
  8592. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8593. error(node, "'context' has not been defined within this scope");
  8594. // Continue with value
  8595. }
  8596. init_core_context(c->checker);
  8597. o->mode = Addressing_Context;
  8598. o->type = t_context;
  8599. }
  8600. break;
  8601. default:
  8602. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8603. return kind;
  8604. }
  8605. case_end;
  8606. case_ast_node(i, Ident, node);
  8607. check_ident(c, o, node, nullptr, type_hint, false);
  8608. case_end;
  8609. case_ast_node(u, Uninit, node);
  8610. o->mode = Addressing_Value;
  8611. o->type = t_untyped_uninit;
  8612. error(node, "Use of --- outside of variable declaration");
  8613. case_end;
  8614. case_ast_node(bl, BasicLit, node);
  8615. Type *t = t_invalid;
  8616. switch (node->tav.value.kind) {
  8617. case ExactValue_String: t = t_untyped_string; break;
  8618. case ExactValue_Float: t = t_untyped_float; break;
  8619. case ExactValue_Complex: t = t_untyped_complex; break;
  8620. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  8621. case ExactValue_Integer:
  8622. t = t_untyped_integer;
  8623. if (bl->token.kind == Token_Rune) {
  8624. t = t_untyped_rune;
  8625. }
  8626. break;
  8627. default:
  8628. GB_PANIC("Unhandled value type for basic literal");
  8629. break;
  8630. }
  8631. o->mode = Addressing_Constant;
  8632. o->type = t;
  8633. o->value = node->tav.value;
  8634. case_end;
  8635. case_ast_node(bd, BasicDirective, node);
  8636. kind = check_basic_directive_expr(c, o, node, type_hint);
  8637. case_end;
  8638. case_ast_node(pg, ProcGroup, node);
  8639. error(node, "Illegal use of a procedure group");
  8640. o->mode = Addressing_Invalid;
  8641. case_end;
  8642. case_ast_node(pl, ProcLit, node);
  8643. CheckerContext ctx = *c;
  8644. DeclInfo *decl = nullptr;
  8645. Type *type = alloc_type(Type_Proc);
  8646. check_open_scope(&ctx, pl->type);
  8647. {
  8648. decl = make_decl_info(ctx.scope, ctx.decl);
  8649. decl->proc_lit = node;
  8650. ctx.decl = decl;
  8651. defer (ctx.decl = ctx.decl->parent);
  8652. if (pl->tags != 0) {
  8653. error(node, "A procedure literal cannot have tags");
  8654. pl->tags = 0; // TODO(bill): Should I zero this?!
  8655. }
  8656. check_procedure_type(&ctx, type, pl->type);
  8657. if (!is_type_proc(type)) {
  8658. gbString str = expr_to_string(node);
  8659. error(node, "Invalid procedure literal '%s'", str);
  8660. gb_string_free(str);
  8661. check_close_scope(&ctx);
  8662. return kind;
  8663. }
  8664. if (pl->body == nullptr) {
  8665. error(node, "A procedure literal must have a body");
  8666. return kind;
  8667. }
  8668. pl->decl = decl;
  8669. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  8670. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  8671. array_add(&ctx.checker->nested_proc_lits, decl);
  8672. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  8673. }
  8674. check_close_scope(&ctx);
  8675. o->mode = Addressing_Value;
  8676. o->type = type;
  8677. case_end;
  8678. case_ast_node(te, TernaryIfExpr, node);
  8679. kind = check_ternary_if_expr(c, o, node, type_hint);
  8680. case_end;
  8681. case_ast_node(te, TernaryWhenExpr, node);
  8682. kind = check_ternary_when_expr(c, o, node, type_hint);
  8683. case_end;
  8684. case_ast_node(oe, OrElseExpr, node);
  8685. return check_or_else_expr(c, o, node, type_hint);
  8686. case_end;
  8687. case_ast_node(re, OrReturnExpr, node);
  8688. return check_or_return_expr(c, o, node, type_hint);
  8689. case_end;
  8690. case_ast_node(cl, CompoundLit, node);
  8691. kind = check_compound_literal(c, o, node, type_hint);
  8692. case_end;
  8693. case_ast_node(pe, ParenExpr, node);
  8694. kind = check_expr_base(c, o, pe->expr, type_hint);
  8695. node->viral_state_flags |= pe->expr->viral_state_flags;
  8696. o->expr = node;
  8697. case_end;
  8698. case_ast_node(te, TagExpr, node);
  8699. String name = te->name.string;
  8700. error(node, "Unknown tag expression, #%.*s", LIT(name));
  8701. if (te->expr) {
  8702. kind = check_expr_base(c, o, te->expr, type_hint);
  8703. node->viral_state_flags |= te->expr->viral_state_flags;
  8704. }
  8705. o->expr = node;
  8706. case_end;
  8707. case_ast_node(ta, TypeAssertion, node);
  8708. kind = check_type_assertion(c, o, node, type_hint);
  8709. case_end;
  8710. case_ast_node(tc, TypeCast, node);
  8711. check_expr_or_type(c, o, tc->type);
  8712. if (o->mode != Addressing_Type) {
  8713. gbString str = expr_to_string(tc->type);
  8714. error(tc->type, "Expected a type, got %s", str);
  8715. gb_string_free(str);
  8716. o->mode = Addressing_Invalid;
  8717. }
  8718. if (o->mode == Addressing_Invalid) {
  8719. o->expr = node;
  8720. return kind;
  8721. }
  8722. Type *type = o->type;
  8723. check_expr_base(c, o, tc->expr, type);
  8724. node->viral_state_flags |= tc->expr->viral_state_flags;
  8725. if (o->mode != Addressing_Invalid) {
  8726. switch (tc->token.kind) {
  8727. case Token_transmute:
  8728. check_transmute(c, node, o, type);
  8729. break;
  8730. case Token_cast:
  8731. check_cast(c, o, type);
  8732. break;
  8733. default:
  8734. error(node, "Invalid AST: Invalid casting expression");
  8735. o->mode = Addressing_Invalid;
  8736. break;
  8737. }
  8738. }
  8739. return Expr_Expr;
  8740. case_end;
  8741. case_ast_node(ac, AutoCast, node);
  8742. check_expr_base(c, o, ac->expr, type_hint);
  8743. node->viral_state_flags |= ac->expr->viral_state_flags;
  8744. if (o->mode == Addressing_Invalid) {
  8745. o->expr = node;
  8746. return kind;
  8747. }
  8748. if (type_hint) {
  8749. Type *type = type_of_expr(ac->expr);
  8750. check_cast(c, o, type_hint);
  8751. if (is_type_typed(type) && are_types_identical(type, type_hint)) {
  8752. if (check_vet_flags(node) & VetFlag_Extra) {
  8753. error(node, "Redundant 'auto_cast' applied to expression");
  8754. }
  8755. }
  8756. }
  8757. o->expr = node;
  8758. return Expr_Expr;
  8759. case_end;
  8760. case_ast_node(ue, UnaryExpr, node);
  8761. Type *th = type_hint;
  8762. if (ue->op.kind == Token_And) {
  8763. th = type_deref(th);
  8764. }
  8765. check_expr_base(c, o, ue->expr, th);
  8766. node->viral_state_flags |= ue->expr->viral_state_flags;
  8767. if (o->mode != Addressing_Invalid) {
  8768. check_unary_expr(c, o, ue->op, node);
  8769. }
  8770. o->expr = node;
  8771. return Expr_Expr;
  8772. case_end;
  8773. case_ast_node(be, BinaryExpr, node);
  8774. check_binary_expr(c, o, node, type_hint, true);
  8775. if (o->mode == Addressing_Invalid) {
  8776. o->expr = node;
  8777. return kind;
  8778. }
  8779. case_end;
  8780. case_ast_node(se, SelectorExpr, node);
  8781. check_selector(c, o, node, type_hint);
  8782. node->viral_state_flags |= se->expr->viral_state_flags;
  8783. case_end;
  8784. case_ast_node(se, SelectorCallExpr, node);
  8785. return check_selector_call_expr(c, o, node, type_hint);
  8786. case_end;
  8787. case_ast_node(ise, ImplicitSelectorExpr, node);
  8788. return check_implicit_selector_expr(c, o, node, type_hint);
  8789. case_end;
  8790. case_ast_node(ie, IndexExpr, node);
  8791. kind = check_index_expr(c, o, node, type_hint);
  8792. case_end;
  8793. case_ast_node(se, SliceExpr, node);
  8794. kind = check_slice_expr(c, o, node, type_hint);
  8795. case_end;
  8796. case_ast_node(mie, MatrixIndexExpr, node);
  8797. check_matrix_index_expr(c, o, node, type_hint);
  8798. o->expr = node;
  8799. return Expr_Expr;
  8800. case_end;
  8801. case_ast_node(ce, CallExpr, node);
  8802. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  8803. case_end;
  8804. case_ast_node(de, DerefExpr, node);
  8805. check_expr_or_type(c, o, de->expr);
  8806. node->viral_state_flags |= de->expr->viral_state_flags;
  8807. if (o->mode == Addressing_Invalid) {
  8808. o->mode = Addressing_Invalid;
  8809. o->expr = node;
  8810. return kind;
  8811. } else {
  8812. Type *t = base_type(o->type);
  8813. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  8814. o->mode = Addressing_Variable;
  8815. o->type = t->Pointer.elem;
  8816. } else if (t->kind == Type_SoaPointer) {
  8817. o->mode = Addressing_SoaVariable;
  8818. o->type = type_deref(t);
  8819. } else if (t->kind == Type_RelativePointer) {
  8820. if (o->mode != Addressing_Variable) {
  8821. gbString str = expr_to_string(o->expr);
  8822. gbString typ = type_to_string(o->type);
  8823. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  8824. gb_string_free(typ);
  8825. gb_string_free(str);
  8826. }
  8827. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  8828. add_type_info_type(c, o->type);
  8829. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  8830. GB_ASSERT(ptr_type->kind == Type_Pointer);
  8831. o->mode = Addressing_Variable;
  8832. o->type = ptr_type->Pointer.elem;
  8833. } else {
  8834. gbString str = expr_to_string(o->expr);
  8835. gbString typ = type_to_string(o->type);
  8836. begin_error_block();
  8837. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  8838. if (o->type && is_type_multi_pointer(o->type)) {
  8839. error_line("\tDid you mean '%s[0]'?\n", str);
  8840. }
  8841. end_error_block();
  8842. gb_string_free(typ);
  8843. gb_string_free(str);
  8844. o->mode = Addressing_Invalid;
  8845. o->expr = node;
  8846. return kind;
  8847. }
  8848. }
  8849. case_end;
  8850. case_ast_node(ia, InlineAsmExpr, node);
  8851. if (c->curr_proc_decl == nullptr) {
  8852. error(node, "Inline asm expressions are only allowed within a procedure body");
  8853. }
  8854. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  8855. Type *return_type = nullptr;
  8856. for_array(i, ia->param_types) {
  8857. param_types[i] = check_type(c, ia->param_types[i]);
  8858. }
  8859. if (ia->return_type != nullptr) {
  8860. return_type = check_type(c, ia->return_type);
  8861. }
  8862. Operand x = {};
  8863. check_expr(c, &x, ia->asm_string);
  8864. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8865. error(x.expr, "Expected a constant string for the inline asm main parameter");
  8866. }
  8867. check_expr(c, &x, ia->constraints_string);
  8868. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8869. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  8870. }
  8871. Scope *scope = create_scope(c->info, c->scope);
  8872. scope->flags |= ScopeFlag_Proc;
  8873. Type *params = alloc_type_tuple();
  8874. Type *results = alloc_type_tuple();
  8875. if (param_types.count != 0) {
  8876. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  8877. for_array(i, param_types) {
  8878. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  8879. }
  8880. }
  8881. if (return_type != nullptr) {
  8882. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  8883. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  8884. }
  8885. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  8886. o->type = pt;
  8887. o->mode = Addressing_Value;
  8888. o->expr = node;
  8889. return Expr_Expr;
  8890. case_end;
  8891. case Ast_TypeidType:
  8892. case Ast_PolyType:
  8893. case Ast_ProcType:
  8894. case Ast_PointerType:
  8895. case Ast_MultiPointerType:
  8896. case Ast_ArrayType:
  8897. case Ast_DynamicArrayType:
  8898. case Ast_StructType:
  8899. case Ast_UnionType:
  8900. case Ast_EnumType:
  8901. case Ast_MapType:
  8902. case Ast_BitSetType:
  8903. case Ast_MatrixType:
  8904. case Ast_RelativeType:
  8905. o->mode = Addressing_Type;
  8906. o->type = check_type(c, node);
  8907. break;
  8908. }
  8909. kind = Expr_Expr;
  8910. o->expr = node;
  8911. return kind;
  8912. }
  8913. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8914. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  8915. if (o->type != nullptr && core_type(o->type) == nullptr) {
  8916. o->type = t_invalid;
  8917. gbString xs = expr_to_string(o->expr);
  8918. if (o->mode == Addressing_Type) {
  8919. error(o->expr, "Invalid type usage '%s'", xs);
  8920. } else {
  8921. error(o->expr, "Invalid expression '%s'", xs);
  8922. }
  8923. gb_string_free(xs);
  8924. }
  8925. if (o->type != nullptr && is_type_untyped(o->type)) {
  8926. add_untyped(c, node, o->mode, o->type, o->value);
  8927. }
  8928. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  8929. add_type_and_value(c, node, o->mode, o->type, o->value);
  8930. return kind;
  8931. }
  8932. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  8933. check_expr_base(c, o, e, nullptr);
  8934. switch (o->mode) {
  8935. default:
  8936. return; // NOTE(bill): Valid
  8937. case Addressing_NoValue:
  8938. error_operand_no_value(o);
  8939. break;
  8940. }
  8941. o->mode = Addressing_Invalid;
  8942. }
  8943. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  8944. check_expr_base(c, o, e, nullptr);
  8945. switch (o->mode) {
  8946. default:
  8947. return; // NOTE(bill): Valid
  8948. case Addressing_NoValue:
  8949. error_operand_no_value(o);
  8950. break;
  8951. case Addressing_Type:
  8952. error_operand_not_expression(o);
  8953. break;
  8954. }
  8955. o->mode = Addressing_Invalid;
  8956. }
  8957. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  8958. check_expr_base(c, o, e, type_hint);
  8959. switch (o->mode) {
  8960. default:
  8961. return; // NOTE(bill): Valid
  8962. case Addressing_NoValue:
  8963. error_operand_no_value(o);
  8964. break;
  8965. case Addressing_Type:
  8966. error_operand_not_expression(o);
  8967. break;
  8968. }
  8969. o->mode = Addressing_Invalid;
  8970. }
  8971. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  8972. if (o->mode == Addressing_Value) {
  8973. // NOTE(bill): Tuples are not first class thus never named
  8974. if (o->type->kind == Type_Tuple) {
  8975. isize count = o->type->Tuple.variables.count;
  8976. error(o->expr,
  8977. "%td-valued expression found where single value expected", count);
  8978. o->mode = Addressing_Invalid;
  8979. GB_ASSERT(count != 1);
  8980. }
  8981. }
  8982. }
  8983. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  8984. check_multi_expr(c, o, e);
  8985. check_not_tuple(c, o);
  8986. }
  8987. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  8988. check_expr_base(c, o, e, type_hint);
  8989. check_not_tuple(c, o);
  8990. error_operand_no_value(o);
  8991. }
  8992. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  8993. switch (v.kind) {
  8994. case ExactValue_Invalid:
  8995. return true;
  8996. case ExactValue_Bool:
  8997. return !v.value_bool;
  8998. case ExactValue_String:
  8999. return v.value_string.len == 0;
  9000. case ExactValue_Integer:
  9001. return big_int_is_zero(&v.value_integer);
  9002. case ExactValue_Float:
  9003. return v.value_float == 0.0;
  9004. case ExactValue_Complex:
  9005. if (v.value_complex) {
  9006. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9007. }
  9008. return true;
  9009. case ExactValue_Quaternion:
  9010. if (v.value_quaternion) {
  9011. return v.value_quaternion->real == 0.0 &&
  9012. v.value_quaternion->imag == 0.0 &&
  9013. v.value_quaternion->jmag == 0.0 &&
  9014. v.value_quaternion->kmag == 0.0;
  9015. }
  9016. return true;
  9017. case ExactValue_Pointer:
  9018. return v.value_pointer == 0;
  9019. case ExactValue_Compound:
  9020. if (v.value_compound == nullptr) {
  9021. return true;
  9022. } else {
  9023. ast_node(cl, CompoundLit, v.value_compound);
  9024. if (cl->elems.count == 0) {
  9025. return true;
  9026. } else {
  9027. for (Ast *elem : cl->elems) {
  9028. if (elem->tav.mode != Addressing_Constant) {
  9029. return false;
  9030. }
  9031. if (!is_exact_value_zero(elem->tav.value)) {
  9032. return false;
  9033. }
  9034. }
  9035. return true;
  9036. }
  9037. }
  9038. case ExactValue_Procedure:
  9039. return v.value_procedure == nullptr;
  9040. case ExactValue_Typeid:
  9041. return v.value_typeid == nullptr;
  9042. }
  9043. return true;
  9044. }
  9045. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9046. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9047. for_array(i, params) {
  9048. if (i > 0) {
  9049. str = gb_string_appendc(str, ", ");
  9050. }
  9051. str = write_expr_to_string(str, params[i], false);
  9052. }
  9053. return str;
  9054. }
  9055. gb_internal gbString string_append_string(gbString str, String string) {
  9056. if (string.len > 0) {
  9057. return gb_string_append_length(str, &string[0], string.len);
  9058. }
  9059. return str;
  9060. }
  9061. gb_internal gbString string_append_token(gbString str, Token token) {
  9062. str = string_append_string(str, token.string);
  9063. return str;
  9064. }
  9065. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9066. if (node == nullptr)
  9067. return str;
  9068. if (is_ast_stmt(node)) {
  9069. GB_ASSERT("stmt passed to write_expr_to_string");
  9070. }
  9071. switch (node->kind) {
  9072. default:
  9073. str = gb_string_appendc(str, "(BadExpr)");
  9074. break;
  9075. case_ast_node(i, Ident, node);
  9076. str = string_append_token(str, i->token);
  9077. case_end;
  9078. case_ast_node(i, Implicit, node);
  9079. str = string_append_token(str, *i);
  9080. case_end;
  9081. case_ast_node(bl, BasicLit, node);
  9082. str = string_append_token(str, bl->token);
  9083. case_end;
  9084. case_ast_node(bd, BasicDirective, node);
  9085. str = gb_string_append_rune(str, '#');
  9086. str = string_append_string(str, bd->name.string);
  9087. case_end;
  9088. case_ast_node(ud, Uninit, node);
  9089. str = gb_string_appendc(str, "---");
  9090. case_end;
  9091. case_ast_node(pg, ProcGroup, node);
  9092. str = gb_string_appendc(str, "proc{");
  9093. for_array(i, pg->args) {
  9094. if (i > 0) str = gb_string_appendc(str, ", ");
  9095. str = write_expr_to_string(str, pg->args[i], shorthand);
  9096. }
  9097. str = gb_string_append_rune(str, '}');
  9098. case_end;
  9099. case_ast_node(pl, ProcLit, node);
  9100. str = write_expr_to_string(str, pl->type, shorthand);
  9101. if (pl->body) {
  9102. str = gb_string_appendc(str, " {...}");
  9103. } else {
  9104. str = gb_string_appendc(str, " ---");
  9105. }
  9106. case_end;
  9107. case_ast_node(cl, CompoundLit, node);
  9108. str = write_expr_to_string(str, cl->type, shorthand);
  9109. str = gb_string_append_rune(str, '{');
  9110. if (shorthand) {
  9111. str = gb_string_appendc(str, "...");
  9112. } else {
  9113. for_array(i, cl->elems) {
  9114. if (i > 0) str = gb_string_appendc(str, ", ");
  9115. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9116. }
  9117. }
  9118. str = gb_string_append_rune(str, '}');
  9119. case_end;
  9120. case_ast_node(te, TagExpr, node);
  9121. str = gb_string_append_rune(str, '#');
  9122. str = string_append_token(str, te->name);
  9123. str = write_expr_to_string(str, te->expr, shorthand);
  9124. case_end;
  9125. case_ast_node(ue, UnaryExpr, node);
  9126. str = string_append_token(str, ue->op);
  9127. str = write_expr_to_string(str, ue->expr, shorthand);
  9128. case_end;
  9129. case_ast_node(de, DerefExpr, node);
  9130. str = write_expr_to_string(str, de->expr, shorthand);
  9131. str = gb_string_append_rune(str, '^');
  9132. case_end;
  9133. case_ast_node(be, BinaryExpr, node);
  9134. str = write_expr_to_string(str, be->left, shorthand);
  9135. str = gb_string_append_rune(str, ' ');
  9136. str = string_append_token(str, be->op);
  9137. str = gb_string_append_rune(str, ' ');
  9138. str = write_expr_to_string(str, be->right, shorthand);
  9139. case_end;
  9140. case_ast_node(te, TernaryIfExpr, node);
  9141. TokenPos x = ast_token(te->x).pos;
  9142. TokenPos cond = ast_token(te->cond).pos;
  9143. if (x < cond) {
  9144. str = write_expr_to_string(str, te->x, shorthand);
  9145. str = gb_string_appendc(str, " if ");
  9146. str = write_expr_to_string(str, te->cond, shorthand);
  9147. str = gb_string_appendc(str, " else ");
  9148. str = write_expr_to_string(str, te->y, shorthand);
  9149. } else {
  9150. str = write_expr_to_string(str, te->cond, shorthand);
  9151. str = gb_string_appendc(str, " ? ");
  9152. str = write_expr_to_string(str, te->x, shorthand);
  9153. str = gb_string_appendc(str, " : ");
  9154. str = write_expr_to_string(str, te->y, shorthand);
  9155. }
  9156. case_end;
  9157. case_ast_node(te, TernaryWhenExpr, node);
  9158. str = write_expr_to_string(str, te->x, shorthand);
  9159. str = gb_string_appendc(str, " when ");
  9160. str = write_expr_to_string(str, te->cond, shorthand);
  9161. str = gb_string_appendc(str, " else ");
  9162. str = write_expr_to_string(str, te->y, shorthand);
  9163. case_end;
  9164. case_ast_node(oe, OrElseExpr, node);
  9165. str = write_expr_to_string(str, oe->x, shorthand);
  9166. str = gb_string_appendc(str, " or_else ");
  9167. str = write_expr_to_string(str, oe->y, shorthand);
  9168. case_end;
  9169. case_ast_node(oe, OrReturnExpr, node);
  9170. str = write_expr_to_string(str, oe->expr, shorthand);
  9171. str = gb_string_appendc(str, " or_return");
  9172. case_end;
  9173. case_ast_node(pe, ParenExpr, node);
  9174. str = gb_string_append_rune(str, '(');
  9175. str = write_expr_to_string(str, pe->expr, shorthand);
  9176. str = gb_string_append_rune(str, ')');
  9177. case_end;
  9178. case_ast_node(se, SelectorExpr, node);
  9179. str = write_expr_to_string(str, se->expr, shorthand);
  9180. str = string_append_token(str, se->token);
  9181. str = write_expr_to_string(str, se->selector, shorthand);
  9182. case_end;
  9183. case_ast_node(se, ImplicitSelectorExpr, node);
  9184. str = gb_string_append_rune(str, '.');
  9185. str = write_expr_to_string(str, se->selector, shorthand);
  9186. case_end;
  9187. case_ast_node(se, SelectorCallExpr, node);
  9188. str = write_expr_to_string(str, se->expr, shorthand);
  9189. str = gb_string_appendc(str, "(");
  9190. ast_node(ce, CallExpr, se->call);
  9191. isize start = se->modified_call ? 1 : 0;
  9192. for (isize i = start; i < ce->args.count; i++) {
  9193. Ast *arg = ce->args[i];
  9194. if (i > start) {
  9195. str = gb_string_appendc(str, ", ");
  9196. }
  9197. str = write_expr_to_string(str, arg, shorthand);
  9198. }
  9199. str = gb_string_appendc(str, ")");
  9200. case_end;
  9201. case_ast_node(ta, TypeAssertion, node);
  9202. str = write_expr_to_string(str, ta->expr, shorthand);
  9203. if (ta->type != nullptr &&
  9204. ta->type->kind == Ast_UnaryExpr &&
  9205. ta->type->UnaryExpr.op.kind == Token_Question) {
  9206. str = gb_string_appendc(str, ".?");
  9207. } else {
  9208. str = gb_string_appendc(str, ".(");
  9209. str = write_expr_to_string(str, ta->type, shorthand);
  9210. str = gb_string_append_rune(str, ')');
  9211. }
  9212. case_end;
  9213. case_ast_node(tc, TypeCast, node);
  9214. str = string_append_token(str, tc->token);
  9215. str = gb_string_append_rune(str, '(');
  9216. str = write_expr_to_string(str, tc->type, shorthand);
  9217. str = gb_string_append_rune(str, ')');
  9218. str = write_expr_to_string(str, tc->expr, shorthand);
  9219. case_end;
  9220. case_ast_node(ac, AutoCast, node);
  9221. str = string_append_token(str, ac->token);
  9222. str = gb_string_append_rune(str, ' ');
  9223. str = write_expr_to_string(str, ac->expr, shorthand);
  9224. case_end;
  9225. case_ast_node(ie, IndexExpr, node);
  9226. str = write_expr_to_string(str, ie->expr, shorthand);
  9227. str = gb_string_append_rune(str, '[');
  9228. str = write_expr_to_string(str, ie->index, shorthand);
  9229. str = gb_string_append_rune(str, ']');
  9230. case_end;
  9231. case_ast_node(se, SliceExpr, node);
  9232. str = write_expr_to_string(str, se->expr, shorthand);
  9233. str = gb_string_append_rune(str, '[');
  9234. str = write_expr_to_string(str, se->low, shorthand);
  9235. str = string_append_token(str, se->interval);
  9236. str = write_expr_to_string(str, se->high, shorthand);
  9237. str = gb_string_append_rune(str, ']');
  9238. case_end;
  9239. case_ast_node(mie, MatrixIndexExpr, node);
  9240. str = write_expr_to_string(str, mie->expr, shorthand);
  9241. str = gb_string_append_rune(str, '[');
  9242. str = write_expr_to_string(str, mie->row_index, shorthand);
  9243. str = gb_string_appendc(str, ", ");
  9244. str = write_expr_to_string(str, mie->column_index, shorthand);
  9245. str = gb_string_append_rune(str, ']');
  9246. case_end;
  9247. case_ast_node(e, Ellipsis, node);
  9248. str = gb_string_appendc(str, "..");
  9249. str = write_expr_to_string(str, e->expr, shorthand);
  9250. case_end;
  9251. case_ast_node(fv, FieldValue, node);
  9252. str = write_expr_to_string(str, fv->field, shorthand);
  9253. str = gb_string_appendc(str, " = ");
  9254. str = write_expr_to_string(str, fv->value, shorthand);
  9255. case_end;
  9256. case_ast_node(fv, EnumFieldValue, node);
  9257. str = write_expr_to_string(str, fv->name, shorthand);
  9258. if (fv->value) {
  9259. str = gb_string_appendc(str, " = ");
  9260. str = write_expr_to_string(str, fv->value, shorthand);
  9261. }
  9262. case_end;
  9263. case_ast_node(ht, HelperType, node);
  9264. str = gb_string_appendc(str, "#type ");
  9265. str = write_expr_to_string(str, ht->type, shorthand);
  9266. case_end;
  9267. case_ast_node(ht, DistinctType, node);
  9268. str = gb_string_appendc(str, "distinct ");
  9269. str = write_expr_to_string(str, ht->type, shorthand);
  9270. case_end;
  9271. case_ast_node(pt, PolyType, node);
  9272. str = gb_string_append_rune(str, '$');
  9273. str = write_expr_to_string(str, pt->type, shorthand);
  9274. if (pt->specialization != nullptr) {
  9275. str = gb_string_append_rune(str, '/');
  9276. str = write_expr_to_string(str, pt->specialization, shorthand);
  9277. }
  9278. case_end;
  9279. case_ast_node(pt, PointerType, node);
  9280. str = gb_string_append_rune(str, '^');
  9281. str = write_expr_to_string(str, pt->type, shorthand);
  9282. case_end;
  9283. case_ast_node(pt, MultiPointerType, node);
  9284. str = gb_string_appendc(str, "[^]");
  9285. str = write_expr_to_string(str, pt->type, shorthand);
  9286. case_end;
  9287. case_ast_node(at, ArrayType, node);
  9288. str = gb_string_append_rune(str, '[');
  9289. if (at->count != nullptr &&
  9290. at->count->kind == Ast_UnaryExpr &&
  9291. at->count->UnaryExpr.op.kind == Token_Question) {
  9292. str = gb_string_appendc(str, "?");
  9293. } else {
  9294. str = write_expr_to_string(str, at->count, shorthand);
  9295. }
  9296. str = gb_string_append_rune(str, ']');
  9297. str = write_expr_to_string(str, at->elem, shorthand);
  9298. case_end;
  9299. case_ast_node(at, DynamicArrayType, node);
  9300. str = gb_string_appendc(str, "[dynamic]");
  9301. str = write_expr_to_string(str, at->elem, shorthand);
  9302. case_end;
  9303. case_ast_node(bs, BitSetType, node);
  9304. str = gb_string_appendc(str, "bit_set[");
  9305. str = write_expr_to_string(str, bs->elem, shorthand);
  9306. str = gb_string_appendc(str, "]");
  9307. case_end;
  9308. case_ast_node(mt, MapType, node);
  9309. str = gb_string_appendc(str, "map[");
  9310. str = write_expr_to_string(str, mt->key, shorthand);
  9311. str = gb_string_append_rune(str, ']');
  9312. str = write_expr_to_string(str, mt->value, shorthand);
  9313. case_end;
  9314. case_ast_node(mt, MatrixType, node);
  9315. str = gb_string_appendc(str, "matrix[");
  9316. str = write_expr_to_string(str, mt->row_count, shorthand);
  9317. str = gb_string_appendc(str, ", ");
  9318. str = write_expr_to_string(str, mt->column_count, shorthand);
  9319. str = gb_string_append_rune(str, ']');
  9320. str = write_expr_to_string(str, mt->elem, shorthand);
  9321. case_end;
  9322. case_ast_node(f, Field, node);
  9323. if (f->flags&FieldFlag_using) {
  9324. str = gb_string_appendc(str, "using ");
  9325. }
  9326. if (f->flags&FieldFlag_no_alias) {
  9327. str = gb_string_appendc(str, "#no_alias ");
  9328. }
  9329. if (f->flags&FieldFlag_c_vararg) {
  9330. str = gb_string_appendc(str, "#c_vararg ");
  9331. }
  9332. if (f->flags&FieldFlag_any_int) {
  9333. str = gb_string_appendc(str, "#any_int ");
  9334. }
  9335. if (f->flags&FieldFlag_const) {
  9336. str = gb_string_appendc(str, "#const ");
  9337. }
  9338. if (f->flags&FieldFlag_subtype) {
  9339. str = gb_string_appendc(str, "#subtype ");
  9340. }
  9341. for_array(i, f->names) {
  9342. Ast *name = f->names[i];
  9343. if (i > 0) str = gb_string_appendc(str, ", ");
  9344. str = write_expr_to_string(str, name, shorthand);
  9345. }
  9346. if (f->names.count > 0) {
  9347. if (f->type == nullptr && f->default_value != nullptr) {
  9348. str = gb_string_append_rune(str, ' ');
  9349. }
  9350. str = gb_string_appendc(str, ":");
  9351. }
  9352. if (f->type != nullptr) {
  9353. str = gb_string_append_rune(str, ' ');
  9354. str = write_expr_to_string(str, f->type, shorthand);
  9355. }
  9356. if (f->default_value != nullptr) {
  9357. if (f->type != nullptr) {
  9358. str = gb_string_append_rune(str, ' ');
  9359. }
  9360. str = gb_string_appendc(str, "= ");
  9361. str = write_expr_to_string(str, f->default_value, shorthand);
  9362. }
  9363. case_end;
  9364. case_ast_node(f, FieldList, node);
  9365. bool has_name = false;
  9366. for_array(i, f->list) {
  9367. ast_node(field, Field, f->list[i]);
  9368. if (field->names.count > 1) {
  9369. has_name = true;
  9370. break;
  9371. }
  9372. if (field->names.count == 0) {
  9373. continue;
  9374. }
  9375. if (!is_blank_ident(field->names[0])) {
  9376. has_name = true;
  9377. break;
  9378. }
  9379. }
  9380. for_array(i, f->list) {
  9381. if (i > 0) str = gb_string_appendc(str, ", ");
  9382. if (has_name) {
  9383. str = write_expr_to_string(str, f->list[i], shorthand);
  9384. } else {
  9385. ast_node(field, Field, f->list[i]);
  9386. if (field->flags&FieldFlag_using) {
  9387. str = gb_string_appendc(str, "using ");
  9388. }
  9389. if (field->flags&FieldFlag_no_alias) {
  9390. str = gb_string_appendc(str, "#no_alias ");
  9391. }
  9392. if (field->flags&FieldFlag_c_vararg) {
  9393. str = gb_string_appendc(str, "#c_vararg ");
  9394. }
  9395. str = write_expr_to_string(str, field->type, shorthand);
  9396. }
  9397. }
  9398. case_end;
  9399. case_ast_node(ce, CallExpr, node);
  9400. switch (ce->inlining) {
  9401. case ProcInlining_inline:
  9402. str = gb_string_appendc(str, "#force_inline ");
  9403. break;
  9404. case ProcInlining_no_inline:
  9405. str = gb_string_appendc(str, "#force_no_inline ");
  9406. break;
  9407. }
  9408. str = write_expr_to_string(str, ce->proc, shorthand);
  9409. str = gb_string_appendc(str, "(");
  9410. isize idx0 = cast(isize)ce->was_selector;
  9411. for (isize i = idx0; i < ce->args.count; i++) {
  9412. Ast *arg = ce->args[i];
  9413. if (i > idx0) {
  9414. str = gb_string_appendc(str, ", ");
  9415. }
  9416. str = write_expr_to_string(str, arg, shorthand);
  9417. }
  9418. str = gb_string_appendc(str, ")");
  9419. case_end;
  9420. case_ast_node(tt, TypeidType, node);
  9421. str = gb_string_appendc(str, "typeid");
  9422. if (tt->specialization) {
  9423. str = gb_string_appendc(str, "/");
  9424. str = write_expr_to_string(str, tt->specialization, shorthand);
  9425. }
  9426. case_end;
  9427. case_ast_node(pt, ProcType, node);
  9428. str = gb_string_appendc(str, "proc(");
  9429. str = write_expr_to_string(str, pt->params, shorthand);
  9430. str = gb_string_appendc(str, ")");
  9431. if (pt->results != nullptr) {
  9432. str = gb_string_appendc(str, " -> ");
  9433. bool parens_needed = false;
  9434. if (pt->results && pt->results->kind == Ast_FieldList) {
  9435. for (Ast *field : pt->results->FieldList.list) {
  9436. ast_node(f, Field, field);
  9437. if (f->names.count != 0) {
  9438. parens_needed = true;
  9439. break;
  9440. }
  9441. }
  9442. }
  9443. if (parens_needed) {
  9444. str = gb_string_append_rune(str, '(');
  9445. }
  9446. str = write_expr_to_string(str, pt->results, shorthand);
  9447. if (parens_needed) {
  9448. str = gb_string_append_rune(str, ')');
  9449. }
  9450. }
  9451. case_end;
  9452. case_ast_node(st, StructType, node);
  9453. str = gb_string_appendc(str, "struct ");
  9454. if (st->polymorphic_params) {
  9455. str = gb_string_append_rune(str, '(');
  9456. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9457. str = gb_string_appendc(str, ") ");
  9458. }
  9459. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9460. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9461. if (st->align) {
  9462. str = gb_string_appendc(str, "#align ");
  9463. str = write_expr_to_string(str, st->align, shorthand);
  9464. str = gb_string_append_rune(str, ' ');
  9465. }
  9466. str = gb_string_append_rune(str, '{');
  9467. if (shorthand) {
  9468. str = gb_string_appendc(str, "...");
  9469. } else {
  9470. str = write_struct_fields_to_string(str, st->fields);
  9471. }
  9472. str = gb_string_append_rune(str, '}');
  9473. case_end;
  9474. case_ast_node(st, UnionType, node);
  9475. str = gb_string_appendc(str, "union ");
  9476. if (st->polymorphic_params) {
  9477. str = gb_string_append_rune(str, '(');
  9478. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9479. str = gb_string_appendc(str, ") ");
  9480. }
  9481. switch (st->kind) {
  9482. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9483. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9484. }
  9485. if (st->align) {
  9486. str = gb_string_appendc(str, "#align ");
  9487. str = write_expr_to_string(str, st->align, shorthand);
  9488. str = gb_string_append_rune(str, ' ');
  9489. }
  9490. str = gb_string_append_rune(str, '{');
  9491. if (shorthand) {
  9492. str = gb_string_appendc(str, "...");
  9493. } else {
  9494. str = write_struct_fields_to_string(str, st->variants);
  9495. }
  9496. str = gb_string_append_rune(str, '}');
  9497. case_end;
  9498. case_ast_node(et, EnumType, node);
  9499. str = gb_string_appendc(str, "enum ");
  9500. if (et->base_type != nullptr) {
  9501. str = write_expr_to_string(str, et->base_type, shorthand);
  9502. str = gb_string_append_rune(str, ' ');
  9503. }
  9504. str = gb_string_append_rune(str, '{');
  9505. if (shorthand) {
  9506. str = gb_string_appendc(str, "...");
  9507. } else {
  9508. for_array(i, et->fields) {
  9509. if (i > 0) {
  9510. str = gb_string_appendc(str, ", ");
  9511. }
  9512. str = write_expr_to_string(str, et->fields[i], shorthand);
  9513. }
  9514. }
  9515. str = gb_string_append_rune(str, '}');
  9516. case_end;
  9517. case_ast_node(rt, RelativeType, node);
  9518. str = write_expr_to_string(str, rt->tag, shorthand);
  9519. str = gb_string_appendc(str, "" );
  9520. str = write_expr_to_string(str, rt->type, shorthand);
  9521. case_end;
  9522. case_ast_node(ia, InlineAsmExpr, node);
  9523. str = gb_string_appendc(str, "asm(");
  9524. for_array(i, ia->param_types) {
  9525. if (i > 0) {
  9526. str = gb_string_appendc(str, ", ");
  9527. }
  9528. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9529. }
  9530. str = gb_string_appendc(str, ")");
  9531. if (ia->return_type != nullptr) {
  9532. str = gb_string_appendc(str, " -> ");
  9533. str = write_expr_to_string(str, ia->return_type, shorthand);
  9534. }
  9535. if (ia->has_side_effects) {
  9536. str = gb_string_appendc(str, " #side_effects");
  9537. }
  9538. if (ia->is_align_stack) {
  9539. str = gb_string_appendc(str, " #stack_align");
  9540. }
  9541. if (ia->dialect) {
  9542. str = gb_string_appendc(str, " #");
  9543. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9544. }
  9545. str = gb_string_appendc(str, " {");
  9546. if (shorthand) {
  9547. str = gb_string_appendc(str, "...");
  9548. } else {
  9549. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9550. str = gb_string_appendc(str, ", ");
  9551. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9552. }
  9553. str = gb_string_appendc(str, "}");
  9554. case_end;
  9555. }
  9556. return str;
  9557. }
  9558. gb_internal gbString expr_to_string(Ast *expression) {
  9559. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9560. }
  9561. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  9562. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  9563. }
  9564. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  9565. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9566. }