check_expr.cpp 318 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092
  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. } else if (!is_type_integer(x->type)) {
  2440. gbString x_str = expr_to_string(x->expr);
  2441. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2442. gb_string_free(x_str);
  2443. x->mode = Addressing_Invalid;
  2444. }
  2445. // x->value = x_val;
  2446. return;
  2447. }
  2448. }
  2449. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2450. gbString err_str = expr_to_string(y->expr);
  2451. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2452. gb_string_free(err_str);
  2453. }
  2454. if (!is_type_integer(x->type)) {
  2455. gbString err_str = expr_to_string(x->expr);
  2456. error(node, "Shift operand '%s' must be an integer", err_str);
  2457. gb_string_free(err_str);
  2458. x->mode = Addressing_Invalid;
  2459. return;
  2460. }
  2461. if (is_type_untyped(y->type)) {
  2462. convert_to_typed(c, y, t_uint);
  2463. }
  2464. x->mode = Addressing_Value;
  2465. }
  2466. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2467. if (check_is_assignable_to(c, operand, y)) {
  2468. return true;
  2469. }
  2470. bool is_constant = operand->mode == Addressing_Constant;
  2471. Type *x = operand->type;
  2472. Type *src = core_type(x);
  2473. Type *dst = core_type(y);
  2474. if (are_types_identical(src, dst)) {
  2475. return true;
  2476. }
  2477. // if (is_type_tuple(src)) {
  2478. // Ast *expr = unparen_expr(operand->expr);
  2479. // if (expr && expr->kind == Ast_CallExpr) {
  2480. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2481. // ast_node(ce, CallExpr, expr);
  2482. // Type *pt = base_type(type_of_expr(ce->proc));
  2483. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2484. // if (pt->Proc.result_count > 0) {
  2485. // Operand op = *operand;
  2486. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2487. // bool ok = check_is_castable_to(c, &op, y);
  2488. // if (ok) {
  2489. // ce->optional_ok_one = true;
  2490. // }
  2491. // return ok;
  2492. // }
  2493. // }
  2494. // }
  2495. // }
  2496. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2497. if (is_type_u8_array(dst)) {
  2498. String s = operand->value.value_string;
  2499. return s.len == dst->Array.count;
  2500. }
  2501. if (is_type_rune_array(dst)) {
  2502. String s = operand->value.value_string;
  2503. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2504. }
  2505. }
  2506. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2507. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2508. return dst->Array.count == src->Array.count;
  2509. }
  2510. }
  2511. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2512. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2513. }
  2514. // Cast between booleans and integers
  2515. if (is_type_boolean(src) || is_type_integer(src)) {
  2516. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2517. return true;
  2518. }
  2519. }
  2520. // Cast between numbers
  2521. if (is_type_integer(src) || is_type_float(src)) {
  2522. if (is_type_integer(dst) || is_type_float(dst)) {
  2523. return true;
  2524. }
  2525. }
  2526. if (is_type_integer(src) && is_type_rune(dst)) {
  2527. return true;
  2528. }
  2529. if (is_type_rune(src) && is_type_integer(dst)) {
  2530. return true;
  2531. }
  2532. if (is_type_complex(src) && is_type_complex(dst)) {
  2533. return true;
  2534. }
  2535. if (is_type_float(src) && is_type_complex(dst)) {
  2536. return true;
  2537. }
  2538. if (is_type_float(src) && is_type_quaternion(dst)) {
  2539. return true;
  2540. }
  2541. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2542. return true;
  2543. }
  2544. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2545. return true;
  2546. }
  2547. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2548. GB_ASSERT(src->kind == Type_Matrix);
  2549. GB_ASSERT(dst->kind == Type_Matrix);
  2550. Operand op = *operand;
  2551. op.type = src->Matrix.elem;
  2552. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2553. return false;
  2554. }
  2555. if (src->Matrix.row_count != src->Matrix.column_count) {
  2556. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2557. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2558. return src_count == dst_count;
  2559. }
  2560. return is_matrix_square(dst) && is_matrix_square(src);
  2561. }
  2562. // Cast between pointers
  2563. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2564. return true;
  2565. }
  2566. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2567. return true;
  2568. }
  2569. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2570. return true;
  2571. }
  2572. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2573. return true;
  2574. }
  2575. // uintptr <-> pointer
  2576. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2577. return true;
  2578. }
  2579. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2580. return true;
  2581. }
  2582. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2583. return true;
  2584. }
  2585. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2586. return true;
  2587. }
  2588. // []byte/[]u8 <-> string (not cstring)
  2589. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2590. return true;
  2591. }
  2592. // cstring -> string
  2593. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2594. if (operand->mode != Addressing_Constant) {
  2595. add_package_dependency(c, "runtime", "cstring_to_string");
  2596. }
  2597. return true;
  2598. }
  2599. // cstring -> ^u8
  2600. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2601. return !is_constant;
  2602. }
  2603. // cstring -> [^]u8
  2604. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2605. return !is_constant;
  2606. }
  2607. // cstring -> rawptr
  2608. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2609. return !is_constant;
  2610. }
  2611. // ^u8 -> cstring
  2612. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2613. return !is_constant;
  2614. }
  2615. // [^]u8 -> cstring
  2616. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2617. return !is_constant;
  2618. }
  2619. // rawptr -> cstring
  2620. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2621. return !is_constant;
  2622. }
  2623. // proc <-> proc
  2624. if (is_type_proc(src) && is_type_proc(dst)) {
  2625. return true;
  2626. }
  2627. // proc -> rawptr
  2628. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2629. return true;
  2630. }
  2631. // rawptr -> proc
  2632. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2633. return true;
  2634. }
  2635. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2636. if (src->SimdVector.count != dst->SimdVector.count) {
  2637. return false;
  2638. }
  2639. Type *elem_src = base_array_type(src);
  2640. Type *elem_dst = base_array_type(dst);
  2641. Operand x = {};
  2642. x.type = elem_src;
  2643. x.mode = Addressing_Value;
  2644. return check_is_castable_to(c, &x, elem_dst);
  2645. }
  2646. if (is_type_simd_vector(dst)) {
  2647. Type *elem = base_array_type(dst);
  2648. if (check_is_castable_to(c, operand, elem)) {
  2649. return true;
  2650. }
  2651. }
  2652. return false;
  2653. }
  2654. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2655. bool is_const_expr = x->mode == Addressing_Constant;
  2656. Type *bt = base_type(type);
  2657. if (is_const_expr && is_type_constant_type(bt)) {
  2658. if (core_type(bt)->kind == Type_Basic) {
  2659. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2660. return true;
  2661. } else if (check_is_castable_to(c, x, type)) {
  2662. if (is_type_pointer(type)) {
  2663. return true;
  2664. }
  2665. }
  2666. } else if (check_is_castable_to(c, x, type)) {
  2667. x->value = {};
  2668. x->mode = Addressing_Value;
  2669. return true;
  2670. }
  2671. } else if (check_is_castable_to(c, x, type)) {
  2672. if (x->mode != Addressing_Constant) {
  2673. x->mode = Addressing_Value;
  2674. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2675. x->mode = Addressing_Value;
  2676. } else if (is_type_union(type)) {
  2677. x->mode = Addressing_Value;
  2678. }
  2679. if (x->mode == Addressing_Value) {
  2680. x->value = {};
  2681. }
  2682. return true;
  2683. }
  2684. return false;
  2685. }
  2686. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2687. if (!is_operand_value(*x)) {
  2688. error(x->expr, "Only values can be casted");
  2689. x->mode = Addressing_Invalid;
  2690. return;
  2691. }
  2692. bool is_const_expr = x->mode == Addressing_Constant;
  2693. bool can_convert = check_cast_internal(c, x, type);
  2694. if (!can_convert) {
  2695. TEMPORARY_ALLOCATOR_GUARD();
  2696. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2697. gbString to_type = type_to_string(type, temporary_allocator());
  2698. gbString from_type = type_to_string(x->type, temporary_allocator());
  2699. x->mode = Addressing_Invalid;
  2700. begin_error_block();
  2701. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2702. if (is_const_expr) {
  2703. gbString val_str = exact_value_to_string(x->value);
  2704. if (is_type_float(x->type) && is_type_integer(type)) {
  2705. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2706. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2707. x->mode = Addressing_Constant;
  2708. x->type = type;
  2709. } else {
  2710. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2711. if (is_type_numeric(type)) {
  2712. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2713. x->mode = Addressing_Constant;
  2714. x->type = type;
  2715. }
  2716. }
  2717. gb_string_free(val_str);
  2718. }
  2719. check_cast_error_suggestion(c, x, type);
  2720. end_error_block();
  2721. return;
  2722. }
  2723. if (is_type_untyped(x->type)) {
  2724. Type *final_type = type;
  2725. if (is_const_expr && !is_type_constant_type(type)) {
  2726. final_type = default_type(x->type);
  2727. }
  2728. update_untyped_expr_type(c, x->expr, final_type, true);
  2729. }
  2730. x->type = type;
  2731. }
  2732. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2733. if (!is_operand_value(*o)) {
  2734. error(o->expr, "'transmute' can only be applied to values");
  2735. o->mode = Addressing_Invalid;
  2736. return false;
  2737. }
  2738. // if (o->mode == Addressing_Constant) {
  2739. // gbString expr_str = expr_to_string(o->expr);
  2740. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2741. // gb_string_free(expr_str);
  2742. // o->mode = Addressing_Invalid;
  2743. // o->expr = node;
  2744. // return false;
  2745. // }
  2746. Type *src_t = o->type;
  2747. Type *dst_t = t;
  2748. Type *src_bt = base_type(src_t);
  2749. Type *dst_bt = base_type(dst_t);
  2750. if (is_type_untyped(src_t)) {
  2751. gbString expr_str = expr_to_string(o->expr);
  2752. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2753. gb_string_free(expr_str);
  2754. o->mode = Addressing_Invalid;
  2755. o->expr = node;
  2756. return false;
  2757. }
  2758. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2759. GB_ASSERT(global_error_collector.count != 0);
  2760. o->mode = Addressing_Invalid;
  2761. o->expr = node;
  2762. return false;
  2763. }
  2764. if (src_bt == nullptr || src_bt == t_invalid) {
  2765. // NOTE(bill): this should be an error
  2766. GB_ASSERT(global_error_collector.count != 0);
  2767. o->mode = Addressing_Value;
  2768. o->expr = node;
  2769. o->type = dst_t;
  2770. return true;
  2771. }
  2772. i64 srcz = type_size_of(src_t);
  2773. i64 dstz = type_size_of(dst_t);
  2774. if (srcz != dstz) {
  2775. gbString expr_str = expr_to_string(o->expr);
  2776. gbString type_str = type_to_string(dst_t);
  2777. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2778. gb_string_free(type_str);
  2779. gb_string_free(expr_str);
  2780. o->mode = Addressing_Invalid;
  2781. o->expr = node;
  2782. return false;
  2783. }
  2784. o->expr = node;
  2785. o->type = dst_t;
  2786. if (o->mode == Addressing_Constant) {
  2787. if (are_types_identical(src_bt, dst_bt)) {
  2788. return true;
  2789. }
  2790. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2791. if (types_have_same_internal_endian(src_t, dst_t)) {
  2792. ExactValue src_v = exact_value_to_integer(o->value);
  2793. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2794. BigInt v = src_v.value_integer;
  2795. BigInt smax = {};
  2796. BigInt umax = {};
  2797. big_int_from_u64(&smax, 0);
  2798. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2799. big_int_from_u64(&umax, 1);
  2800. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2801. big_int_shl_eq(&umax, &sz_in_bits);
  2802. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2803. if (big_int_cmp(&v, &smax) >= 0) {
  2804. big_int_sub_eq(&v, &umax);
  2805. }
  2806. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2807. if (big_int_is_neg(&v)) {
  2808. big_int_add_eq(&v, &umax);
  2809. }
  2810. }
  2811. o->value.kind = ExactValue_Integer;
  2812. o->value.value_integer = v;
  2813. return true;
  2814. }
  2815. }
  2816. }
  2817. o->mode = Addressing_Value;
  2818. o->value = {};
  2819. return true;
  2820. }
  2821. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2822. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2823. if (check_is_assignable_to(c, y, x->type)) {
  2824. if (check_binary_op(c, x, op)) {
  2825. return true;
  2826. }
  2827. }
  2828. }
  2829. return false;
  2830. }
  2831. gb_internal bool is_ise_expr(Ast *node) {
  2832. node = unparen_expr(node);
  2833. return node->kind == Ast_ImplicitSelectorExpr;
  2834. }
  2835. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2836. if (use_lhs_as_type_hint) { // RHS in this case
  2837. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2838. }
  2839. return false;
  2840. }
  2841. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2842. Type *xt = base_type(matrix);
  2843. if (type_hint != nullptr) {
  2844. Type *th = base_type(type_hint);
  2845. if (are_types_identical(th, xt)) {
  2846. return type_hint;
  2847. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2848. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2849. // ignore
  2850. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2851. return type_hint;
  2852. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2853. return type_hint;
  2854. }
  2855. }
  2856. }
  2857. return matrix;
  2858. }
  2859. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2860. if (!check_binary_op(c, x, op)) {
  2861. x->mode = Addressing_Invalid;
  2862. return;
  2863. }
  2864. Type *xt = base_type(x->type);
  2865. Type *yt = base_type(y->type);
  2866. if (is_type_matrix(x->type)) {
  2867. GB_ASSERT(xt->kind == Type_Matrix);
  2868. if (op.kind == Token_Mul) {
  2869. if (yt->kind == Type_Matrix) {
  2870. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2871. goto matrix_error;
  2872. }
  2873. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2874. goto matrix_error;
  2875. }
  2876. x->mode = Addressing_Value;
  2877. if (are_types_identical(xt, yt)) {
  2878. if (!is_type_named(x->type) && is_type_named(y->type)) {
  2879. // prefer the named type
  2880. x->type = y->type;
  2881. }
  2882. } else {
  2883. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2884. }
  2885. goto matrix_success;
  2886. } else if (yt->kind == Type_Array) {
  2887. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2888. goto matrix_error;
  2889. }
  2890. if (xt->Matrix.column_count != yt->Array.count) {
  2891. goto matrix_error;
  2892. }
  2893. // Treat arrays as column vectors
  2894. x->mode = Addressing_Value;
  2895. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2896. x->type = y->type;
  2897. } else {
  2898. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2899. }
  2900. goto matrix_success;
  2901. }
  2902. }
  2903. if (!are_types_identical(xt, yt)) {
  2904. goto matrix_error;
  2905. }
  2906. x->mode = Addressing_Value;
  2907. x->type = xt;
  2908. goto matrix_success;
  2909. } else {
  2910. GB_ASSERT(!is_type_matrix(xt));
  2911. GB_ASSERT(is_type_matrix(yt));
  2912. if (op.kind == Token_Mul) {
  2913. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2914. if (xt->kind == Type_Array) {
  2915. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2916. goto matrix_error;
  2917. }
  2918. if (xt->Array.count != yt->Matrix.row_count) {
  2919. goto matrix_error;
  2920. }
  2921. // Treat arrays as row vectors
  2922. x->mode = Addressing_Value;
  2923. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2924. x->type = x->type;
  2925. } else {
  2926. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2927. }
  2928. goto matrix_success;
  2929. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  2930. x->type = check_matrix_type_hint(y->type, type_hint);
  2931. return;
  2932. }
  2933. }
  2934. if (!are_types_identical(xt, yt)) {
  2935. goto matrix_error;
  2936. }
  2937. x->mode = Addressing_Value;
  2938. x->type = xt;
  2939. goto matrix_success;
  2940. }
  2941. matrix_success:
  2942. x->type = check_matrix_type_hint(x->type, type_hint);
  2943. return;
  2944. matrix_error:
  2945. gbString xts = type_to_string(x->type);
  2946. gbString yts = type_to_string(y->type);
  2947. gbString expr_str = expr_to_string(x->expr);
  2948. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2949. gb_string_free(expr_str);
  2950. gb_string_free(yts);
  2951. gb_string_free(xts);
  2952. x->type = t_invalid;
  2953. x->mode = Addressing_Invalid;
  2954. return;
  2955. }
  2956. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2957. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2958. Operand y_ = {}, *y = &y_;
  2959. ast_node(be, BinaryExpr, node);
  2960. defer({
  2961. node->viral_state_flags |= be->left->viral_state_flags;
  2962. node->viral_state_flags |= be->right->viral_state_flags;
  2963. });
  2964. Token op = be->op;
  2965. switch (op.kind) {
  2966. case Token_CmpEq:
  2967. case Token_NotEq: {
  2968. // NOTE(bill): Allow comparisons between types
  2969. if (is_ise_expr(be->left)) {
  2970. // Evalute the right before the left for an '.X' expression
  2971. check_expr_or_type(c, y, be->right, type_hint);
  2972. check_expr_or_type(c, x, be->left, y->type);
  2973. } else {
  2974. check_expr_or_type(c, x, be->left, type_hint);
  2975. check_expr_or_type(c, y, be->right, x->type);
  2976. }
  2977. bool xt = x->mode == Addressing_Type;
  2978. bool yt = y->mode == Addressing_Type;
  2979. // If only one is a type, this is an error
  2980. if (xt ^ yt) {
  2981. GB_ASSERT(xt != yt);
  2982. if (xt) {
  2983. if (!is_type_typeid(y->type)) {
  2984. error_operand_not_expression(x);
  2985. }
  2986. }
  2987. if (yt) {
  2988. if (!is_type_typeid(x->type)) {
  2989. error_operand_not_expression(y);
  2990. }
  2991. }
  2992. }
  2993. break;
  2994. }
  2995. case Token_in:
  2996. case Token_not_in:
  2997. {
  2998. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  2999. check_expr(c, y, be->right);
  3000. Type *rhs_type = type_deref(y->type);
  3001. if (is_type_bit_set(rhs_type)) {
  3002. Type *elem = base_type(rhs_type)->BitSet.elem;
  3003. check_expr_with_type_hint(c, x, be->left, elem);
  3004. } else if (is_type_map(rhs_type)) {
  3005. Type *key = base_type(rhs_type)->Map.key;
  3006. check_expr_with_type_hint(c, x, be->left, key);
  3007. } else {
  3008. check_expr(c, x, be->left);
  3009. }
  3010. if (x->mode == Addressing_Invalid) {
  3011. return;
  3012. }
  3013. if (y->mode == Addressing_Invalid) {
  3014. x->mode = Addressing_Invalid;
  3015. x->expr = y->expr;
  3016. return;
  3017. }
  3018. if (is_type_map(rhs_type)) {
  3019. Type *yt = base_type(rhs_type);
  3020. if (op.kind == Token_in) {
  3021. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3022. } else {
  3023. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3024. }
  3025. add_map_get_dependencies(c);
  3026. } else if (is_type_bit_set(rhs_type)) {
  3027. Type *yt = base_type(rhs_type);
  3028. if (op.kind == Token_in) {
  3029. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3030. } else {
  3031. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3032. }
  3033. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3034. ExactValue k = exact_value_to_integer(x->value);
  3035. ExactValue v = exact_value_to_integer(y->value);
  3036. GB_ASSERT(k.kind == ExactValue_Integer);
  3037. GB_ASSERT(v.kind == ExactValue_Integer);
  3038. i64 key = big_int_to_i64(&k.value_integer);
  3039. i64 lower = yt->BitSet.lower;
  3040. i64 upper = yt->BitSet.upper;
  3041. if (lower <= key && key <= upper) {
  3042. i64 bit = 1ll<<key;
  3043. i64 bits = big_int_to_i64(&v.value_integer);
  3044. x->mode = Addressing_Constant;
  3045. x->type = t_untyped_bool;
  3046. if (op.kind == Token_in) {
  3047. x->value = exact_value_bool((bit & bits) != 0);
  3048. } else {
  3049. x->value = exact_value_bool((bit & bits) == 0);
  3050. }
  3051. x->expr = node;
  3052. return;
  3053. } else {
  3054. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3055. x->mode = Addressing_Invalid;
  3056. }
  3057. }
  3058. } else {
  3059. gbString t = type_to_string(y->type);
  3060. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3061. gb_string_free(t);
  3062. x->expr = node;
  3063. x->mode = Addressing_Invalid;
  3064. return;
  3065. }
  3066. if (x->mode != Addressing_Invalid) {
  3067. x->mode = Addressing_Value;
  3068. x->type = t_untyped_bool;
  3069. }
  3070. x->expr = node;
  3071. return;
  3072. }
  3073. default:
  3074. if (is_ise_expr(be->left)) {
  3075. // Evalute the right before the left for an '.X' expression
  3076. check_expr_or_type(c, y, be->right, type_hint);
  3077. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3078. check_expr_or_type(c, x, be->left, y->type);
  3079. } else {
  3080. check_expr_with_type_hint(c, x, be->left, type_hint);
  3081. }
  3082. } else {
  3083. check_expr_with_type_hint(c, x, be->left, type_hint);
  3084. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3085. check_expr_with_type_hint(c, y, be->right, x->type);
  3086. } else {
  3087. check_expr_with_type_hint(c, y, be->right, type_hint);
  3088. }
  3089. }
  3090. break;
  3091. }
  3092. if (x->mode == Addressing_Invalid) {
  3093. return;
  3094. }
  3095. if (y->mode == Addressing_Invalid) {
  3096. x->mode = Addressing_Invalid;
  3097. x->expr = y->expr;
  3098. return;
  3099. }
  3100. if (x->mode == Addressing_Builtin) {
  3101. x->mode = Addressing_Invalid;
  3102. error(x->expr, "built-in expression in binary expression");
  3103. return;
  3104. }
  3105. if (y->mode == Addressing_Builtin) {
  3106. x->mode = Addressing_Invalid;
  3107. error(y->expr, "built-in expression in binary expression");
  3108. return;
  3109. }
  3110. if (x->mode == Addressing_ProcGroup) {
  3111. x->mode = Addressing_Invalid;
  3112. if (x->proc_group != nullptr) {
  3113. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3114. } else {
  3115. error(x->expr, "procedure group used in binary expression");
  3116. }
  3117. return;
  3118. }
  3119. if (y->mode == Addressing_ProcGroup) {
  3120. x->mode = Addressing_Invalid;
  3121. if (x->proc_group != nullptr) {
  3122. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3123. } else {
  3124. error(y->expr, "procedure group used in binary expression");
  3125. }
  3126. return;
  3127. }
  3128. if (token_is_shift(op.kind)) {
  3129. check_shift(c, x, y, node, type_hint);
  3130. return;
  3131. }
  3132. switch (op.kind) {
  3133. case Token_Quo:
  3134. case Token_Mod:
  3135. case Token_ModMod:
  3136. case Token_QuoEq:
  3137. case Token_ModEq:
  3138. case Token_ModModEq:
  3139. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3140. is_type_float(x->type) && is_type_untyped(x->type)) {
  3141. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3142. gbString t = type_to_string(y->type);
  3143. if (x->value.kind != ExactValue_Invalid) {
  3144. gbString s = exact_value_to_string(x->value);
  3145. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3146. gb_string_free(s);
  3147. } else {
  3148. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3149. }
  3150. gb_string_free(t);
  3151. }
  3152. break;
  3153. }
  3154. convert_to_typed(c, x, y->type);
  3155. if (x->mode == Addressing_Invalid) {
  3156. return;
  3157. }
  3158. convert_to_typed(c, y, x->type);
  3159. if (y->mode == Addressing_Invalid) {
  3160. x->mode = Addressing_Invalid;
  3161. return;
  3162. }
  3163. if (token_is_comparison(op.kind)) {
  3164. check_comparison(c, node, x, y, op.kind);
  3165. return;
  3166. }
  3167. if (check_binary_array_expr(c, op, x, y)) {
  3168. x->mode = Addressing_Value;
  3169. x->type = x->type;
  3170. return;
  3171. }
  3172. if (check_binary_array_expr(c, op, y, x)) {
  3173. x->mode = Addressing_Value;
  3174. x->type = y->type;
  3175. return;
  3176. }
  3177. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3178. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3179. x->expr = node;
  3180. return;
  3181. }
  3182. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3183. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3184. // NOTE(bill, 2022-06-26)
  3185. // Allow any boolean types within `&&` and `||`
  3186. // This is an exception to all other binary expressions since the result
  3187. // of a comparison will always be an untyped boolean, and allowing
  3188. // any boolean between these two simplifies a lot of expressions
  3189. } else if (!are_types_identical(x->type, y->type)) {
  3190. if (x->type != t_invalid &&
  3191. y->type != t_invalid) {
  3192. gbString xt = type_to_string(x->type);
  3193. gbString yt = type_to_string(y->type);
  3194. gbString expr_str = expr_to_string(node);
  3195. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3196. gb_string_free(expr_str);
  3197. gb_string_free(yt);
  3198. gb_string_free(xt);
  3199. }
  3200. x->mode = Addressing_Invalid;
  3201. return;
  3202. }
  3203. if (!check_binary_op(c, x, op)) {
  3204. x->mode = Addressing_Invalid;
  3205. return;
  3206. }
  3207. switch (op.kind) {
  3208. case Token_Quo:
  3209. case Token_Mod:
  3210. case Token_ModMod:
  3211. case Token_QuoEq:
  3212. case Token_ModEq:
  3213. case Token_ModModEq:
  3214. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3215. y->mode == Addressing_Constant) {
  3216. bool fail = false;
  3217. switch (y->value.kind) {
  3218. case ExactValue_Integer:
  3219. if (big_int_is_zero(&y->value.value_integer)) {
  3220. fail = true;
  3221. }
  3222. break;
  3223. case ExactValue_Float:
  3224. if (y->value.value_float == 0.0) {
  3225. fail = true;
  3226. }
  3227. break;
  3228. }
  3229. if (fail) {
  3230. error(y->expr, "Division by zero not allowed");
  3231. x->mode = Addressing_Invalid;
  3232. return;
  3233. }
  3234. }
  3235. break;
  3236. case Token_CmpAnd:
  3237. case Token_CmpOr:
  3238. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3239. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3240. }
  3241. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3242. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3243. }
  3244. break;
  3245. }
  3246. if (x->mode == Addressing_Constant &&
  3247. y->mode == Addressing_Constant) {
  3248. ExactValue a = x->value;
  3249. ExactValue b = y->value;
  3250. if (!is_type_constant_type(x->type)) {
  3251. x->mode = Addressing_Value;
  3252. return;
  3253. }
  3254. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3255. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3256. }
  3257. if (is_type_bit_set(x->type)) {
  3258. switch (op.kind) {
  3259. case Token_Add: op.kind = Token_Or; break;
  3260. case Token_Sub: op.kind = Token_AndNot; break;
  3261. }
  3262. }
  3263. x->value = exact_binary_operator_value(op.kind, a, b);
  3264. if (is_type_typed(x->type)) {
  3265. if (node != nullptr) {
  3266. x->expr = node;
  3267. }
  3268. check_is_expressible(c, x, x->type);
  3269. }
  3270. return;
  3271. } else if (is_type_string(x->type)) {
  3272. error(node, "String concatenation is only allowed with constant strings");
  3273. x->mode = Addressing_Invalid;
  3274. return;
  3275. }
  3276. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3277. Type *bt = base_type(x->type);
  3278. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3279. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3280. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3281. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3282. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3283. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3284. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3285. }
  3286. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3287. Type *bt = base_type(x->type);
  3288. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3289. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3290. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3291. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3292. }
  3293. }
  3294. x->mode = Addressing_Value;
  3295. }
  3296. gb_internal Operand make_operand_from_node(Ast *node) {
  3297. GB_ASSERT(node != nullptr);
  3298. Operand x = {};
  3299. x.expr = node;
  3300. x.mode = node->tav.mode;
  3301. x.type = node->tav.type;
  3302. x.value = node->tav.value;
  3303. return x;
  3304. }
  3305. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3306. GB_ASSERT(e != nullptr);
  3307. ExprInfo *old = check_get_expr_info(c, e);
  3308. if (old == nullptr) {
  3309. if (type != nullptr && type != t_invalid) {
  3310. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3311. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3312. if (e->kind == Ast_TernaryIfExpr) {
  3313. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3314. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3315. }
  3316. }
  3317. }
  3318. return;
  3319. }
  3320. switch (e->kind) {
  3321. case_ast_node(ue, UnaryExpr, e);
  3322. if (old->value.kind != ExactValue_Invalid) {
  3323. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3324. // They don't need to be updated as they will be updated later and
  3325. // checked at the end of general checking stage.
  3326. break;
  3327. }
  3328. update_untyped_expr_type(c, ue->expr, type, final);
  3329. case_end;
  3330. case_ast_node(be, BinaryExpr, e);
  3331. if (old->value.kind != ExactValue_Invalid) {
  3332. // See above note in UnaryExpr case
  3333. break;
  3334. }
  3335. if (token_is_comparison(be->op.kind)) {
  3336. // NOTE(bill): Do nothing as the types are fine
  3337. } else if (token_is_shift(be->op.kind)) {
  3338. update_untyped_expr_type(c, be->left, type, final);
  3339. } else {
  3340. update_untyped_expr_type(c, be->left, type, final);
  3341. update_untyped_expr_type(c, be->right, type, final);
  3342. }
  3343. case_end;
  3344. case_ast_node(te, TernaryIfExpr, e);
  3345. if (old->value.kind != ExactValue_Invalid) {
  3346. // See above note in UnaryExpr case
  3347. break;
  3348. }
  3349. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3350. // having an untyped value
  3351. Operand x = make_operand_from_node(te->x);
  3352. Operand y = make_operand_from_node(te->y);
  3353. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3354. update_untyped_expr_type(c, te->x, type, final);
  3355. }
  3356. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3357. update_untyped_expr_type(c, te->y, type, final);
  3358. }
  3359. case_end;
  3360. case_ast_node(te, TernaryWhenExpr, e);
  3361. if (old->value.kind != ExactValue_Invalid) {
  3362. // See above note in UnaryExpr case
  3363. break;
  3364. }
  3365. update_untyped_expr_type(c, te->x, type, final);
  3366. update_untyped_expr_type(c, te->y, type, final);
  3367. case_end;
  3368. case_ast_node(ore, OrReturnExpr, e);
  3369. if (old->value.kind != ExactValue_Invalid) {
  3370. // See above note in UnaryExpr case
  3371. break;
  3372. }
  3373. update_untyped_expr_type(c, ore->expr, type, final);
  3374. case_end;
  3375. case_ast_node(obe, OrBranchExpr, e);
  3376. if (old->value.kind != ExactValue_Invalid) {
  3377. // See above note in UnaryExpr case
  3378. break;
  3379. }
  3380. update_untyped_expr_type(c, obe->expr, type, final);
  3381. case_end;
  3382. case_ast_node(oee, OrElseExpr, e);
  3383. if (old->value.kind != ExactValue_Invalid) {
  3384. // See above note in UnaryExpr case
  3385. break;
  3386. }
  3387. update_untyped_expr_type(c, oee->x, type, final);
  3388. update_untyped_expr_type(c, oee->y, type, final);
  3389. case_end;
  3390. case_ast_node(pe, ParenExpr, e);
  3391. update_untyped_expr_type(c, pe->expr, type, final);
  3392. case_end;
  3393. }
  3394. if (!final && is_type_untyped(type)) {
  3395. old->type = base_type(type);
  3396. return;
  3397. }
  3398. // We need to remove it and then give it a new one
  3399. check_remove_expr_info(c, e);
  3400. if (old->is_lhs && !is_type_integer(type)) {
  3401. gbString expr_str = expr_to_string(e);
  3402. gbString type_str = type_to_string(type);
  3403. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3404. gb_string_free(type_str);
  3405. gb_string_free(expr_str);
  3406. return;
  3407. }
  3408. add_type_and_value(c, e, old->mode, type, old->value);
  3409. }
  3410. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3411. GB_ASSERT(e != nullptr);
  3412. ExprInfo *found = check_get_expr_info(c, e);
  3413. if (found) {
  3414. found->value = value;
  3415. }
  3416. }
  3417. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3418. gbString expr_str = expr_to_string(operand->expr);
  3419. gbString type_str = type_to_string(target_type);
  3420. gbString from_type_str = type_to_string(operand->type);
  3421. char const *extra_text = "";
  3422. if (operand->mode == Addressing_Constant) {
  3423. if (big_int_is_zero(&operand->value.value_integer)) {
  3424. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3425. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3426. extra_text = " - Did you want 'nil'?";
  3427. }
  3428. }
  3429. }
  3430. ERROR_BLOCK();
  3431. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3432. if (operand->value.kind == ExactValue_String) {
  3433. String key = operand->value.value_string;
  3434. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3435. Type *et = base_type(target_type);
  3436. check_did_you_mean_type(key, et->Enum.fields, ".");
  3437. }
  3438. }
  3439. gb_string_free(from_type_str);
  3440. gb_string_free(type_str);
  3441. gb_string_free(expr_str);
  3442. operand->mode = Addressing_Invalid;
  3443. }
  3444. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3445. Type *t = core_type(type);
  3446. if (is_type_boolean(t)) {
  3447. // v = exact_value_to_boolean(v);
  3448. } else if (is_type_float(t)) {
  3449. v = exact_value_to_float(v);
  3450. } else if (is_type_integer(t)) {
  3451. v = exact_value_to_integer(v);
  3452. } else if (is_type_pointer(t)) {
  3453. v = exact_value_to_integer(v);
  3454. } else if (is_type_complex(t)) {
  3455. v = exact_value_to_complex(v);
  3456. } else if (is_type_quaternion(t)) {
  3457. v = exact_value_to_quaternion(v);
  3458. }
  3459. return v;
  3460. }
  3461. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3462. GB_ASSERT_NOT_NULL(target_type);
  3463. if (operand->mode == Addressing_Invalid ||
  3464. operand->mode == Addressing_Type ||
  3465. is_type_typed(operand->type) ||
  3466. target_type == t_invalid) {
  3467. return;
  3468. }
  3469. if (is_type_untyped(target_type)) {
  3470. GB_ASSERT(operand->type->kind == Type_Basic);
  3471. GB_ASSERT(target_type->kind == Type_Basic);
  3472. BasicKind x_kind = operand->type->Basic.kind;
  3473. BasicKind y_kind = target_type->Basic.kind;
  3474. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3475. if (x_kind < y_kind) {
  3476. operand->type = target_type;
  3477. update_untyped_expr_type(c, operand->expr, target_type, false);
  3478. }
  3479. } else if (x_kind != y_kind) {
  3480. operand->mode = Addressing_Invalid;
  3481. convert_untyped_error(c, operand, target_type);
  3482. return;
  3483. }
  3484. return;
  3485. }
  3486. Type *t = base_type(target_type);
  3487. if (c->in_enum_type) {
  3488. t = core_type(target_type);
  3489. }
  3490. switch (t->kind) {
  3491. case Type_Basic:
  3492. if (operand->mode == Addressing_Constant) {
  3493. check_is_expressible(c, operand, t);
  3494. if (operand->mode == Addressing_Invalid) {
  3495. return;
  3496. }
  3497. update_untyped_expr_value(c, operand->expr, operand->value);
  3498. } else {
  3499. switch (operand->type->Basic.kind) {
  3500. case Basic_UntypedBool:
  3501. if (!is_type_boolean(target_type)) {
  3502. operand->mode = Addressing_Invalid;
  3503. convert_untyped_error(c, operand, target_type);
  3504. return;
  3505. }
  3506. break;
  3507. case Basic_UntypedInteger:
  3508. case Basic_UntypedFloat:
  3509. case Basic_UntypedComplex:
  3510. case Basic_UntypedQuaternion:
  3511. case Basic_UntypedRune:
  3512. if (!is_type_numeric(target_type)) {
  3513. operand->mode = Addressing_Invalid;
  3514. convert_untyped_error(c, operand, target_type);
  3515. return;
  3516. }
  3517. break;
  3518. case Basic_UntypedNil:
  3519. if (is_type_any(target_type)) {
  3520. // target_type = t_untyped_nil;
  3521. } else if (is_type_cstring(target_type)) {
  3522. // target_type = t_untyped_nil;
  3523. } else if (!type_has_nil(target_type)) {
  3524. operand->mode = Addressing_Invalid;
  3525. convert_untyped_error(c, operand, target_type);
  3526. return;
  3527. }
  3528. break;
  3529. }
  3530. }
  3531. break;
  3532. case Type_Array: {
  3533. Type *elem = base_array_type(t);
  3534. if (check_is_assignable_to(c, operand, elem)) {
  3535. operand->mode = Addressing_Value;
  3536. } else {
  3537. if (operand->value.kind == ExactValue_String) {
  3538. String s = operand->value.value_string;
  3539. if (is_type_u8_array(t)) {
  3540. if (s.len == t->Array.count) {
  3541. break;
  3542. }
  3543. } else if (is_type_rune_array(t)) {
  3544. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3545. if (rune_count == t->Array.count) {
  3546. break;
  3547. }
  3548. }
  3549. }
  3550. operand->mode = Addressing_Invalid;
  3551. convert_untyped_error(c, operand, target_type);
  3552. return;
  3553. }
  3554. break;
  3555. }
  3556. case Type_Matrix: {
  3557. Type *elem = base_array_type(t);
  3558. if (check_is_assignable_to(c, operand, elem)) {
  3559. if (t->Matrix.row_count != t->Matrix.column_count) {
  3560. operand->mode = Addressing_Invalid;
  3561. begin_error_block();
  3562. defer (end_error_block());
  3563. convert_untyped_error(c, operand, target_type);
  3564. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3565. return;
  3566. } else {
  3567. operand->mode = Addressing_Value;
  3568. }
  3569. } else {
  3570. operand->mode = Addressing_Invalid;
  3571. convert_untyped_error(c, operand, target_type);
  3572. return;
  3573. }
  3574. break;
  3575. }
  3576. case Type_Union:
  3577. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3578. TEMPORARY_ALLOCATOR_GUARD();
  3579. isize count = t->Union.variants.count;
  3580. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3581. isize valid_count = 0;
  3582. isize first_success_index = -1;
  3583. for_array(i, t->Union.variants) {
  3584. Type *vt = t->Union.variants[i];
  3585. i64 score = 0;
  3586. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3587. valids[valid_count].index = i;
  3588. valids[valid_count].score = score;
  3589. valid_count += 1;
  3590. if (first_success_index < 0) {
  3591. first_success_index = i;
  3592. }
  3593. }
  3594. }
  3595. if (valid_count > 1) {
  3596. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3597. i64 best_score = valids[0].score;
  3598. for (isize i = 1; i < valid_count; i++) {
  3599. auto v = valids[i];
  3600. if (best_score > v.score) {
  3601. valid_count = i;
  3602. break;
  3603. }
  3604. best_score = v.score;
  3605. }
  3606. first_success_index = valids[0].index;
  3607. }
  3608. gbString type_str = type_to_string(target_type);
  3609. defer (gb_string_free(type_str));
  3610. if (valid_count == 1) {
  3611. operand->mode = Addressing_Value;
  3612. operand->type = t->Union.variants[first_success_index];
  3613. target_type = t->Union.variants[first_success_index];
  3614. break;
  3615. } else if (valid_count > 1) {
  3616. begin_error_block();
  3617. defer (end_error_block());
  3618. GB_ASSERT(first_success_index >= 0);
  3619. operand->mode = Addressing_Invalid;
  3620. convert_untyped_error(c, operand, target_type);
  3621. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3622. i32 j = 0;
  3623. for (i32 i = 0; i < valid_count; i++) {
  3624. ValidIndexAndScore valid = valids[i];
  3625. if (j > 0 && valid_count > 2) error_line(", ");
  3626. if (j == valid_count-1) {
  3627. if (valid_count == 2) error_line(" ");
  3628. error_line("or ");
  3629. }
  3630. gbString str = type_to_string(t->Union.variants[valid.index]);
  3631. error_line("'%s'", str);
  3632. gb_string_free(str);
  3633. j++;
  3634. }
  3635. error_line("\n\n");
  3636. return;
  3637. } else if (is_type_untyped_uninit(operand->type)) {
  3638. target_type = t_untyped_uninit;
  3639. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3640. begin_error_block();
  3641. defer (end_error_block());
  3642. operand->mode = Addressing_Invalid;
  3643. convert_untyped_error(c, operand, target_type);
  3644. if (count > 0) {
  3645. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3646. error_line("\t");
  3647. for (i32 i = 0; i < count; i++) {
  3648. Type *v = t->Union.variants[i];
  3649. if (i > 0 && count > 2) error_line(", ");
  3650. if (i == count-1) {
  3651. if (count == 2) error_line(" ");
  3652. if (count > 1) {
  3653. error_line("or ");
  3654. }
  3655. }
  3656. gbString str = type_to_string(v);
  3657. error_line("'%s'", str);
  3658. gb_string_free(str);
  3659. }
  3660. error_line("\n\n");
  3661. }
  3662. return;
  3663. }
  3664. }
  3665. /* fallthrough */
  3666. default:
  3667. if (is_type_untyped_uninit(operand->type)) {
  3668. target_type = t_untyped_uninit;
  3669. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3670. target_type = t_untyped_nil;
  3671. } else {
  3672. operand->mode = Addressing_Invalid;
  3673. convert_untyped_error(c, operand, target_type);
  3674. return;
  3675. }
  3676. break;
  3677. }
  3678. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3679. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3680. } else {
  3681. target_type = default_type(operand->type);
  3682. }
  3683. }
  3684. update_untyped_expr_type(c, operand->expr, target_type, true);
  3685. operand->type = target_type;
  3686. }
  3687. 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) {
  3688. Operand operand = {Addressing_Invalid};
  3689. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3690. if (operand.mode == Addressing_Invalid) {
  3691. if (value) *value = 0;
  3692. return false;
  3693. }
  3694. Type *index_type = t_int;
  3695. if (type_hint != nullptr) {
  3696. index_type = type_hint;
  3697. }
  3698. convert_to_typed(c, &operand, index_type);
  3699. if (operand.mode == Addressing_Invalid) {
  3700. if (value) *value = 0;
  3701. return false;
  3702. }
  3703. if (type_hint != nullptr) {
  3704. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3705. gbString expr_str = expr_to_string(operand.expr);
  3706. gbString index_type_str = type_to_string(type_hint);
  3707. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3708. gb_string_free(index_type_str);
  3709. gb_string_free(expr_str);
  3710. if (value) *value = 0;
  3711. return false;
  3712. }
  3713. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3714. gbString expr_str = expr_to_string(operand.expr);
  3715. gbString type_str = type_to_string(operand.type);
  3716. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3717. gb_string_free(type_str);
  3718. gb_string_free(expr_str);
  3719. if (value) *value = 0;
  3720. return false;
  3721. }
  3722. if (operand.mode == Addressing_Constant &&
  3723. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3724. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3725. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3726. TEMPORARY_ALLOCATOR_GUARD();
  3727. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3728. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3729. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3730. if (value) *value = 0;
  3731. return false;
  3732. }
  3733. if (max_count >= 0) {
  3734. if (is_type_enum(index_type)) {
  3735. Type *bt = base_type(index_type);
  3736. GB_ASSERT(bt->kind == Type_Enum);
  3737. ExactValue const &lo = *bt->Enum.min_value;
  3738. ExactValue const &hi = *bt->Enum.max_value;
  3739. String lo_str = {};
  3740. String hi_str = {};
  3741. if (bt->Enum.fields.count > 0) {
  3742. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3743. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3744. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3745. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3746. }
  3747. bool out_of_bounds = false;
  3748. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3749. out_of_bounds = true;
  3750. }
  3751. if (out_of_bounds) {
  3752. gbString expr_str = expr_to_string(operand.expr);
  3753. if (lo_str.len > 0) {
  3754. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3755. } else {
  3756. gbString index_type_str = type_to_string(index_type);
  3757. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3758. gb_string_free(index_type_str);
  3759. }
  3760. gb_string_free(expr_str);
  3761. return false;
  3762. }
  3763. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3764. return true;
  3765. } else { // NOTE(bill): Do array bound checking
  3766. i64 v = -1;
  3767. if (i.used <= 1) {
  3768. v = big_int_to_i64(&i);
  3769. }
  3770. if (value) *value = v;
  3771. bool out_of_bounds = false;
  3772. if (v < 0) {
  3773. out_of_bounds = true;
  3774. } else if (open_range) {
  3775. out_of_bounds = v > max_count;
  3776. } else {
  3777. out_of_bounds = v >= max_count;
  3778. }
  3779. if (out_of_bounds) {
  3780. TEMPORARY_ALLOCATOR_GUARD();
  3781. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3782. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3783. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3784. return false;
  3785. }
  3786. return true;
  3787. }
  3788. } else {
  3789. if (value) *value = exact_value_to_i64(operand.value);
  3790. return true;
  3791. }
  3792. }
  3793. // NOTE(bill): It's alright :D
  3794. if (value) *value = -1;
  3795. return true;
  3796. }
  3797. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3798. if (value.kind == ExactValue_String) {
  3799. GB_ASSERT(0 <= index && index < value.value_string.len);
  3800. u8 val = value.value_string[index];
  3801. if (success_) *success_ = true;
  3802. if (finish_) *finish_ = true;
  3803. return exact_value_u64(val);
  3804. }
  3805. if (value.kind != ExactValue_Compound) {
  3806. if (success_) *success_ = true;
  3807. if (finish_) *finish_ = true;
  3808. return value;
  3809. }
  3810. Ast *node = value.value_compound;
  3811. switch (node->kind) {
  3812. case_ast_node(cl, CompoundLit, node);
  3813. if (cl->elems.count == 0) {
  3814. if (success_) *success_ = true;
  3815. if (finish_) *finish_ = true;
  3816. return empty_exact_value;
  3817. }
  3818. if (cl->elems[0]->kind == Ast_FieldValue) {
  3819. if (is_type_struct(node->tav.type)) {
  3820. bool found = false;
  3821. for (Ast *elem : cl->elems) {
  3822. if (elem->kind != Ast_FieldValue) {
  3823. continue;
  3824. }
  3825. ast_node(fv, FieldValue, elem);
  3826. String name = fv->field->Ident.token.string;
  3827. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3828. defer (array_free(&sub_sel.index));
  3829. if (sub_sel.index[0] == index) {
  3830. value = fv->value->tav.value;
  3831. found = true;
  3832. break;
  3833. }
  3834. }
  3835. if (!found) {
  3836. // Use the zero value if it is not found
  3837. value = {};
  3838. }
  3839. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3840. for (Ast *elem : cl->elems) {
  3841. if (elem->kind != Ast_FieldValue) {
  3842. continue;
  3843. }
  3844. ast_node(fv, FieldValue, elem);
  3845. if (is_ast_range(fv->field)) {
  3846. ast_node(ie, BinaryExpr, fv->field);
  3847. TypeAndValue lo_tav = ie->left->tav;
  3848. TypeAndValue hi_tav = ie->right->tav;
  3849. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3850. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3851. TokenKind op = ie->op.kind;
  3852. i64 lo = exact_value_to_i64(lo_tav.value);
  3853. i64 hi = exact_value_to_i64(hi_tav.value);
  3854. i64 corrected_index = index;
  3855. if (is_type_enumerated_array(node->tav.type)) {
  3856. Type *bt = base_type(node->tav.type);
  3857. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3858. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3859. }
  3860. if (op != Token_RangeHalf) {
  3861. if (lo <= corrected_index && corrected_index <= hi) {
  3862. TypeAndValue tav = fv->value->tav;
  3863. if (success_) *success_ = true;
  3864. if (finish_) *finish_ = false;
  3865. return tav.value;
  3866. }
  3867. } else {
  3868. if (lo <= corrected_index && corrected_index < hi) {
  3869. TypeAndValue tav = fv->value->tav;
  3870. if (success_) *success_ = true;
  3871. if (finish_) *finish_ = false;
  3872. return tav.value;
  3873. }
  3874. }
  3875. } else {
  3876. TypeAndValue index_tav = fv->field->tav;
  3877. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3878. ExactValue index_value = index_tav.value;
  3879. if (is_type_enumerated_array(node->tav.type)) {
  3880. Type *bt = base_type(node->tav.type);
  3881. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3882. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3883. }
  3884. i64 field_index = exact_value_to_i64(index_value);
  3885. if (index == field_index) {
  3886. TypeAndValue tav = fv->value->tav;
  3887. if (success_) *success_ = true;
  3888. if (finish_) *finish_ = false;
  3889. return tav.value;;
  3890. }
  3891. }
  3892. }
  3893. }
  3894. } else {
  3895. i32 count = (i32)cl->elems.count;
  3896. if (count < index) {
  3897. if (success_) *success_ = false;
  3898. if (finish_) *finish_ = true;
  3899. return empty_exact_value;
  3900. }
  3901. if (cl->elems.count <= index) {
  3902. if (success_) *success_ = false;
  3903. if (finish_) *finish_ = false;
  3904. return value;
  3905. }
  3906. TypeAndValue tav = cl->elems[index]->tav;
  3907. if (tav.mode == Addressing_Constant) {
  3908. if (success_) *success_ = true;
  3909. if (finish_) *finish_ = false;
  3910. return tav.value;
  3911. } else {
  3912. GB_ASSERT(is_type_untyped_nil(tav.type));
  3913. if (success_) *success_ = true;
  3914. if (finish_) *finish_ = false;
  3915. return tav.value;
  3916. }
  3917. }
  3918. case_end;
  3919. default:
  3920. if (success_) *success_ = true;
  3921. if (finish_) *finish_ = true;
  3922. return empty_exact_value;
  3923. }
  3924. if (finish_) *finish_ = false;
  3925. return value;
  3926. }
  3927. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3928. if (operand->mode != Addressing_Constant) {
  3929. if (success_) *success_ = false;
  3930. return empty_exact_value;
  3931. }
  3932. if (sel.indirect) {
  3933. if (success_) *success_ = false;
  3934. return empty_exact_value;
  3935. }
  3936. if (sel.index.count == 0) {
  3937. if (success_) *success_ = false;
  3938. return empty_exact_value;
  3939. }
  3940. ExactValue value = operand->value;
  3941. if (value.kind == ExactValue_Compound) {
  3942. while (sel.index.count > 0) {
  3943. i32 index = sel.index[0];
  3944. sel = sub_selection(sel, 1);
  3945. bool finish = false;
  3946. value = get_constant_field_single(c, value, index, success_, &finish);
  3947. if (finish) {
  3948. return value;
  3949. }
  3950. }
  3951. if (success_) *success_ = true;
  3952. return value;
  3953. } else if (value.kind == ExactValue_Quaternion) {
  3954. // @QuaternionLayout
  3955. Quaternion256 q = *value.value_quaternion;
  3956. GB_ASSERT(sel.index.count == 1);
  3957. switch (sel.index[0]) {
  3958. case 3: // w
  3959. if (success_) *success_ = true;
  3960. return exact_value_float(q.real);
  3961. case 0: // x
  3962. if (success_) *success_ = true;
  3963. return exact_value_float(q.imag);
  3964. case 1: // y
  3965. if (success_) *success_ = true;
  3966. return exact_value_float(q.jmag);
  3967. case 2: // z
  3968. if (success_) *success_ = true;
  3969. return exact_value_float(q.kmag);
  3970. }
  3971. if (success_) *success_ = false;
  3972. return empty_exact_value;
  3973. } else if (value.kind == ExactValue_Complex) {
  3974. // @QuaternionLayout
  3975. Complex128 c = *value.value_complex;
  3976. GB_ASSERT(sel.index.count == 1);
  3977. switch (sel.index[0]) {
  3978. case 0: // real
  3979. if (success_) *success_ = true;
  3980. return exact_value_float(c.real);
  3981. case 1: // imag
  3982. if (success_) *success_ = true;
  3983. return exact_value_float(c.imag);
  3984. }
  3985. if (success_) *success_ = false;
  3986. return empty_exact_value;
  3987. }
  3988. if (success_) *success_ = true;
  3989. return empty_exact_value;
  3990. }
  3991. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  3992. Type *array_type = base_type(type_deref(original_type));
  3993. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  3994. if (array_type->kind == Type_SimdVector) {
  3995. Type *elem_type = array_type->SimdVector.elem;
  3996. return alloc_type_simd_vector(new_count, elem_type);
  3997. }
  3998. Type *elem_type = array_type->Array.elem;
  3999. Type *swizzle_array_type = nullptr;
  4000. Type *bth = base_type(type_deref(type_hint));
  4001. if (bth != nullptr && bth->kind == Type_Array &&
  4002. bth->Array.count == new_count &&
  4003. are_types_identical(bth->Array.elem, elem_type)) {
  4004. swizzle_array_type = type_hint;
  4005. } else {
  4006. i64 max_count = array_type->Array.count;
  4007. if (new_count == max_count) {
  4008. swizzle_array_type = original_type;
  4009. } else {
  4010. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4011. }
  4012. }
  4013. return swizzle_array_type;
  4014. }
  4015. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4016. bool is_declared = entity != nullptr;
  4017. if (is_declared) {
  4018. if (entity->kind == Entity_Builtin) {
  4019. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4020. // This means that we should just ignore the found result through it
  4021. *allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  4022. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4023. is_declared = false;
  4024. }
  4025. }
  4026. return is_declared;
  4027. }
  4028. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4029. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4030. if (node->kind == Ast_Ident) {
  4031. String name = node->Ident.token.string;
  4032. return scope_lookup(c->scope, name);
  4033. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4034. ast_node(se, SelectorExpr, node);
  4035. if (se->token.kind == Token_ArrowRight) {
  4036. return nullptr;
  4037. }
  4038. Ast *op_expr = se->expr;
  4039. Ast *selector = unparen_expr(se->selector);
  4040. if (selector == nullptr) {
  4041. return nullptr;
  4042. }
  4043. if (selector->kind != Ast_Ident) {
  4044. return nullptr;
  4045. }
  4046. Entity *entity = nullptr;
  4047. Entity *expr_entity = nullptr;
  4048. bool check_op_expr = true;
  4049. if (op_expr->kind == Ast_Ident) {
  4050. String op_name = op_expr->Ident.token.string;
  4051. Entity *e = scope_lookup(c->scope, op_name);
  4052. if (e == nullptr) {
  4053. return nullptr;
  4054. }
  4055. add_entity_use(c, op_expr, e);
  4056. expr_entity = e;
  4057. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4058. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4059. // It pretty much needs to be in this order and this way
  4060. // If you can clean this up, please do but be really careful
  4061. String import_name = op_name;
  4062. Scope *import_scope = e->ImportName.scope;
  4063. String entity_name = selector->Ident.token.string;
  4064. check_op_expr = false;
  4065. entity = scope_lookup_current(import_scope, entity_name);
  4066. bool allow_builtin = false;
  4067. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4068. return nullptr;
  4069. }
  4070. check_entity_decl(c, entity, nullptr, nullptr);
  4071. if (entity->kind == Entity_ProcGroup) {
  4072. return entity;
  4073. }
  4074. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4075. }
  4076. }
  4077. Operand operand = {};
  4078. if (check_op_expr) {
  4079. check_expr_base(c, &operand, op_expr, nullptr);
  4080. if (operand.mode == Addressing_Invalid) {
  4081. return nullptr;
  4082. }
  4083. }
  4084. if (entity == nullptr && selector->kind == Ast_Ident) {
  4085. String field_name = selector->Ident.token.string;
  4086. if (is_type_dynamic_array(type_deref(operand.type))) {
  4087. init_mem_allocator(c->checker);
  4088. }
  4089. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4090. entity = sel.entity;
  4091. }
  4092. if (entity != nullptr) {
  4093. return entity;
  4094. }
  4095. }
  4096. return nullptr;
  4097. }
  4098. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4099. ast_node(se, SelectorExpr, node);
  4100. bool check_op_expr = true;
  4101. Entity *expr_entity = nullptr;
  4102. Entity *entity = nullptr;
  4103. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4104. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4105. error(node, "Illegal use of -> selector shorthand outside of a call");
  4106. operand->mode = Addressing_Invalid;
  4107. operand->expr = node;
  4108. return nullptr;
  4109. }
  4110. operand->expr = node;
  4111. Ast *op_expr = se->expr;
  4112. Ast *selector = unparen_expr(se->selector);
  4113. if (selector == nullptr) {
  4114. operand->mode = Addressing_Invalid;
  4115. operand->expr = node;
  4116. return nullptr;
  4117. }
  4118. if (selector->kind != Ast_Ident) {
  4119. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4120. operand->mode = Addressing_Invalid;
  4121. operand->expr = node;
  4122. return nullptr;
  4123. }
  4124. if (op_expr->kind == Ast_Ident) {
  4125. String op_name = op_expr->Ident.token.string;
  4126. Entity *e = scope_lookup(c->scope, op_name);
  4127. add_entity_use(c, op_expr, e);
  4128. expr_entity = e;
  4129. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4130. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4131. // It pretty much needs to be in this order and this way
  4132. // If you can clean this up, please do but be really careful
  4133. String import_name = op_name;
  4134. Scope *import_scope = e->ImportName.scope;
  4135. String entity_name = selector->Ident.token.string;
  4136. check_op_expr = false;
  4137. entity = scope_lookup_current(import_scope, entity_name);
  4138. bool allow_builtin = false;
  4139. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4140. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4141. operand->mode = Addressing_Invalid;
  4142. operand->expr = node;
  4143. check_did_you_mean_scope(entity_name, import_scope);
  4144. return nullptr;
  4145. }
  4146. check_entity_decl(c, entity, nullptr, nullptr);
  4147. if (entity->kind == Entity_ProcGroup) {
  4148. operand->mode = Addressing_ProcGroup;
  4149. operand->proc_group = entity;
  4150. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4151. return entity;
  4152. }
  4153. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4154. if (!is_entity_exported(entity, allow_builtin)) {
  4155. gbString sel_str = expr_to_string(selector);
  4156. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4157. gb_string_free(sel_str);
  4158. // NOTE(bill): make the state valid still, even if it's "invalid"
  4159. // operand->mode = Addressing_Invalid;
  4160. // operand->expr = node;
  4161. // return nullptr;
  4162. }
  4163. if (entity->kind == Entity_ProcGroup) {
  4164. Array<Entity *> procs = entity->ProcGroup.entities;
  4165. bool skip = false;
  4166. for (Entity *p : procs) {
  4167. Type *t = base_type(p->type);
  4168. if (t == t_invalid) {
  4169. continue;
  4170. }
  4171. Operand x = {};
  4172. x.mode = Addressing_Value;
  4173. x.type = t;
  4174. if (type_hint != nullptr) {
  4175. if (check_is_assignable_to(c, &x, type_hint)) {
  4176. entity = p;
  4177. skip = true;
  4178. break;
  4179. }
  4180. }
  4181. }
  4182. if (!skip) {
  4183. GB_ASSERT(entity != nullptr);
  4184. operand->mode = Addressing_ProcGroup;
  4185. operand->type = t_invalid;
  4186. operand->expr = node;
  4187. operand->proc_group = entity;
  4188. return entity;
  4189. }
  4190. }
  4191. }
  4192. }
  4193. if (check_op_expr) {
  4194. check_expr_base(c, operand, op_expr, nullptr);
  4195. if (operand->mode == Addressing_Invalid) {
  4196. operand->mode = Addressing_Invalid;
  4197. operand->expr = node;
  4198. return nullptr;
  4199. }
  4200. }
  4201. if (entity == nullptr && selector->kind == Ast_Ident) {
  4202. String field_name = selector->Ident.token.string;
  4203. Type *t = type_deref(operand->type);
  4204. if (t == nullptr) {
  4205. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4206. } else if (is_type_dynamic_array(t)) {
  4207. init_mem_allocator(c->checker);
  4208. }
  4209. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4210. entity = sel.entity;
  4211. // NOTE(bill): Add type info needed for fields like 'names'
  4212. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4213. add_type_info_type(c, operand->type);
  4214. }
  4215. if (is_type_enum(operand->type)) {
  4216. add_type_info_type(c, operand->type);
  4217. }
  4218. }
  4219. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  4220. String field_name = selector->Ident.token.string;
  4221. if (1 < field_name.len && field_name.len <= 4) {
  4222. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4223. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4224. bool found_xyzw = false;
  4225. bool found_rgba = false;
  4226. for (isize i = 0; i < field_name.len; i++) {
  4227. bool valid = false;
  4228. for (isize j = 0; j < 4; j++) {
  4229. if (field_name.text[i] == swizzles_xyzw[j]) {
  4230. found_xyzw = true;
  4231. valid = true;
  4232. break;
  4233. }
  4234. if (field_name.text[i] == swizzles_rgba[j]) {
  4235. found_rgba = true;
  4236. valid = true;
  4237. break;
  4238. }
  4239. }
  4240. if (!valid) {
  4241. goto end_of_array_selector_swizzle;
  4242. }
  4243. }
  4244. u8 *swizzles = nullptr;
  4245. u8 index_count = cast(u8)field_name.len;
  4246. if (found_xyzw && found_rgba) {
  4247. gbString op_str = expr_to_string(op_expr);
  4248. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4249. gb_string_free(op_str);
  4250. operand->mode = Addressing_Invalid;
  4251. operand->expr = node;
  4252. return nullptr;
  4253. }
  4254. u8 indices = 0;
  4255. if (found_xyzw) {
  4256. swizzles = swizzles_xyzw;
  4257. } else if (found_rgba) {
  4258. swizzles = swizzles_rgba;
  4259. }
  4260. for (isize i = 0; i < field_name.len; i++) {
  4261. for (isize j = 0; j < 4; j++) {
  4262. if (field_name.text[i] == swizzles[j]) {
  4263. indices |= cast(u8)(j)<<(i*2);
  4264. break;
  4265. }
  4266. }
  4267. }
  4268. Type *original_type = operand->type;
  4269. Type *array_type = base_type(type_deref(original_type));
  4270. GB_ASSERT(array_type->kind == Type_Array);
  4271. i64 array_count = array_type->Array.count;
  4272. for (u8 i = 0; i < index_count; i++) {
  4273. u8 idx = indices>>(i*2) & 3;
  4274. if (idx >= array_count) {
  4275. char c = 0;
  4276. if (found_xyzw) {
  4277. c = swizzles_xyzw[idx];
  4278. } else if (found_rgba) {
  4279. c = swizzles_rgba[idx];
  4280. } else {
  4281. GB_PANIC("unknown swizzle kind");
  4282. }
  4283. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4284. break;
  4285. }
  4286. }
  4287. se->swizzle_count = index_count;
  4288. se->swizzle_indices = indices;
  4289. AddressingMode prev_mode = operand->mode;
  4290. operand->mode = Addressing_SwizzleValue;
  4291. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4292. operand->expr = node;
  4293. switch (prev_mode) {
  4294. case Addressing_Variable:
  4295. case Addressing_SoaVariable:
  4296. case Addressing_SwizzleVariable:
  4297. operand->mode = Addressing_SwizzleVariable;
  4298. break;
  4299. }
  4300. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4301. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4302. return swizzle_entity;
  4303. }
  4304. end_of_array_selector_swizzle:;
  4305. }
  4306. if (entity == nullptr) {
  4307. gbString op_str = expr_to_string(op_expr);
  4308. gbString type_str = type_to_string_shorthand(operand->type);
  4309. gbString sel_str = expr_to_string(selector);
  4310. if (operand->mode == Addressing_Type) {
  4311. if (is_type_polymorphic(operand->type, true)) {
  4312. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4313. } else {
  4314. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4315. }
  4316. } else {
  4317. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4318. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4319. String const &name = selector->Ident.token.string;
  4320. Type *bt = base_type(operand->type);
  4321. if (operand->type->kind == Type_Named &&
  4322. operand->type->Named.type_name &&
  4323. operand->type->Named.type_name->kind == Entity_TypeName &&
  4324. operand->type->Named.type_name->TypeName.objc_metadata) {
  4325. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4326. } else if (bt->kind == Type_Struct) {
  4327. check_did_you_mean_type(name, bt->Struct.fields);
  4328. } else if (bt->kind == Type_Enum) {
  4329. check_did_you_mean_type(name, bt->Enum.fields);
  4330. }
  4331. }
  4332. }
  4333. gb_string_free(sel_str);
  4334. gb_string_free(type_str);
  4335. gb_string_free(op_str);
  4336. operand->mode = Addressing_Invalid;
  4337. operand->expr = node;
  4338. return nullptr;
  4339. }
  4340. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4341. bool success = false;
  4342. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4343. if (success) {
  4344. operand->mode = Addressing_Constant;
  4345. operand->expr = node;
  4346. operand->value = field_value;
  4347. operand->type = entity->type;
  4348. add_entity_use(c, selector, entity);
  4349. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4350. return entity;
  4351. }
  4352. gbString op_str = expr_to_string(op_expr);
  4353. gbString type_str = type_to_string_shorthand(operand->type);
  4354. gbString sel_str = expr_to_string(selector);
  4355. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4356. gb_string_free(sel_str);
  4357. gb_string_free(type_str);
  4358. gb_string_free(op_str);
  4359. operand->mode = Addressing_Invalid;
  4360. operand->expr = node;
  4361. return nullptr;
  4362. }
  4363. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4364. bool success = false;
  4365. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4366. if (success) {
  4367. operand->mode = Addressing_Constant;
  4368. operand->expr = node;
  4369. operand->value = field_value;
  4370. operand->type = entity->type;
  4371. add_entity_use(c, selector, entity);
  4372. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4373. return entity;
  4374. }
  4375. gbString op_str = expr_to_string(op_expr);
  4376. gbString type_str = type_to_string_shorthand(operand->type);
  4377. gbString sel_str = expr_to_string(selector);
  4378. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4379. gb_string_free(sel_str);
  4380. gb_string_free(type_str);
  4381. gb_string_free(op_str);
  4382. operand->mode = Addressing_Invalid;
  4383. operand->expr = node;
  4384. return nullptr;
  4385. }
  4386. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4387. gbString op_str = expr_to_string(op_expr);
  4388. gbString type_str = type_to_string_shorthand(operand->type);
  4389. gbString sel_str = expr_to_string(selector);
  4390. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4391. gb_string_free(sel_str);
  4392. gb_string_free(type_str);
  4393. gb_string_free(op_str);
  4394. operand->mode = Addressing_Invalid;
  4395. operand->expr = node;
  4396. return nullptr;
  4397. }
  4398. add_entity_use(c, selector, entity);
  4399. operand->type = entity->type;
  4400. operand->expr = node;
  4401. switch (entity->kind) {
  4402. case Entity_Constant:
  4403. operand->value = entity->Constant.value;
  4404. operand->mode = Addressing_Constant;
  4405. if (operand->value.kind == ExactValue_Procedure) {
  4406. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4407. if (proc != nullptr) {
  4408. operand->mode = Addressing_Value;
  4409. operand->type = proc->type;
  4410. }
  4411. }
  4412. break;
  4413. case Entity_Variable:
  4414. if (sel.indirect) {
  4415. operand->mode = Addressing_Variable;
  4416. } else if (operand->mode == Addressing_Context) {
  4417. // Do nothing
  4418. } else if (operand->mode == Addressing_MapIndex) {
  4419. operand->mode = Addressing_Value;
  4420. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4421. operand->mode = Addressing_SoaVariable;
  4422. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4423. operand->mode = Addressing_Value;
  4424. } else if (operand->mode == Addressing_SoaVariable) {
  4425. operand->mode = Addressing_Variable;
  4426. } else if (operand->mode != Addressing_Value) {
  4427. operand->mode = Addressing_Variable;
  4428. } else {
  4429. operand->mode = Addressing_Value;
  4430. }
  4431. break;
  4432. case Entity_TypeName:
  4433. operand->mode = Addressing_Type;
  4434. break;
  4435. case Entity_Procedure:
  4436. operand->mode = Addressing_Value;
  4437. operand->value = exact_value_procedure(node);
  4438. break;
  4439. case Entity_Builtin:
  4440. operand->mode = Addressing_Builtin;
  4441. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4442. break;
  4443. case Entity_ProcGroup:
  4444. operand->mode = Addressing_ProcGroup;
  4445. operand->proc_group = entity;
  4446. break;
  4447. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4448. case Entity_Nil:
  4449. operand->mode = Addressing_Value;
  4450. break;
  4451. }
  4452. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4453. return entity;
  4454. }
  4455. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4456. ptr = base_type(ptr);
  4457. if (is_type_pointer(ptr)) {
  4458. if (is_type_rawptr(ptr)) {
  4459. return false;
  4460. }
  4461. if (elem) *elem = ptr->Pointer.elem;
  4462. return true;
  4463. }
  4464. return false;
  4465. }
  4466. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4467. elem = core_type(elem);
  4468. if (is_type_internally_pointer_like(elem)) {
  4469. return true;
  4470. }
  4471. if (elem->kind == Type_BitSet) {
  4472. elem = bit_set_to_int(elem);
  4473. }
  4474. if (elem->kind != Type_Basic) {
  4475. return false;
  4476. }
  4477. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4478. }
  4479. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4480. switch (node->kind) {
  4481. case_ast_node(i, Ident, node);
  4482. String name = i->token.string;
  4483. if (nested) {
  4484. Entity *e = scope_lookup_current(s, name);
  4485. if (e != nullptr) {
  4486. if (out_scope) *out_scope = e->scope;
  4487. return true;
  4488. }
  4489. } else {
  4490. Entity *e = scope_lookup(s, name);
  4491. if (e != nullptr) {
  4492. if (out_scope) *out_scope = e->scope;
  4493. return true;
  4494. }
  4495. }
  4496. case_end;
  4497. case_ast_node(se, SelectorExpr, node);
  4498. Ast *lhs = se->expr;
  4499. Ast *rhs = se->selector;
  4500. Scope *lhs_scope = nullptr;
  4501. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4502. return check_identifier_exists(lhs_scope, rhs, true);
  4503. }
  4504. case_end;
  4505. }
  4506. return false;
  4507. }
  4508. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4509. if (o.type && is_type_no_copy(o.type)) {
  4510. Ast *expr = unparen_expr(o.expr);
  4511. if (expr && o.mode != Addressing_Constant) {
  4512. if (expr->kind == Ast_CallExpr) {
  4513. // Okay
  4514. } else {
  4515. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4516. return true;
  4517. }
  4518. }
  4519. }
  4520. return false;
  4521. }
  4522. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4523. bool optional_ok = false;
  4524. isize tuple_index = 0;
  4525. for (Ast *rhs_expr : rhs) {
  4526. CheckerContext c_ = *ctx;
  4527. CheckerContext *c = &c_;
  4528. Operand o = {};
  4529. Type *type_hint = nullptr;
  4530. if (tuple_index < lhs.count) {
  4531. type_hint = lhs[tuple_index].type;
  4532. }
  4533. check_expr_base(c, &o, rhs_expr, type_hint);
  4534. if (o.mode == Addressing_NoValue) {
  4535. error_operand_no_value(&o);
  4536. o.mode = Addressing_Invalid;
  4537. }
  4538. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4539. if (lhs.count == 2 && rhs.count == 1 &&
  4540. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4541. Ast *expr = unparen_expr(o.expr);
  4542. Operand val0 = o;
  4543. Operand val1 = o;
  4544. val0.mode = Addressing_Value;
  4545. val1.mode = Addressing_Value;
  4546. val1.type = t_untyped_bool;
  4547. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4548. if (expr->kind == Ast_TypeAssertion &&
  4549. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4550. // NOTE(bill): Used only for optimizations in the backend
  4551. if (is_blank_ident(lhs[0].expr)) {
  4552. expr->TypeAssertion.ignores[0] = true;
  4553. }
  4554. if (is_blank_ident(lhs[1].expr)) {
  4555. expr->TypeAssertion.ignores[1] = true;
  4556. }
  4557. }
  4558. array_add(operands, val0);
  4559. array_add(operands, val1);
  4560. optional_ok = true;
  4561. tuple_index += 2;
  4562. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4563. Type *tuple = o.type;
  4564. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4565. Ast *expr = unparen_expr(o.expr);
  4566. if (expr->kind == Ast_CallExpr) {
  4567. expr->CallExpr.optional_ok_one = true;
  4568. }
  4569. Operand val = o;
  4570. val.type = tuple->Tuple.variables[0]->type;
  4571. val.mode = Addressing_Value;
  4572. array_add(operands, val);
  4573. tuple_index += tuple->Tuple.variables.count;
  4574. } else {
  4575. array_add(operands, o);
  4576. tuple_index += 1;
  4577. }
  4578. } else {
  4579. TypeTuple *tuple = &o.type->Tuple;
  4580. for (Entity *e : tuple->variables) {
  4581. o.type = e->type;
  4582. array_add(operands, o);
  4583. check_no_copy_assignment(o, str_lit("assignment"));
  4584. }
  4585. tuple_index += tuple->variables.count;
  4586. }
  4587. }
  4588. return optional_ok;
  4589. }
  4590. typedef u32 UnpackFlags;
  4591. enum UnpackFlag : u32 {
  4592. UnpackFlag_None = 0,
  4593. UnpackFlag_AllowOk = 1<<0,
  4594. UnpackFlag_IsVariadic = 1<<1,
  4595. UnpackFlag_AllowUndef = 1<<2,
  4596. };
  4597. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4598. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4599. if (lhs == nullptr || c->decl == nullptr) {
  4600. return tuple_count;
  4601. }
  4602. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4603. Entity *e = lhs[tuple_index + j];
  4604. if (e == nullptr) {
  4605. continue;
  4606. }
  4607. DeclInfo *decl = decl_info_of_entity(e);
  4608. if (decl == nullptr) {
  4609. continue;
  4610. }
  4611. rw_mutex_shared_lock(&decl->deps_mutex);
  4612. rw_mutex_lock(&c->decl->deps_mutex);
  4613. for (Entity *dep : decl->deps) {
  4614. ptr_set_add(&c->decl->deps, dep);
  4615. }
  4616. rw_mutex_unlock(&c->decl->deps_mutex);
  4617. rw_mutex_shared_unlock(&decl->deps_mutex);
  4618. }
  4619. return tuple_count;
  4620. };
  4621. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4622. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4623. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4624. bool optional_ok = false;
  4625. isize tuple_index = 0;
  4626. for (Ast *rhs : rhs_arguments) {
  4627. if (rhs->kind == Ast_FieldValue) {
  4628. error(rhs, "Invalid use of 'field = value'");
  4629. rhs = rhs->FieldValue.value;
  4630. }
  4631. CheckerContext c_ = *ctx;
  4632. CheckerContext *c = &c_;
  4633. Operand o = {};
  4634. Type *type_hint = nullptr;
  4635. if (lhs != nullptr && tuple_index < lhs_count) {
  4636. // NOTE(bill): override DeclInfo for dependency
  4637. Entity *e = lhs[tuple_index];
  4638. if (e != nullptr) {
  4639. type_hint = e->type;
  4640. if (e->flags & EntityFlag_Ellipsis) {
  4641. GB_ASSERT(is_type_slice(e->type));
  4642. GB_ASSERT(e->type->kind == Type_Slice);
  4643. type_hint = e->type->Slice.elem;
  4644. }
  4645. }
  4646. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4647. // NOTE(bill): override DeclInfo for dependency
  4648. Entity *e = lhs[lhs_count-1];
  4649. if (e != nullptr) {
  4650. type_hint = e->type;
  4651. if (e->flags & EntityFlag_Ellipsis) {
  4652. GB_ASSERT(is_type_slice(e->type));
  4653. GB_ASSERT(e->type->kind == Type_Slice);
  4654. type_hint = e->type->Slice.elem;
  4655. }
  4656. }
  4657. }
  4658. Ast *rhs_expr = unparen_expr(rhs);
  4659. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4660. // NOTE(bill): Just handle this very specific logic here
  4661. o.type = t_untyped_uninit;
  4662. o.mode = Addressing_Value;
  4663. o.expr = rhs;
  4664. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4665. } else {
  4666. check_expr_base(c, &o, rhs, type_hint);
  4667. }
  4668. if (o.mode == Addressing_NoValue) {
  4669. error_operand_no_value(&o);
  4670. o.mode = Addressing_Invalid;
  4671. }
  4672. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4673. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4674. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4675. Ast *expr = unparen_expr(o.expr);
  4676. Operand val0 = o;
  4677. Operand val1 = o;
  4678. val0.mode = Addressing_Value;
  4679. val1.mode = Addressing_Value;
  4680. val1.type = t_untyped_bool;
  4681. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4682. if (expr->kind == Ast_TypeAssertion &&
  4683. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4684. // NOTE(bill): Used only for optimizations in the backend
  4685. if (is_blank_ident(lhs[0]->token)) {
  4686. expr->TypeAssertion.ignores[0] = true;
  4687. }
  4688. if (is_blank_ident(lhs[1]->token)) {
  4689. expr->TypeAssertion.ignores[1] = true;
  4690. }
  4691. }
  4692. array_add(operands, val0);
  4693. array_add(operands, val1);
  4694. optional_ok = true;
  4695. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4696. } else {
  4697. array_add(operands, o);
  4698. tuple_index += 1;
  4699. }
  4700. } else {
  4701. TypeTuple *tuple = &o.type->Tuple;
  4702. for (Entity *e : tuple->variables) {
  4703. o.type = e->type;
  4704. array_add(operands, o);
  4705. }
  4706. isize count = tuple->variables.count;
  4707. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4708. }
  4709. }
  4710. return optional_ok;
  4711. }
  4712. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4713. GB_ASSERT(pt != nullptr);
  4714. GB_ASSERT(pt->kind == Type_Proc);
  4715. isize param_count = 0;
  4716. isize param_count_excluding_defaults = 0;
  4717. bool variadic = pt->Proc.variadic;
  4718. TypeTuple *param_tuple = nullptr;
  4719. if (pt->Proc.params != nullptr) {
  4720. param_tuple = &pt->Proc.params->Tuple;
  4721. param_count = param_tuple->variables.count;
  4722. if (variadic) {
  4723. for (isize i = param_count-1; i >= 0; i--) {
  4724. Entity *e = param_tuple->variables[i];
  4725. if (e->kind == Entity_TypeName) {
  4726. break;
  4727. }
  4728. if (e->kind == Entity_Variable) {
  4729. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4730. param_count--;
  4731. continue;
  4732. }
  4733. }
  4734. break;
  4735. }
  4736. param_count--;
  4737. }
  4738. }
  4739. param_count_excluding_defaults = param_count;
  4740. if (param_tuple != nullptr) {
  4741. for (isize i = param_count-1; i >= 0; i--) {
  4742. Entity *e = param_tuple->variables[i];
  4743. if (e->kind == Entity_TypeName) {
  4744. break;
  4745. }
  4746. if (e->kind == Entity_Variable) {
  4747. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4748. param_count_excluding_defaults--;
  4749. continue;
  4750. }
  4751. }
  4752. break;
  4753. }
  4754. }
  4755. if (param_count_) *param_count_ = param_count;
  4756. return param_count_excluding_defaults;
  4757. }
  4758. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4759. isize param_count = pt->param_count;
  4760. for (isize i = 0; i < param_count; i++) {
  4761. Entity *e = pt->params->Tuple.variables[i];
  4762. String name = e->token.string;
  4763. if (is_blank_ident(name)) {
  4764. continue;
  4765. }
  4766. if (name == parameter_name) {
  4767. return i;
  4768. }
  4769. }
  4770. return -1;
  4771. }
  4772. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4773. type = base_type(type);
  4774. GB_ASSERT(type->kind == Type_Proc);
  4775. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4776. }
  4777. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  4778. Entity *entity, Type *proc_type,
  4779. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  4780. CallArgumentErrorMode show_error_mode,
  4781. CallArgumentData *data) {
  4782. TEMPORARY_ALLOCATOR_GUARD();
  4783. CallArgumentError err = CallArgumentError_None;
  4784. ast_node(ce, CallExpr, call);
  4785. GB_ASSERT(is_type_proc(proc_type));
  4786. proc_type = base_type(proc_type);
  4787. TypeProc *pt = &proc_type->Proc;
  4788. isize param_count = 0;
  4789. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4790. bool variadic = pt->variadic;
  4791. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4792. i64 score = 0;
  4793. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  4794. Type *final_proc_type = proc_type;
  4795. Entity *gen_entity = nullptr;
  4796. if (vari_expand && !variadic) {
  4797. if (show_error) {
  4798. error(ce->ellipsis,
  4799. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4800. LIT(ce->proc->Ident.token.string));
  4801. }
  4802. err = CallArgumentError_NonVariadicExpand;
  4803. } else if (vari_expand && pt->c_vararg) {
  4804. if (show_error) {
  4805. error(ce->ellipsis,
  4806. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4807. LIT(ce->proc->Ident.token.string));
  4808. }
  4809. err = CallArgumentError_NonVariadicExpand;
  4810. }
  4811. GB_ASSERT(ce->split_args);
  4812. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  4813. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  4814. defer ({
  4815. for (Operand const &o : ordered_operands) {
  4816. if (o.expr != nullptr) {
  4817. call->viral_state_flags |= o.expr->viral_state_flags;
  4818. }
  4819. }
  4820. });
  4821. isize positional_operand_count = positional_operands.count;
  4822. if (variadic) {
  4823. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  4824. } else if (positional_operand_count > pt->param_count) {
  4825. err = CallArgumentError_TooManyArguments;
  4826. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4827. if (show_error) {
  4828. gbString proc_str = expr_to_string(ce->proc);
  4829. defer (gb_string_free(proc_str));
  4830. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  4831. }
  4832. return err;
  4833. }
  4834. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  4835. for (isize i = 0; i < positional_operand_count; i++) {
  4836. ordered_operands[i] = positional_operands[i];
  4837. visited[i] = true;
  4838. }
  4839. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  4840. bool named_variadic_param = false;
  4841. if (named_operands.count != 0) {
  4842. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  4843. for_array(i, ce->split_args->named) {
  4844. Ast *arg = ce->split_args->named[i];
  4845. Operand operand = named_operands[i];
  4846. ast_node(fv, FieldValue, arg);
  4847. if (fv->field->kind != Ast_Ident) {
  4848. if (show_error) {
  4849. gbString expr_str = expr_to_string(fv->field);
  4850. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4851. gb_string_free(expr_str);
  4852. }
  4853. err = CallArgumentError_InvalidFieldValue;
  4854. continue;
  4855. }
  4856. String name = fv->field->Ident.token.string;
  4857. isize param_index = lookup_procedure_parameter(pt, name);
  4858. if (param_index < 0) {
  4859. if (show_error) {
  4860. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4861. }
  4862. err = CallArgumentError_ParameterNotFound;
  4863. continue;
  4864. }
  4865. if (pt->variadic && param_index == pt->variadic_index) {
  4866. named_variadic_param = true;
  4867. }
  4868. if (visited[param_index]) {
  4869. if (show_error) {
  4870. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4871. }
  4872. err = CallArgumentError_DuplicateParameter;
  4873. continue;
  4874. }
  4875. visited[param_index] = true;
  4876. ordered_operands[param_index] = operand;
  4877. }
  4878. }
  4879. isize dummy_argument_count = 0;
  4880. bool actually_variadic = false;
  4881. if (variadic) {
  4882. if (visited[pt->variadic_index] &&
  4883. positional_operand_count < positional_operands.count) {
  4884. if (show_error) {
  4885. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  4886. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  4887. }
  4888. err = CallArgumentError_DuplicateParameter;
  4889. } else if (!visited[pt->variadic_index]) {
  4890. visited[pt->variadic_index] = true;
  4891. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  4892. if (vari_expand) {
  4893. GB_ASSERT(variadic_operands.count != 0);
  4894. *variadic_operand = variadic_operands[0];
  4895. variadic_operand->type = default_type(variadic_operand->type);
  4896. actually_variadic = true;
  4897. } else {
  4898. AstFile *f = call->file();
  4899. // HACK(bill): this is an awful hack
  4900. Operand o = {};
  4901. o.mode = Addressing_Value;
  4902. o.expr = ast_ident(f, make_token_ident("nil"));
  4903. o.expr->Ident.token.pos = ast_token(call).pos;
  4904. if (variadic_operands.count != 0) {
  4905. actually_variadic = true;
  4906. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  4907. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  4908. o.type = vt->type;
  4909. } else {
  4910. dummy_argument_count += 1;
  4911. o.type = t_untyped_nil;
  4912. }
  4913. *variadic_operand = o;
  4914. }
  4915. }
  4916. }
  4917. for (Operand const &o : ordered_operands) {
  4918. if (o.mode != Addressing_Invalid) {
  4919. check_no_copy_assignment(o, str_lit("procedure call expression"));
  4920. }
  4921. }
  4922. for (isize i = 0; i < pt->param_count; i++) {
  4923. if (!visited[i]) {
  4924. Entity *e = pt->params->Tuple.variables[i];
  4925. if (is_blank_ident(e->token)) {
  4926. continue;
  4927. }
  4928. if (e->kind == Entity_Variable) {
  4929. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4930. ordered_operands[i].mode = Addressing_Value;
  4931. ordered_operands[i].type = e->type;
  4932. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  4933. dummy_argument_count += 1;
  4934. score += assign_score_function(1);
  4935. continue;
  4936. }
  4937. }
  4938. if (show_error) {
  4939. if (e->kind == Entity_TypeName) {
  4940. error(call, "Type parameter '%.*s' is missing in procedure call",
  4941. LIT(e->token.string));
  4942. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4943. // Ignore
  4944. } else {
  4945. gbString str = type_to_string(e->type);
  4946. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4947. LIT(e->token.string), str);
  4948. gb_string_free(str);
  4949. }
  4950. }
  4951. err = CallArgumentError_ParameterMissing;
  4952. }
  4953. }
  4954. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  4955. i64 s = 0;
  4956. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic)) {
  4957. bool ok = false;
  4958. if (e && e->flags & EntityFlag_AnyInt) {
  4959. if (is_type_integer(param_type)) {
  4960. ok = check_is_castable_to(c, o, param_type);
  4961. }
  4962. }
  4963. if (ok) {
  4964. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4965. } else {
  4966. if (show_error) {
  4967. check_assignment(c, o, param_type, str_lit("procedure argument"));
  4968. Type *src = base_type(o->type);
  4969. Type *dst = base_type(param_type);
  4970. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  4971. gbString a = expr_to_string(o->expr);
  4972. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  4973. gb_string_free(a);
  4974. }
  4975. }
  4976. err = CallArgumentError_WrongTypes;
  4977. }
  4978. } else if (show_error) {
  4979. check_assignment(c, o, param_type, str_lit("procedure argument"));
  4980. }
  4981. if (e && e->flags & EntityFlag_ConstInput) {
  4982. if (o->mode != Addressing_Constant) {
  4983. if (show_error) {
  4984. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4985. }
  4986. err = CallArgumentError_NoneConstantParameter;
  4987. }
  4988. }
  4989. if (!err && is_type_any(param_type)) {
  4990. add_type_info_type(c, o->type);
  4991. }
  4992. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  4993. add_type_info_type(c, o->type);
  4994. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  4995. } else if (show_error && is_type_untyped(o->type)) {
  4996. update_untyped_expr_type(c, o->expr, param_type, true);
  4997. }
  4998. return s;
  4999. };
  5000. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5001. err = CallArgumentError_None;
  5002. if (variadic) {
  5003. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5004. Type *t = pt->params->Tuple.variables[0]->type;
  5005. if (is_type_polymorphic(t)) {
  5006. if (show_error) {
  5007. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5008. }
  5009. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5010. }
  5011. }
  5012. } else {
  5013. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5014. PolyProcData poly_proc_data = {};
  5015. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5016. gen_entity = poly_proc_data.gen_entity;
  5017. Type *gept = base_type(gen_entity->type);
  5018. GB_ASSERT(is_type_proc(gept));
  5019. final_proc_type = gen_entity->type;
  5020. pt = &gept->Proc;
  5021. } else {
  5022. err = CallArgumentError_WrongTypes;
  5023. }
  5024. }
  5025. for (isize i = 0; i < pt->param_count; i++) {
  5026. Operand *o = &ordered_operands[i];
  5027. if (o->mode == Addressing_Invalid) {
  5028. continue;
  5029. }
  5030. Entity *e = pt->params->Tuple.variables[i];
  5031. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5032. if (e->kind == Entity_TypeName) {
  5033. GB_ASSERT(pt->is_polymorphic);
  5034. if (o->mode != Addressing_Type) {
  5035. if (show_error) {
  5036. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5037. }
  5038. err = CallArgumentError_WrongTypes;
  5039. }
  5040. if (are_types_identical(e->type, o->type)) {
  5041. score += assign_score_function(1);
  5042. } else {
  5043. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5044. }
  5045. continue;
  5046. }
  5047. if (param_is_variadic) {
  5048. continue;
  5049. }
  5050. score += eval_param_and_score(c, o, e->type, err, param_is_variadic, e, show_error);
  5051. }
  5052. }
  5053. if (variadic) {
  5054. Type *slice = pt->params->Tuple.variables[pt->variadic_index]->type;
  5055. GB_ASSERT(is_type_slice(slice));
  5056. Type *elem = base_type(slice)->Slice.elem;
  5057. Type *t = elem;
  5058. if (is_type_polymorphic(t)) {
  5059. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5060. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5061. }
  5062. for_array(operand_index, variadic_operands) {
  5063. Operand *o = &variadic_operands[operand_index];
  5064. if (vari_expand) {
  5065. t = slice;
  5066. if (operand_index > 0) {
  5067. if (show_error) {
  5068. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5069. }
  5070. if (data) {
  5071. data->score = score;
  5072. data->result_type = final_proc_type->Proc.results;
  5073. data->gen_entity = gen_entity;
  5074. }
  5075. return CallArgumentError_MultipleVariadicExpand;
  5076. }
  5077. }
  5078. score += eval_param_and_score(c, o, t, err, true, nullptr, show_error);
  5079. }
  5080. }
  5081. if (data) {
  5082. data->score = score;
  5083. data->result_type = final_proc_type->Proc.results;
  5084. data->gen_entity = gen_entity;
  5085. Ast *proc_lit = nullptr;
  5086. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5087. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5088. if (vp && vp->kind == Ast_ProcLit) {
  5089. proc_lit = vp;
  5090. }
  5091. }
  5092. if (proc_lit == nullptr) {
  5093. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5094. }
  5095. }
  5096. return err;
  5097. }
  5098. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5099. GB_ASSERT(ce != nullptr);
  5100. if (ce->args.count == 0) {
  5101. return false;
  5102. }
  5103. return ce->args[0]->kind == Ast_FieldValue;
  5104. }
  5105. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5106. Entity **lhs = nullptr;
  5107. isize lhs_count = -1;
  5108. if (proc_type == nullptr) {
  5109. return nullptr;
  5110. }
  5111. GB_ASSERT(is_type_proc(proc_type));
  5112. TypeProc *pt = &base_type(proc_type)->Proc;
  5113. *is_variadic = pt->variadic;
  5114. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5115. if (pt->params != nullptr) {
  5116. lhs = pt->params->Tuple.variables.data;
  5117. lhs_count = pt->params->Tuple.variables.count;
  5118. }
  5119. } else {
  5120. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5121. if (pt->params == nullptr) {
  5122. lhs_count = 0;
  5123. } else {
  5124. lhs_count = pt->params->Tuple.variables.count;
  5125. }
  5126. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5127. for (isize i = 0; i < lhs_count; i++) {
  5128. Entity *e = pt->params->Tuple.variables[i];
  5129. if (!is_type_polymorphic(e->type)) {
  5130. lhs[i] = e;
  5131. }
  5132. }
  5133. }
  5134. if (lhs_count_) *lhs_count_ = lhs_count;
  5135. return lhs;
  5136. }
  5137. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5138. if (clauses != nullptr) {
  5139. for (Ast *clause : *clauses) {
  5140. Operand o = {};
  5141. check_expr(ctx, &o, clause);
  5142. if (o.mode != Addressing_Constant) {
  5143. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5144. if (print_err && call_expr) error(call_expr, "at caller location");
  5145. return false;
  5146. } else if (o.value.kind != ExactValue_Bool) {
  5147. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5148. if (print_err && call_expr) error(call_expr, "at caller location");
  5149. return false;
  5150. } else if (!o.value.value_bool) {
  5151. if (print_err) {
  5152. ERROR_BLOCK();
  5153. gbString str = expr_to_string(clause);
  5154. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5155. gb_string_free(str);
  5156. if (scope != nullptr) {
  5157. isize print_count = 0;
  5158. for (auto const &entry : scope->elements) {
  5159. Entity *e = entry.value;
  5160. switch (e->kind) {
  5161. case Entity_TypeName: {
  5162. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5163. gbString str = type_to_string(e->type);
  5164. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5165. gb_string_free(str);
  5166. print_count += 1;
  5167. break;
  5168. }
  5169. case Entity_Constant: {
  5170. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5171. gbString str = exact_value_to_string(e->Constant.value);
  5172. if (is_type_untyped(e->type)) {
  5173. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5174. } else {
  5175. gbString t = type_to_string(e->type);
  5176. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5177. gb_string_free(t);
  5178. }
  5179. gb_string_free(str);
  5180. print_count += 1;
  5181. break;
  5182. }
  5183. }
  5184. }
  5185. }
  5186. if (call_expr) error(call_expr, "at caller location");
  5187. }
  5188. return false;
  5189. }
  5190. }
  5191. }
  5192. return true;
  5193. }
  5194. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5195. bool success = true;
  5196. type = base_type(type);
  5197. if (named_args.count > 0) {
  5198. TypeProc *pt = nullptr;
  5199. if (is_type_proc(type)) {
  5200. pt = &type->Proc;
  5201. }
  5202. for_array(i, named_args) {
  5203. Ast *arg = named_args[i];
  5204. if (arg->kind != Ast_FieldValue) {
  5205. if (show_error) {
  5206. error(arg, "Expected a 'field = value'");
  5207. }
  5208. return false;
  5209. }
  5210. ast_node(fv, FieldValue, arg);
  5211. if (fv->field->kind != Ast_Ident) {
  5212. if (show_error) {
  5213. gbString expr_str = expr_to_string(fv->field);
  5214. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5215. gb_string_free(expr_str);
  5216. }
  5217. success = false;
  5218. continue;
  5219. }
  5220. String key = fv->field->Ident.token.string;
  5221. Ast *value = fv->value;
  5222. Type *type_hint = nullptr;
  5223. if (pt) {
  5224. isize param_index = lookup_procedure_parameter(pt, key);
  5225. if (param_index < 0) {
  5226. if (show_error) {
  5227. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5228. }
  5229. success = false;
  5230. continue;
  5231. }
  5232. Entity *e = pt->params->Tuple.variables[param_index];
  5233. if (!is_type_polymorphic(e->type)) {
  5234. type_hint = e->type;
  5235. }
  5236. }
  5237. Operand o = {};
  5238. check_expr_with_type_hint(c, &o, value, type_hint);
  5239. if (o.mode == Addressing_Invalid) {
  5240. success = false;
  5241. }
  5242. array_add(named_operands, o);
  5243. }
  5244. }
  5245. return success;
  5246. }
  5247. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5248. Entity *e, Type *proc_type,
  5249. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5250. CallArgumentErrorMode show_error_mode,
  5251. CallArgumentData *data) {
  5252. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5253. Ast *ident = operand->expr;
  5254. while (ident->kind == Ast_SelectorExpr) {
  5255. Ast *s = ident->SelectorExpr.selector;
  5256. ident = s;
  5257. }
  5258. if (e == nullptr) {
  5259. e = entity_of_node(ident);
  5260. if (e != nullptr) {
  5261. proc_type = e->type;
  5262. }
  5263. }
  5264. GB_ASSERT(proc_type != nullptr);
  5265. proc_type = base_type(proc_type);
  5266. GB_ASSERT(proc_type->kind == Type_Proc);
  5267. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5268. if (return_on_failure && err != CallArgumentError_None) {
  5269. return false;
  5270. }
  5271. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5272. if (!return_on_failure && entity_to_use != nullptr) {
  5273. add_entity_use(c, ident, entity_to_use);
  5274. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5275. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5276. }
  5277. if (data->gen_entity != nullptr) {
  5278. Entity *e = data->gen_entity;
  5279. DeclInfo *decl = data->gen_entity->decl_info;
  5280. CheckerContext ctx = *c;
  5281. ctx.scope = decl->scope;
  5282. ctx.decl = decl;
  5283. ctx.proc_name = e->token.string;
  5284. ctx.curr_proc_decl = decl;
  5285. ctx.curr_proc_sig = e->type;
  5286. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5287. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5288. if (return_on_failure) {
  5289. if (!ok) {
  5290. return false;
  5291. }
  5292. } else {
  5293. decl->where_clauses_evaluated = true;
  5294. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5295. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5296. }
  5297. if (is_type_proc(data->gen_entity->type)) {
  5298. Type *t = base_type(entity_to_use->type);
  5299. data->result_type = t->Proc.results;
  5300. }
  5301. }
  5302. }
  5303. return true;
  5304. }
  5305. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5306. ast_node(ce, CallExpr, call);
  5307. GB_ASSERT(ce->split_args != nullptr);
  5308. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5309. Slice<Ast *> const &named_args = ce->split_args->named;
  5310. CallArgumentData data = {};
  5311. data.result_type = t_invalid;
  5312. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5313. auto procs = proc_group_entities_cloned(c, *operand);
  5314. if (procs.count > 1) {
  5315. isize max_arg_count = positional_args.count + named_args.count;
  5316. for (Ast *arg : positional_args) {
  5317. // NOTE(bill): The only thing that may have multiple values
  5318. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5319. arg = strip_or_return_expr(arg);
  5320. if (arg && arg->kind == Ast_CallExpr) {
  5321. max_arg_count = ISIZE_MAX;
  5322. break;
  5323. }
  5324. }
  5325. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5326. // NOTE(bill): The only thing that may have multiple values
  5327. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5328. if (arg->kind == Ast_FieldValue) {
  5329. arg = strip_or_return_expr(arg->FieldValue.value);
  5330. if (arg && arg->kind == Ast_CallExpr) {
  5331. max_arg_count = ISIZE_MAX;
  5332. break;
  5333. }
  5334. }
  5335. }
  5336. // ignore named arguments first
  5337. for (Ast *arg : named_args) {
  5338. if (arg->kind != Ast_FieldValue) {
  5339. continue;
  5340. }
  5341. ast_node(fv, FieldValue, arg);
  5342. if (fv->field->kind != Ast_Ident) {
  5343. continue;
  5344. }
  5345. String key = fv->field->Ident.token.string;
  5346. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5347. Type *t = procs[proc_index]->type;
  5348. if (is_type_proc(t)) {
  5349. isize param_index = lookup_procedure_parameter(t, key);
  5350. if (param_index < 0) {
  5351. array_unordered_remove(&procs, proc_index);
  5352. }
  5353. }
  5354. }
  5355. }
  5356. if (procs.count == 0) {
  5357. // if any of the named arguments are wrong, the `procs` will be empty
  5358. // just start from scratch
  5359. array_free(&procs);
  5360. procs = proc_group_entities_cloned(c, *operand);
  5361. }
  5362. // filter by positional argument length
  5363. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5364. Entity *proc = procs[proc_index];
  5365. Type *pt = base_type(proc->type);
  5366. if (!(pt != nullptr && is_type_proc(pt))) {
  5367. proc_index++;
  5368. continue;
  5369. }
  5370. isize param_count = 0;
  5371. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5372. if (param_count_excluding_defaults > max_arg_count) {
  5373. array_unordered_remove(&procs, proc_index);
  5374. continue;
  5375. }
  5376. proc_index++;
  5377. }
  5378. }
  5379. Entity **lhs = nullptr;
  5380. isize lhs_count = -1;
  5381. bool is_variadic = false;
  5382. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5383. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5384. defer (array_free(&positional_operands));
  5385. defer (array_free(&named_operands));
  5386. if (procs.count == 1) {
  5387. Entity *e = procs[0];
  5388. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5389. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5390. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5391. check_call_arguments_single(c, call, operand,
  5392. e, e->type,
  5393. positional_operands, named_operands,
  5394. CallArgumentErrorMode::ShowErrors,
  5395. &data);
  5396. }
  5397. return data;
  5398. }
  5399. {
  5400. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5401. // where the same positional parameter has the same type value (and ellipsis)
  5402. isize proc_arg_count = -1;
  5403. for (Entity *p : procs) {
  5404. Type *pt = base_type(p->type);
  5405. if (pt != nullptr && is_type_proc(pt)) {
  5406. if (proc_arg_count < 0) {
  5407. proc_arg_count = pt->Proc.param_count;
  5408. } else {
  5409. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5410. }
  5411. }
  5412. }
  5413. if (proc_arg_count >= 0) {
  5414. lhs_count = proc_arg_count;
  5415. if (lhs_count > 0) {
  5416. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5417. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5418. Entity *e = nullptr;
  5419. for (Entity *p : procs) {
  5420. Type *pt = base_type(p->type);
  5421. if (!(pt != nullptr && is_type_proc(pt))) {
  5422. continue;
  5423. }
  5424. if (e == nullptr) {
  5425. e = pt->Proc.params->Tuple.variables[param_index];
  5426. } else {
  5427. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5428. if (e == f) {
  5429. continue;
  5430. }
  5431. if (are_types_identical(e->type, f->type)) {
  5432. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5433. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5434. if (ee == fe) {
  5435. continue;
  5436. }
  5437. }
  5438. // NOTE(bill): Entities are not close enough to be used
  5439. e = nullptr;
  5440. break;
  5441. }
  5442. }
  5443. lhs[param_index] = e;
  5444. }
  5445. }
  5446. }
  5447. }
  5448. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5449. for_array(i, named_args) {
  5450. Ast *arg = named_args[i];
  5451. if (arg->kind != Ast_FieldValue) {
  5452. error(arg, "Expected a 'field = value'");
  5453. return data;
  5454. }
  5455. ast_node(fv, FieldValue, arg);
  5456. if (fv->field->kind != Ast_Ident) {
  5457. gbString expr_str = expr_to_string(fv->field);
  5458. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5459. gb_string_free(expr_str);
  5460. return data;
  5461. }
  5462. String key = fv->field->Ident.token.string;
  5463. Ast *value = fv->value;
  5464. Type *type_hint = nullptr;
  5465. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5466. Entity *e = lhs[lhs_idx];
  5467. if (e != nullptr && e->token.string == key &&
  5468. !is_type_polymorphic(e->type)) {
  5469. type_hint = e->type;
  5470. break;
  5471. }
  5472. }
  5473. Operand o = {};
  5474. check_expr_with_type_hint(c, &o, value, type_hint);
  5475. array_add(&named_operands, o);
  5476. }
  5477. gb_free(heap_allocator(), lhs);
  5478. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5479. defer (array_free(&valids));
  5480. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5481. defer (array_free(&proc_entities));
  5482. for (Entity *proc : procs) {
  5483. array_add(&proc_entities, proc);
  5484. }
  5485. gbString expr_name = expr_to_string(operand->expr);
  5486. defer (gb_string_free(expr_name));
  5487. for_array(i, procs) {
  5488. Entity *p = procs[i];
  5489. Type *pt = base_type(p->type);
  5490. if (pt != nullptr && is_type_proc(pt)) {
  5491. CallArgumentData data = {};
  5492. CheckerContext ctx = *c;
  5493. ctx.no_polymorphic_errors = true;
  5494. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5495. ctx.hide_polymorphic_errors = true;
  5496. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5497. p, pt,
  5498. positional_operands, named_operands,
  5499. CallArgumentErrorMode::NoErrors,
  5500. &data);
  5501. if (!is_a_candidate) {
  5502. continue;
  5503. }
  5504. isize index = i;
  5505. ValidIndexAndScore item = {};
  5506. item.score = data.score;
  5507. if (data.gen_entity != nullptr) {
  5508. array_add(&proc_entities, data.gen_entity);
  5509. index = proc_entities.count-1;
  5510. // prefer non-polymorphic procedures over polymorphic
  5511. item.score += assign_score_function(1);
  5512. }
  5513. item.index = index;
  5514. array_add(&valids, item);
  5515. }
  5516. }
  5517. if (valids.count > 1) {
  5518. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  5519. i64 best_score = valids[0].score;
  5520. Entity *best_entity = proc_entities[valids[0].index];
  5521. GB_ASSERT(best_entity != nullptr);
  5522. for (isize i = 1; i < valids.count; i++) {
  5523. if (best_score > valids[i].score) {
  5524. valids.count = i;
  5525. break;
  5526. }
  5527. if (best_entity == proc_entities[valids[i].index]) {
  5528. valids.count = i;
  5529. break;
  5530. }
  5531. }
  5532. }
  5533. auto print_argument_types = [&]() {
  5534. error_line("\tGiven argument types: (");
  5535. isize i = 0;
  5536. for (Operand const &o : positional_operands) {
  5537. if (i++ > 0) error_line(", ");
  5538. gbString type = type_to_string(o.type);
  5539. defer (gb_string_free(type));
  5540. error_line("%s", type);
  5541. }
  5542. for (Operand const &o : named_operands) {
  5543. if (i++ > 0) error_line(", ");
  5544. gbString type = type_to_string(o.type);
  5545. defer (gb_string_free(type));
  5546. if (i < ce->split_args->named.count) {
  5547. Ast *named_field = ce->split_args->named[i];
  5548. ast_node(fv, FieldValue, named_field);
  5549. gbString field = expr_to_string(fv->field);
  5550. defer (gb_string_free(field));
  5551. error_line("%s = %s", field, type);
  5552. } else {
  5553. error_line("%s", type);
  5554. }
  5555. }
  5556. error_line(")\n");
  5557. };
  5558. if (valids.count == 0) {
  5559. begin_error_block();
  5560. defer (end_error_block());
  5561. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5562. if (positional_operands.count == 0 && named_operands.count == 0) {
  5563. error_line("\tNo given arguments\n");
  5564. } else {
  5565. print_argument_types();
  5566. }
  5567. if (procs.count == 0) {
  5568. procs = proc_group_entities_cloned(c, *operand);
  5569. }
  5570. if (procs.count > 0) {
  5571. error_line("Did you mean to use one of the following:\n");
  5572. }
  5573. isize max_name_length = 0;
  5574. isize max_type_length = 0;
  5575. for (Entity *proc : procs) {
  5576. Type *t = base_type(proc->type);
  5577. if (t == t_invalid) continue;
  5578. String prefix = {};
  5579. String prefix_sep = {};
  5580. if (proc->pkg) {
  5581. prefix = proc->pkg->name;
  5582. prefix_sep = str_lit(".");
  5583. }
  5584. String name = proc->token.string;
  5585. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5586. gbString pt;
  5587. if (t->Proc.node != nullptr) {
  5588. pt = expr_to_string(t->Proc.node);
  5589. } else {
  5590. pt = type_to_string(t);
  5591. }
  5592. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5593. gb_string_free(pt);
  5594. }
  5595. isize max_spaces = gb_max(max_name_length, max_type_length);
  5596. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5597. for (isize i = 0; i < max_spaces; i++) {
  5598. spaces[i] = ' ';
  5599. }
  5600. spaces[max_spaces] = 0;
  5601. for (Entity *proc : procs) {
  5602. TokenPos pos = proc->token.pos;
  5603. Type *t = base_type(proc->type);
  5604. if (t == t_invalid) continue;
  5605. GB_ASSERT(t->kind == Type_Proc);
  5606. gbString pt;
  5607. defer (gb_string_free(pt));
  5608. if (t->Proc.node != nullptr) {
  5609. pt = expr_to_string(t->Proc.node);
  5610. } else {
  5611. pt = type_to_string(t);
  5612. }
  5613. String prefix = {};
  5614. String prefix_sep = {};
  5615. if (proc->pkg) {
  5616. prefix = proc->pkg->name;
  5617. prefix_sep = str_lit(".");
  5618. }
  5619. String name = proc->token.string;
  5620. isize len = prefix.len + prefix_sep.len + name.len;
  5621. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5622. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5623. char const *sep = "::";
  5624. if (proc->kind == Entity_Variable) {
  5625. sep = ":=";
  5626. }
  5627. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5628. LIT(prefix), LIT(prefix_sep), LIT(name),
  5629. name_padding, spaces,
  5630. sep,
  5631. pt,
  5632. type_padding, spaces,
  5633. token_pos_to_string(pos)
  5634. );
  5635. }
  5636. if (procs.count > 0) {
  5637. error_line("\n");
  5638. }
  5639. data.result_type = t_invalid;
  5640. } else if (valids.count > 1) {
  5641. begin_error_block();
  5642. defer (end_error_block());
  5643. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5644. print_argument_types();
  5645. for (auto const &valid : valids) {
  5646. Entity *proc = proc_entities[valid.index];
  5647. GB_ASSERT(proc != nullptr);
  5648. TokenPos pos = proc->token.pos;
  5649. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5650. gbString pt = nullptr;
  5651. defer (gb_string_free(pt));
  5652. if (t->Proc.node != nullptr) {
  5653. pt = expr_to_string(t->Proc.node);
  5654. } else {
  5655. pt = type_to_string(t);
  5656. }
  5657. String name = proc->token.string;
  5658. char const *sep = "::";
  5659. if (proc->kind == Entity_Variable) {
  5660. sep = ":=";
  5661. }
  5662. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5663. if (proc->decl_info->proc_lit != nullptr) {
  5664. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5665. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5666. if (pl->where_token.kind != Token_Invalid) {
  5667. error_line("\n\t\twhere ");
  5668. for_array(j, pl->where_clauses) {
  5669. Ast *clause = pl->where_clauses[j];
  5670. if (j != 0) {
  5671. error_line("\t\t ");
  5672. }
  5673. gbString str = expr_to_string(clause);
  5674. error_line("%s", str);
  5675. gb_string_free(str);
  5676. if (j != pl->where_clauses.count-1) {
  5677. error_line(",");
  5678. }
  5679. }
  5680. error_line("\n\t");
  5681. }
  5682. }
  5683. error_line("at %s\n", token_pos_to_string(pos));
  5684. }
  5685. data.result_type = t_invalid;
  5686. } else {
  5687. GB_ASSERT(valids.count == 1);
  5688. Ast *ident = operand->expr;
  5689. while (ident->kind == Ast_SelectorExpr) {
  5690. Ast *s = ident->SelectorExpr.selector;
  5691. ident = s;
  5692. }
  5693. Entity *e = proc_entities[valids[0].index];
  5694. GB_ASSERT(e != nullptr);
  5695. Array<Operand> named_operands = {};
  5696. check_call_arguments_single(c, call, operand,
  5697. e, e->type,
  5698. positional_operands, named_operands,
  5699. CallArgumentErrorMode::ShowErrors,
  5700. &data);
  5701. return data;
  5702. }
  5703. return data;
  5704. }
  5705. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5706. Type *proc_type = nullptr;
  5707. CallArgumentData data = {};
  5708. data.result_type = t_invalid;
  5709. proc_type = base_type(operand->type);
  5710. TypeProc *pt = nullptr;
  5711. if (proc_type) {
  5712. pt = &proc_type->Proc;
  5713. }
  5714. TEMPORARY_ALLOCATOR_GUARD();
  5715. ast_node(ce, CallExpr, call);
  5716. bool any_failure = false;
  5717. // Split positional and named args into separate arrays/slices
  5718. Slice<Ast *> positional_args = {};
  5719. Slice<Ast *> named_args = {};
  5720. if (ce->split_args == nullptr) {
  5721. positional_args = ce->args;
  5722. for (isize i = 0; i < ce->args.count; i++) {
  5723. Ast *arg = ce->args.data[i];
  5724. if (arg->kind == Ast_FieldValue) {
  5725. positional_args.count = i;
  5726. break;
  5727. }
  5728. }
  5729. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5730. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5731. split_args->positional = positional_args;
  5732. split_args->named = named_args;
  5733. ce->split_args = split_args;
  5734. } else {
  5735. positional_args = ce->split_args->positional;
  5736. named_args = ce->split_args->named;
  5737. }
  5738. if (operand->mode == Addressing_ProcGroup) {
  5739. return check_call_arguments_proc_group(c, operand, call);
  5740. }
  5741. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5742. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5743. defer (array_free(&positional_operands));
  5744. defer (array_free(&named_operands));
  5745. if (positional_args.count > 0) {
  5746. isize lhs_count = -1;
  5747. bool is_variadic = false;
  5748. Entity **lhs = nullptr;
  5749. if (pt != nullptr) {
  5750. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5751. }
  5752. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5753. }
  5754. if (named_args.count > 0) {
  5755. for_array(i, named_args) {
  5756. Ast *arg = named_args[i];
  5757. if (arg->kind != Ast_FieldValue) {
  5758. error(arg, "Expected a 'field = value'");
  5759. return data;
  5760. }
  5761. ast_node(fv, FieldValue, arg);
  5762. if (fv->field->kind != Ast_Ident) {
  5763. gbString expr_str = expr_to_string(fv->field);
  5764. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5765. any_failure = true;
  5766. gb_string_free(expr_str);
  5767. continue;
  5768. }
  5769. String key = fv->field->Ident.token.string;
  5770. Ast *value = fv->value;
  5771. isize param_index = lookup_procedure_parameter(pt, key);
  5772. Type *type_hint = nullptr;
  5773. if (param_index >= 0) {
  5774. Entity *e = pt->params->Tuple.variables[param_index];
  5775. type_hint = e->type;
  5776. }
  5777. Operand o = {};
  5778. check_expr_with_type_hint(c, &o, value, type_hint);
  5779. if (o.mode == Addressing_Invalid) {
  5780. any_failure = true;
  5781. }
  5782. array_add(&named_operands, o);
  5783. }
  5784. }
  5785. if (!any_failure) {
  5786. check_call_arguments_single(c, call, operand,
  5787. nullptr, proc_type,
  5788. positional_operands, named_operands,
  5789. CallArgumentErrorMode::ShowErrors,
  5790. &data);
  5791. } else if (pt) {
  5792. data.result_type = pt->results;
  5793. }
  5794. return data;
  5795. }
  5796. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5797. if (!is_type_polymorphic_record(t)) {
  5798. return -1;
  5799. }
  5800. TypeTuple *params = get_record_polymorphic_params(t);
  5801. if (params == nullptr) {
  5802. return -1;
  5803. }
  5804. for_array(i, params->variables) {
  5805. Entity *e = params->variables[i];
  5806. String name = e->token.string;
  5807. if (is_blank_ident(name)) {
  5808. continue;
  5809. }
  5810. if (name == parameter_name) {
  5811. return i;
  5812. }
  5813. }
  5814. return -1;
  5815. }
  5816. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5817. ast_node(ce, CallExpr, call);
  5818. Type *original_type = operand->type;
  5819. GB_ASSERT(is_type_polymorphic_record(original_type));
  5820. bool show_error = true;
  5821. Array<Operand> operands = {};
  5822. defer (array_free(&operands));
  5823. bool named_fields = false;
  5824. {
  5825. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5826. auto prev_type_path = c->type_path;
  5827. c->type_path = new_checker_type_path();
  5828. defer ({
  5829. destroy_checker_type_path(c->type_path);
  5830. c->type_path = prev_type_path;
  5831. });
  5832. if (is_call_expr_field_value(ce)) {
  5833. named_fields = true;
  5834. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5835. for_array(i, ce->args) {
  5836. Ast *arg = ce->args[i];
  5837. ast_node(fv, FieldValue, arg);
  5838. if (fv->field->kind == Ast_Ident) {
  5839. String name = fv->field->Ident.token.string;
  5840. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5841. if (index >= 0) {
  5842. TypeTuple *params = get_record_polymorphic_params(original_type);
  5843. Entity *e = params->variables[i];
  5844. if (e->kind == Entity_Constant) {
  5845. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5846. continue;
  5847. }
  5848. }
  5849. }
  5850. check_expr_or_type(c, &operands[i], fv->value);
  5851. }
  5852. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5853. if (vari_expand) {
  5854. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5855. }
  5856. } else {
  5857. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5858. Entity **lhs = nullptr;
  5859. isize lhs_count = -1;
  5860. TypeTuple *params = get_record_polymorphic_params(original_type);
  5861. if (params != nullptr) {
  5862. lhs = params->variables.data;
  5863. lhs_count = params->variables.count;
  5864. }
  5865. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  5866. }
  5867. }
  5868. CallArgumentError err = CallArgumentError_None;
  5869. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5870. isize param_count = tuple->variables.count;
  5871. isize minimum_param_count = param_count;
  5872. for (; minimum_param_count > 0; minimum_param_count--) {
  5873. Entity *e = tuple->variables[minimum_param_count-1];
  5874. if (e->kind != Entity_Constant) {
  5875. break;
  5876. }
  5877. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5878. break;
  5879. }
  5880. }
  5881. Array<Operand> ordered_operands = operands;
  5882. if (!named_fields) {
  5883. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5884. array_copy(&ordered_operands, operands, 0);
  5885. } else {
  5886. TEMPORARY_ALLOCATOR_GUARD();
  5887. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5888. // LEAK(bill)
  5889. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5890. for_array(i, ce->args) {
  5891. Ast *arg = ce->args[i];
  5892. ast_node(fv, FieldValue, arg);
  5893. if (fv->field->kind != Ast_Ident) {
  5894. if (show_error) {
  5895. gbString expr_str = expr_to_string(fv->field);
  5896. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5897. gb_string_free(expr_str);
  5898. }
  5899. err = CallArgumentError_InvalidFieldValue;
  5900. continue;
  5901. }
  5902. String name = fv->field->Ident.token.string;
  5903. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5904. if (index < 0) {
  5905. if (show_error) {
  5906. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5907. }
  5908. err = CallArgumentError_ParameterNotFound;
  5909. continue;
  5910. }
  5911. if (visited[index]) {
  5912. if (show_error) {
  5913. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5914. }
  5915. err = CallArgumentError_DuplicateParameter;
  5916. continue;
  5917. }
  5918. visited[index] = true;
  5919. ordered_operands[index] = operands[i];
  5920. }
  5921. for (isize i = 0; i < param_count; i++) {
  5922. if (!visited[i]) {
  5923. Entity *e = tuple->variables[i];
  5924. if (is_blank_ident(e->token)) {
  5925. continue;
  5926. }
  5927. if (show_error) {
  5928. if (e->kind == Entity_TypeName) {
  5929. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5930. LIT(e->token.string));
  5931. } else {
  5932. gbString str = type_to_string(e->type);
  5933. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5934. LIT(e->token.string), str);
  5935. gb_string_free(str);
  5936. }
  5937. }
  5938. err = CallArgumentError_ParameterMissing;
  5939. }
  5940. }
  5941. }
  5942. if (err != 0) {
  5943. operand->mode = Addressing_Invalid;
  5944. return err;
  5945. }
  5946. while (ordered_operands.count > 0) {
  5947. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5948. break;
  5949. }
  5950. array_pop(&ordered_operands);
  5951. }
  5952. if (minimum_param_count != param_count) {
  5953. if (param_count < ordered_operands.count) {
  5954. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  5955. err = CallArgumentError_TooManyArguments;
  5956. } else if (minimum_param_count > ordered_operands.count) {
  5957. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  5958. err = CallArgumentError_TooFewArguments;
  5959. }
  5960. } else {
  5961. if (param_count < ordered_operands.count) {
  5962. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5963. err = CallArgumentError_TooManyArguments;
  5964. } else if (param_count > ordered_operands.count) {
  5965. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5966. err = CallArgumentError_TooFewArguments;
  5967. }
  5968. }
  5969. if (err != 0) {
  5970. return err;
  5971. }
  5972. if (minimum_param_count != param_count) {
  5973. array_resize(&ordered_operands, param_count);
  5974. isize missing_count = 0;
  5975. // NOTE(bill): Replace missing operands with the default values (if possible)
  5976. for_array(i, ordered_operands) {
  5977. Operand *o = &ordered_operands[i];
  5978. if (o->expr == nullptr) {
  5979. Entity *e = tuple->variables[i];
  5980. if (e->kind == Entity_Constant) {
  5981. missing_count += 1;
  5982. o->mode = Addressing_Constant;
  5983. o->type = default_type(e->type);
  5984. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  5985. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  5986. o->value = e->Constant.param_value.value;
  5987. }
  5988. } else if (e->kind == Entity_TypeName) {
  5989. missing_count += 1;
  5990. o->mode = Addressing_Type;
  5991. o->type = e->type;
  5992. o->expr = e->identifier;
  5993. }
  5994. }
  5995. }
  5996. }
  5997. isize oo_count = gb_min(param_count, ordered_operands.count);
  5998. i64 score = 0;
  5999. for (isize i = 0; i < oo_count; i++) {
  6000. Entity *e = tuple->variables[i];
  6001. Operand *o = &ordered_operands[i];
  6002. if (o->mode == Addressing_Invalid) {
  6003. continue;
  6004. }
  6005. if (e->kind == Entity_TypeName) {
  6006. if (o->mode != Addressing_Type) {
  6007. if (show_error) {
  6008. gbString expr = expr_to_string(o->expr);
  6009. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6010. gb_string_free(expr);
  6011. }
  6012. err = CallArgumentError_WrongTypes;
  6013. }
  6014. if (are_types_identical(e->type, o->type)) {
  6015. score += assign_score_function(1);
  6016. } else {
  6017. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6018. }
  6019. } else {
  6020. i64 s = 0;
  6021. if (o->type->kind == Type_Generic) {
  6022. // Polymorphic name!
  6023. score += assign_score_function(1);
  6024. continue;
  6025. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6026. if (show_error) {
  6027. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6028. }
  6029. err = CallArgumentError_WrongTypes;
  6030. }
  6031. o->type = e->type;
  6032. if (o->mode != Addressing_Constant) {
  6033. bool valid = false;
  6034. if (is_type_proc(o->type)) {
  6035. Entity *proc_entity = entity_from_expr(o->expr);
  6036. valid = proc_entity != nullptr;
  6037. }
  6038. if (!valid) {
  6039. if (show_error) {
  6040. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6041. }
  6042. err = CallArgumentError_NoneConstantParameter;
  6043. }
  6044. }
  6045. score += s;
  6046. }
  6047. // NOTE(bill): Add type info the parameters
  6048. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6049. // add_type_info_type(c, o->type);
  6050. }
  6051. if (show_error && err) {
  6052. return err;
  6053. }
  6054. {
  6055. bool failure = false;
  6056. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  6057. if (found_entity) {
  6058. operand->mode = Addressing_Type;
  6059. operand->type = found_entity->type;
  6060. return err;
  6061. }
  6062. CheckerContext ctx = *c;
  6063. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6064. ctx.scope = polymorphic_record_parent_scope(original_type);
  6065. GB_ASSERT(ctx.scope != nullptr);
  6066. Type *bt = base_type(original_type);
  6067. String generated_name = make_string_c(expr_to_string(call));
  6068. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6069. if (bt->kind == Type_Struct) {
  6070. Ast *node = clone_ast(bt->Struct.node);
  6071. Type *struct_type = alloc_type_struct();
  6072. struct_type->Struct.node = node;
  6073. struct_type->Struct.polymorphic_parent = original_type;
  6074. set_base_type(named_type, struct_type);
  6075. check_open_scope(&ctx, node);
  6076. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6077. check_close_scope(&ctx);
  6078. } else if (bt->kind == Type_Union) {
  6079. Ast *node = clone_ast(bt->Union.node);
  6080. Type *union_type = alloc_type_union();
  6081. union_type->Union.node = node;
  6082. union_type->Union.polymorphic_parent = original_type;
  6083. set_base_type(named_type, union_type);
  6084. check_open_scope(&ctx, node);
  6085. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6086. check_close_scope(&ctx);
  6087. } else {
  6088. GB_PANIC("Unsupported parametric polymorphic record type");
  6089. }
  6090. bt = base_type(named_type);
  6091. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6092. GB_ASSERT(original_type->kind == Type_Named);
  6093. Entity *e = original_type->Named.type_name;
  6094. GB_ASSERT(e->kind == Entity_TypeName);
  6095. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6096. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6097. Type *params = nullptr;
  6098. switch (bt->kind) {
  6099. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6100. case Type_Union: params = bt->Union.polymorphic_params; break;
  6101. }
  6102. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6103. Entity *v = params->Tuple.variables[i];
  6104. String name = v->token.string;
  6105. if (i > 0) {
  6106. s = gb_string_append_fmt(s, ", ");
  6107. }
  6108. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6109. if (v->kind == Entity_TypeName) {
  6110. if (v->type->kind != Type_Generic) {
  6111. s = gb_string_append_fmt(s, "=");
  6112. s = write_type_to_string(s, v->type, false);
  6113. }
  6114. } else if (v->kind == Entity_Constant) {
  6115. s = gb_string_append_fmt(s, "=");
  6116. s = write_exact_value_to_string(s, v->Constant.value);
  6117. }
  6118. }
  6119. s = gb_string_append_fmt(s, ")");
  6120. String new_name = make_string_c(s);
  6121. named_type->Named.name = new_name;
  6122. if (named_type->Named.type_name) {
  6123. named_type->Named.type_name->token.string = new_name;
  6124. }
  6125. }
  6126. operand->mode = Addressing_Type;
  6127. operand->type = named_type;
  6128. }
  6129. return err;
  6130. }
  6131. // returns true on success
  6132. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6133. bool success = true;
  6134. if (args.count > 0) {
  6135. if (allow_mixed) {
  6136. bool was_named = false;
  6137. for (Ast *arg : args) {
  6138. if (was_named && arg->kind != Ast_FieldValue) {
  6139. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6140. success = false;
  6141. break;
  6142. }
  6143. was_named = was_named || arg->kind == Ast_FieldValue;
  6144. }
  6145. } else {
  6146. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6147. for (Ast *arg : args) {
  6148. bool mix = false;
  6149. if (first_is_field_value) {
  6150. mix = arg->kind != Ast_FieldValue;
  6151. } else {
  6152. mix = arg->kind == Ast_FieldValue;
  6153. }
  6154. if (mix) {
  6155. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6156. success = false;
  6157. }
  6158. }
  6159. }
  6160. }
  6161. return success;
  6162. }
  6163. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6164. operand->mode = Addressing_Invalid; \
  6165. operand->expr = call; \
  6166. return Expr_Stmt; \
  6167. }
  6168. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6169. if (proc != nullptr &&
  6170. proc->kind == Ast_BasicDirective) {
  6171. ast_node(bd, BasicDirective, proc);
  6172. String name = bd->name.string;
  6173. if (
  6174. name == "location" ||
  6175. name == "assert" ||
  6176. name == "panic" ||
  6177. name == "defined" ||
  6178. name == "config" ||
  6179. name == "load" ||
  6180. name == "load_hash" ||
  6181. name == "load_or"
  6182. ) {
  6183. operand->mode = Addressing_Builtin;
  6184. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6185. operand->expr = proc;
  6186. operand->type = t_invalid;
  6187. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6188. } else {
  6189. error(proc, "Unknown directive: #%.*s", LIT(name));
  6190. operand->expr = proc;
  6191. operand->type = t_invalid;
  6192. operand->mode = Addressing_Invalid;
  6193. return Expr_Expr;
  6194. }
  6195. if (inlining != ProcInlining_none) {
  6196. error(call, "Inlining operators are not allowed on built-in procedures");
  6197. }
  6198. } else {
  6199. if (proc != nullptr) {
  6200. check_expr_or_type(c, operand, proc);
  6201. } else {
  6202. GB_ASSERT(operand->expr != nullptr);
  6203. }
  6204. }
  6205. if (operand->mode == Addressing_Invalid) {
  6206. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6207. for (Ast *arg : args) {
  6208. if (arg->kind == Ast_FieldValue) {
  6209. arg = arg->FieldValue.value;
  6210. }
  6211. check_expr_base(c, operand, arg, nullptr);
  6212. }
  6213. operand->mode = Addressing_Invalid;
  6214. operand->expr = call;
  6215. return Expr_Stmt;
  6216. }
  6217. if (operand->mode == Addressing_Type) {
  6218. Type *t = operand->type;
  6219. if (is_type_polymorphic_record(t)) {
  6220. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6221. if (!is_type_named(t)) {
  6222. gbString s = expr_to_string(operand->expr);
  6223. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6224. gb_string_free(s);
  6225. operand->mode = Addressing_Invalid;
  6226. operand->type = t_invalid;;
  6227. return Expr_Expr;
  6228. }
  6229. auto err = check_polymorphic_record_type(c, operand, call);
  6230. if (err == 0) {
  6231. Ast *ident = operand->expr;
  6232. while (ident->kind == Ast_SelectorExpr) {
  6233. Ast *s = ident->SelectorExpr.selector;
  6234. ident = s;
  6235. }
  6236. Type *ot = operand->type;
  6237. GB_ASSERT(ot->kind == Type_Named);
  6238. Entity *e = ot->Named.type_name;
  6239. add_entity_use(c, ident, e);
  6240. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6241. } else {
  6242. operand->mode = Addressing_Invalid;
  6243. operand->type = t_invalid;
  6244. }
  6245. } else {
  6246. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6247. operand->mode = Addressing_Invalid;
  6248. isize arg_count = args.count;
  6249. switch (arg_count) {
  6250. case 0:
  6251. {
  6252. gbString str = type_to_string(t);
  6253. error(call, "Missing argument in conversion to '%s'", str);
  6254. gb_string_free(str);
  6255. } break;
  6256. default:
  6257. {
  6258. gbString str = type_to_string(t);
  6259. error(call, "Too many arguments in conversion to '%s'", str);
  6260. gb_string_free(str);
  6261. } break;
  6262. case 1: {
  6263. Ast *arg = args[0];
  6264. if (arg->kind == Ast_FieldValue) {
  6265. error(call, "'field = value' cannot be used in a type conversion");
  6266. arg = arg->FieldValue.value;
  6267. // NOTE(bill): Carry on the cast regardless
  6268. }
  6269. check_expr_with_type_hint(c, operand, arg, t);
  6270. if (operand->mode != Addressing_Invalid) {
  6271. if (is_type_polymorphic(t)) {
  6272. error(call, "A polymorphic type cannot be used in a type conversion");
  6273. } else {
  6274. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6275. // as it assumes it is determining the type
  6276. check_cast(c, operand, t);
  6277. }
  6278. }
  6279. operand->type = t;
  6280. operand->expr = call;
  6281. if (operand->mode != Addressing_Invalid) {
  6282. update_untyped_expr_type(c, arg, t, false);
  6283. }
  6284. break;
  6285. }
  6286. }
  6287. }
  6288. return Expr_Expr;
  6289. }
  6290. if (operand->mode == Addressing_Builtin) {
  6291. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6292. i32 id = operand->builtin_id;
  6293. Entity *e = entity_of_node(operand->expr);
  6294. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6295. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6296. }
  6297. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6298. operand->mode = Addressing_Invalid;
  6299. operand->type = t_invalid;
  6300. }
  6301. operand->expr = call;
  6302. return builtin_procs[id].kind;
  6303. }
  6304. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6305. Entity *initial_entity = entity_of_node(operand->expr);
  6306. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6307. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6308. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6309. if (c->decl) {
  6310. c->decl->defer_used += 1;
  6311. }
  6312. }
  6313. add_entity_use(c, operand->expr, initial_entity);
  6314. }
  6315. if (operand->mode != Addressing_ProcGroup) {
  6316. Type *proc_type = base_type(operand->type);
  6317. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6318. bool valid_mode = is_operand_value(*operand);
  6319. if (!valid_type || !valid_mode) {
  6320. Ast *e = operand->expr;
  6321. gbString str = expr_to_string(e);
  6322. gbString type_str = type_to_string(operand->type);
  6323. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6324. gb_string_free(type_str);
  6325. gb_string_free(str);
  6326. operand->mode = Addressing_Invalid;
  6327. operand->expr = call;
  6328. return Expr_Stmt;
  6329. }
  6330. }
  6331. CallArgumentData data = check_call_arguments(c, operand, call);
  6332. Type *result_type = data.result_type;
  6333. gb_zero_item(operand);
  6334. operand->expr = call;
  6335. if (result_type == t_invalid) {
  6336. operand->mode = Addressing_Invalid;
  6337. operand->type = t_invalid;
  6338. return Expr_Stmt;
  6339. }
  6340. Type *pt = base_type(operand->type);
  6341. if (pt == nullptr) {
  6342. pt = t_invalid;
  6343. }
  6344. if (pt == t_invalid) {
  6345. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6346. pt = type_of_expr(operand->expr->CallExpr.proc);
  6347. }
  6348. if (pt == t_invalid && data.gen_entity) {
  6349. pt = data.gen_entity->type;
  6350. }
  6351. }
  6352. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6353. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6354. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6355. }
  6356. }
  6357. if (result_type == nullptr) {
  6358. operand->mode = Addressing_NoValue;
  6359. } else {
  6360. GB_ASSERT(is_type_tuple(result_type));
  6361. isize count = result_type->Tuple.variables.count;
  6362. switch (count) {
  6363. case 0:
  6364. operand->mode = Addressing_NoValue;
  6365. break;
  6366. case 1:
  6367. operand->mode = Addressing_Value;
  6368. operand->type = result_type->Tuple.variables[0]->type;
  6369. break;
  6370. default:
  6371. operand->mode = Addressing_Value;
  6372. operand->type = result_type;
  6373. break;
  6374. }
  6375. }
  6376. switch (inlining) {
  6377. case ProcInlining_inline:
  6378. if (proc != nullptr) {
  6379. Entity *e = entity_from_expr(proc);
  6380. if (e != nullptr && e->kind == Entity_Procedure) {
  6381. DeclInfo *decl = e->decl_info;
  6382. if (decl->proc_lit) {
  6383. ast_node(pl, ProcLit, decl->proc_lit);
  6384. if (pl->inlining == ProcInlining_no_inline) {
  6385. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6386. }
  6387. }
  6388. }
  6389. }
  6390. break;
  6391. case ProcInlining_no_inline:
  6392. break;
  6393. }
  6394. operand->expr = call;
  6395. {
  6396. Type *type = nullptr;
  6397. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6398. type = type_of_expr(operand->expr->CallExpr.proc);
  6399. }
  6400. if (type == nullptr) {
  6401. type = pt;
  6402. }
  6403. type = base_type(type);
  6404. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6405. operand->mode = Addressing_OptionalOk;
  6406. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6407. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6408. operand->expr->CallExpr.optional_ok_one = true;
  6409. }
  6410. }
  6411. }
  6412. return Expr_Expr;
  6413. }
  6414. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6415. check_expr_base(c, o, e, t);
  6416. check_not_tuple(c, o);
  6417. char const *err_str = nullptr;
  6418. switch (o->mode) {
  6419. case Addressing_NoValue:
  6420. err_str = "used as a value";
  6421. break;
  6422. case Addressing_Type:
  6423. if (t == nullptr || !is_type_typeid(t)) {
  6424. err_str = "is not an expression but a type, in this context it is ambiguous";
  6425. }
  6426. break;
  6427. case Addressing_Builtin:
  6428. err_str = "must be called";
  6429. break;
  6430. }
  6431. if (err_str != nullptr) {
  6432. gbString str = expr_to_string(e);
  6433. error(e, "'%s' %s", str, err_str);
  6434. gb_string_free(str);
  6435. o->mode = Addressing_Invalid;
  6436. }
  6437. }
  6438. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6439. switch (t->kind) {
  6440. case Type_Basic:
  6441. if (t->Basic.kind == Basic_string) {
  6442. if (o->mode == Addressing_Constant) {
  6443. *max_count = o->value.value_string.len;
  6444. }
  6445. if (o->mode != Addressing_Constant) {
  6446. o->mode = Addressing_Value;
  6447. }
  6448. o->type = t_u8;
  6449. return true;
  6450. } else if (t->Basic.kind == Basic_UntypedString) {
  6451. if (o->mode == Addressing_Constant) {
  6452. *max_count = o->value.value_string.len;
  6453. o->type = t_u8;
  6454. return true;
  6455. }
  6456. return false;
  6457. }
  6458. break;
  6459. case Type_MultiPointer:
  6460. o->type = t->MultiPointer.elem;
  6461. if (o->mode != Addressing_Constant) {
  6462. o->mode = Addressing_Variable;
  6463. }
  6464. return true;
  6465. case Type_Array:
  6466. *max_count = t->Array.count;
  6467. if (indirection) {
  6468. o->mode = Addressing_Variable;
  6469. } else if (o->mode != Addressing_Variable &&
  6470. o->mode != Addressing_Constant) {
  6471. o->mode = Addressing_Value;
  6472. }
  6473. o->type = t->Array.elem;
  6474. return true;
  6475. case Type_EnumeratedArray:
  6476. *max_count = t->EnumeratedArray.count;
  6477. if (indirection) {
  6478. o->mode = Addressing_Variable;
  6479. } else if (o->mode != Addressing_Variable &&
  6480. o->mode != Addressing_Constant) {
  6481. o->mode = Addressing_Value;
  6482. }
  6483. o->type = t->EnumeratedArray.elem;
  6484. return true;
  6485. case Type_Matrix:
  6486. *max_count = t->Matrix.column_count;
  6487. if (indirection) {
  6488. o->mode = Addressing_Variable;
  6489. } else if (o->mode != Addressing_Variable) {
  6490. o->mode = Addressing_Value;
  6491. }
  6492. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6493. return true;
  6494. case Type_Slice:
  6495. o->type = t->Slice.elem;
  6496. if (o->mode != Addressing_Constant) {
  6497. o->mode = Addressing_Variable;
  6498. }
  6499. return true;
  6500. case Type_RelativeMultiPointer:
  6501. {
  6502. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6503. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6504. o->type = pointer_type->MultiPointer.elem;
  6505. if (o->mode != Addressing_Constant) {
  6506. o->mode = Addressing_Variable;
  6507. }
  6508. }
  6509. return true;
  6510. case Type_DynamicArray:
  6511. o->type = t->DynamicArray.elem;
  6512. if (o->mode != Addressing_Constant) {
  6513. o->mode = Addressing_Variable;
  6514. }
  6515. return true;
  6516. case Type_Struct:
  6517. if (t->Struct.soa_kind != StructSoa_None) {
  6518. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6519. *max_count = t->Struct.soa_count;
  6520. }
  6521. o->type = t->Struct.soa_elem;
  6522. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  6523. o->mode = Addressing_SoaVariable;
  6524. } else {
  6525. o->mode = Addressing_Value;
  6526. }
  6527. return true;
  6528. }
  6529. return false;
  6530. }
  6531. if (is_type_pointer(original_type) && indirection) {
  6532. Type *ptr = base_type(original_type);
  6533. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6534. o->type = ptr->Pointer.elem;
  6535. o->mode = Addressing_Value;
  6536. return true;
  6537. }
  6538. }
  6539. return false;
  6540. }
  6541. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6542. if (is_type_untyped_uninit(x)) {
  6543. return true;
  6544. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6545. return true;
  6546. } else if (is_type_untyped_uninit(y)) {
  6547. return true;
  6548. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6549. return true;
  6550. }
  6551. return are_types_identical(x, y);
  6552. }
  6553. 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) {
  6554. if (!is_ast_range(node)) {
  6555. return false;
  6556. }
  6557. ast_node(ie, BinaryExpr, node);
  6558. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6559. if (x->mode == Addressing_Invalid) {
  6560. return false;
  6561. }
  6562. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6563. if (y->mode == Addressing_Invalid) {
  6564. return false;
  6565. }
  6566. convert_to_typed(c, x, y->type);
  6567. if (x->mode == Addressing_Invalid) {
  6568. return false;
  6569. }
  6570. convert_to_typed(c, y, x->type);
  6571. if (y->mode == Addressing_Invalid) {
  6572. return false;
  6573. }
  6574. convert_to_typed(c, x, default_type(y->type));
  6575. if (x->mode == Addressing_Invalid) {
  6576. return false;
  6577. }
  6578. convert_to_typed(c, y, default_type(x->type));
  6579. if (y->mode == Addressing_Invalid) {
  6580. return false;
  6581. }
  6582. if (!are_types_identical(x->type, y->type)) {
  6583. if (x->type != t_invalid &&
  6584. y->type != t_invalid) {
  6585. gbString xt = type_to_string(x->type);
  6586. gbString yt = type_to_string(y->type);
  6587. gbString expr_str = expr_to_string(x->expr);
  6588. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6589. gb_string_free(expr_str);
  6590. gb_string_free(yt);
  6591. gb_string_free(xt);
  6592. }
  6593. return false;
  6594. }
  6595. Type *type = x->type;
  6596. if (is_for_loop) {
  6597. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6598. error(ie->op, "Only numerical types are allowed within interval expressions");
  6599. return false;
  6600. }
  6601. } else {
  6602. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6603. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6604. return false;
  6605. }
  6606. }
  6607. if (x->mode == Addressing_Constant &&
  6608. y->mode == Addressing_Constant) {
  6609. ExactValue a = x->value;
  6610. ExactValue b = y->value;
  6611. GB_ASSERT(are_types_identical(x->type, y->type));
  6612. TokenKind op = Token_Lt;
  6613. switch (ie->op.kind) {
  6614. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6615. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6616. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6617. default: error(ie->op, "Invalid range operator"); break;
  6618. }
  6619. bool ok = compare_exact_values(op, a, b);
  6620. if (!ok) {
  6621. // TODO(bill): Better error message
  6622. error(ie->op, "Invalid interval range");
  6623. return false;
  6624. }
  6625. ExactValue inline_for_depth = exact_value_sub(b, a);
  6626. if (ie->op.kind != Token_RangeHalf) {
  6627. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6628. }
  6629. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6630. } else if (inline_for_depth_ != nullptr) {
  6631. error(ie->op, "Interval expressions must be constant");
  6632. return false;
  6633. }
  6634. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6635. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6636. return true;
  6637. }
  6638. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6639. if (is_operand_nil(*o)) {
  6640. return true;
  6641. }
  6642. Ast *expr = unparen_expr(o->expr);
  6643. if (expr != nullptr) {
  6644. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6645. if (e != nullptr && e->kind == Entity_Procedure) {
  6646. return true;
  6647. }
  6648. if (expr->kind == Ast_ProcLit) {
  6649. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6650. return true;
  6651. }
  6652. }
  6653. return o->mode == Addressing_Constant;
  6654. }
  6655. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6656. if (is_type_enum(th)) {
  6657. Type *enum_type = base_type(th);
  6658. GB_ASSERT(enum_type->kind == Type_Enum);
  6659. String name = ise->selector->Ident.token.string;
  6660. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6661. if (e == nullptr) {
  6662. return false;
  6663. }
  6664. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6665. GB_ASSERT(e->kind == Entity_Constant);
  6666. o->value = e->Constant.value;
  6667. o->mode = Addressing_Constant;
  6668. o->type = e->type;
  6669. return true;
  6670. }
  6671. if (is_type_union(th)) {
  6672. TEMPORARY_ALLOCATOR_GUARD();
  6673. Type *union_type = base_type(th);
  6674. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6675. for (Type *vt : union_type->Union.variants) {
  6676. Operand x = {};
  6677. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6678. array_add(&operands, x);
  6679. }
  6680. }
  6681. if (operands.count == 1) {
  6682. *o = operands[0];
  6683. return true;
  6684. }
  6685. }
  6686. return false;
  6687. }
  6688. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6689. ast_node(ise, ImplicitSelectorExpr, node);
  6690. o->type = t_invalid;
  6691. o->expr = node;
  6692. o->mode = Addressing_Invalid;
  6693. Type *th = type_hint;
  6694. if (th == nullptr) {
  6695. gbString str = expr_to_string(node);
  6696. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6697. gb_string_free(str);
  6698. return Expr_Expr;
  6699. }
  6700. o->type = th;
  6701. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6702. if (!ok) {
  6703. String name = ise->selector->Ident.token.string;
  6704. if (is_type_enum(th)) {
  6705. Type *bt = base_type(th);
  6706. GB_ASSERT(bt->kind == Type_Enum);
  6707. gbString typ = type_to_string(th);
  6708. defer (gb_string_free(typ));
  6709. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6710. check_did_you_mean_type(name, bt->Enum.fields);
  6711. } else {
  6712. gbString typ = type_to_string(th);
  6713. gbString str = expr_to_string(node);
  6714. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6715. gb_string_free(str);
  6716. gb_string_free(typ);
  6717. }
  6718. }
  6719. o->expr = node;
  6720. return Expr_Expr;
  6721. }
  6722. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  6723. switch (x->mode) {
  6724. case Addressing_MapIndex:
  6725. case Addressing_OptionalOk:
  6726. case Addressing_OptionalOkPtr:
  6727. if (val_type_) *val_type_ = x->type;
  6728. break;
  6729. default:
  6730. if (ok_type_) *ok_type_ = x->type;
  6731. return;
  6732. }
  6733. Ast *expr = unparen_expr(x->expr);
  6734. if (expr->kind == Ast_CallExpr) {
  6735. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6736. if (is_type_proc(pt)) {
  6737. Type *tuple = pt->Proc.results;
  6738. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6739. if (pt->Proc.result_count >= 2) {
  6740. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6741. }
  6742. expr->CallExpr.optional_ok_one = false;
  6743. x->type = tuple;
  6744. return;
  6745. }
  6746. }
  6747. Type *tuple = make_optional_ok_type(x->type);
  6748. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6749. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6750. x->type = tuple;
  6751. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6752. }
  6753. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6754. ast_node(ie, MatrixIndexExpr, node);
  6755. check_expr(c, o, ie->expr);
  6756. node->viral_state_flags |= ie->expr->viral_state_flags;
  6757. if (o->mode == Addressing_Invalid) {
  6758. o->expr = node;
  6759. return;
  6760. }
  6761. Type *t = base_type(type_deref(o->type));
  6762. bool is_ptr = is_type_pointer(o->type);
  6763. bool is_const = o->mode == Addressing_Constant;
  6764. if (t->kind != Type_Matrix) {
  6765. gbString str = expr_to_string(o->expr);
  6766. gbString type_str = type_to_string(o->type);
  6767. defer (gb_string_free(str));
  6768. defer (gb_string_free(type_str));
  6769. if (is_const) {
  6770. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6771. } else {
  6772. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6773. }
  6774. o->mode = Addressing_Invalid;
  6775. o->expr = node;
  6776. return;
  6777. }
  6778. o->type = t->Matrix.elem;
  6779. if (is_ptr) {
  6780. o->mode = Addressing_Variable;
  6781. } else if (o->mode != Addressing_Variable) {
  6782. o->mode = Addressing_Value;
  6783. }
  6784. if (ie->row_index == nullptr) {
  6785. gbString str = expr_to_string(o->expr);
  6786. error(o->expr, "Missing row index for '%s'", str);
  6787. gb_string_free(str);
  6788. o->mode = Addressing_Invalid;
  6789. o->expr = node;
  6790. return;
  6791. }
  6792. if (ie->column_index == nullptr) {
  6793. gbString str = expr_to_string(o->expr);
  6794. error(o->expr, "Missing column index for '%s'", str);
  6795. gb_string_free(str);
  6796. o->mode = Addressing_Invalid;
  6797. o->expr = node;
  6798. return;
  6799. }
  6800. i64 row_count = t->Matrix.row_count;
  6801. i64 column_count = t->Matrix.column_count;
  6802. i64 row_index = 0;
  6803. i64 column_index = 0;
  6804. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6805. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6806. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  6807. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  6808. }
  6809. gb_unused(row_ok);
  6810. gb_unused(column_ok);
  6811. }
  6812. struct TypeAndToken {
  6813. Type *type;
  6814. Token token;
  6815. };
  6816. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  6817. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  6818. if (operand.mode != Addressing_Constant) {
  6819. return;
  6820. }
  6821. if (operand.value.kind == ExactValue_Invalid) {
  6822. return;
  6823. }
  6824. uintptr key = hash_exact_value(operand.value);
  6825. TypeAndToken *found = map_get(seen, key);
  6826. if (found != nullptr) {
  6827. TEMPORARY_ALLOCATOR_GUARD();
  6828. isize count = multi_map_count(seen, key);
  6829. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  6830. multi_map_get_all(seen, key, taps);
  6831. for (isize i = 0; i < count; i++) {
  6832. TypeAndToken tap = taps[i];
  6833. Operand to = {};
  6834. to.mode = Addressing_Value;
  6835. to.type = tap.type;
  6836. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  6837. continue;
  6838. }
  6839. TokenPos pos = tap.token.pos;
  6840. if (use_expr) {
  6841. gbString expr_str = expr_to_string(operand.expr);
  6842. error(operand.expr,
  6843. "Duplicate case '%s'\n"
  6844. "\tprevious case at %s",
  6845. expr_str,
  6846. token_pos_to_string(pos));
  6847. gb_string_free(expr_str);
  6848. } else {
  6849. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  6850. }
  6851. return;
  6852. }
  6853. }
  6854. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  6855. multi_map_insert(seen, key, tap);
  6856. }
  6857. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  6858. if (is_type_enum(x.type)) {
  6859. // TODO(bill): Fix this logic so it's fast!!!
  6860. i64 v0 = exact_value_to_i64(lhs.value);
  6861. i64 v1 = exact_value_to_i64(rhs.value);
  6862. Operand v = {};
  6863. v.mode = Addressing_Constant;
  6864. v.type = x.type;
  6865. v.expr = x.expr;
  6866. Type *bt = base_type(x.type);
  6867. GB_ASSERT(bt->kind == Type_Enum);
  6868. for (i64 vi = v0; vi <= v1; vi++) {
  6869. if (upper_op != Token_LtEq && vi == v1) {
  6870. break;
  6871. }
  6872. v.value = exact_value_i64(vi);
  6873. add_constant_switch_case(ctx, seen, v);
  6874. }
  6875. } else {
  6876. add_constant_switch_case(ctx, seen, lhs);
  6877. if (upper_op == Token_LtEq) {
  6878. add_constant_switch_case(ctx, seen, rhs);
  6879. }
  6880. }
  6881. }
  6882. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  6883. add_constant_switch_case(ctx, seen, x);
  6884. }
  6885. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6886. ast_node(bd, BasicDirective, node);
  6887. ExprKind kind = Expr_Expr;
  6888. o->mode = Addressing_Constant;
  6889. String name = bd->name.string;
  6890. if (name == "file") {
  6891. o->type = t_untyped_string;
  6892. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6893. } else if (name == "line") {
  6894. o->type = t_untyped_integer;
  6895. o->value = exact_value_i64(bd->token.pos.line);
  6896. } else if (name == "procedure") {
  6897. if (c->curr_proc_decl == nullptr) {
  6898. error(node, "#procedure may only be used within procedures");
  6899. o->type = t_untyped_string;
  6900. o->value = exact_value_string(str_lit(""));
  6901. } else {
  6902. o->type = t_untyped_string;
  6903. o->value = exact_value_string(c->proc_name);
  6904. }
  6905. } else if (name == "caller_location") {
  6906. init_core_source_code_location(c->checker);
  6907. error(node, "#caller_location may only be used as a default argument parameter");
  6908. o->type = t_source_code_location;
  6909. o->mode = Addressing_Value;
  6910. } else {
  6911. if (name == "location") {
  6912. init_core_source_code_location(c->checker);
  6913. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  6914. o->type = t_source_code_location;
  6915. o->mode = Addressing_Value;
  6916. } else if (
  6917. name == "assert" ||
  6918. name == "defined" ||
  6919. name == "config" ||
  6920. name == "load" ||
  6921. name == "load_hash" ||
  6922. name == "load_or"
  6923. ) {
  6924. error(node, "'#%.*s' must be used as a call", LIT(name));
  6925. o->type = t_invalid;
  6926. o->mode = Addressing_Invalid;
  6927. } else {
  6928. error(node, "Unknown directive: #%.*s", LIT(name));
  6929. o->type = t_invalid;
  6930. o->mode = Addressing_Invalid;
  6931. }
  6932. }
  6933. return kind;
  6934. }
  6935. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6936. ExprKind kind = Expr_Expr;
  6937. Operand cond = {Addressing_Invalid};
  6938. ast_node(te, TernaryIfExpr, node);
  6939. check_expr(c, &cond, te->cond);
  6940. node->viral_state_flags |= te->cond->viral_state_flags;
  6941. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6942. error(te->cond, "Non-boolean condition in ternary if expression");
  6943. }
  6944. Operand x = {Addressing_Invalid};
  6945. Operand y = {Addressing_Invalid};
  6946. check_expr_or_type(c, &x, te->x, type_hint);
  6947. node->viral_state_flags |= te->x->viral_state_flags;
  6948. if (te->y != nullptr) {
  6949. Type *th = type_hint;
  6950. if (type_hint == nullptr && is_type_typed(x.type)) {
  6951. th = x.type;
  6952. }
  6953. check_expr_or_type(c, &y, te->y, th);
  6954. node->viral_state_flags |= te->y->viral_state_flags;
  6955. } else {
  6956. error(node, "A ternary expression must have an else clause");
  6957. return kind;
  6958. }
  6959. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  6960. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  6961. gbString type_string = expr_to_string(type_expr);
  6962. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  6963. gb_string_free(type_string);
  6964. return kind;
  6965. }
  6966. if (x.type == nullptr || x.type == t_invalid ||
  6967. y.type == nullptr || y.type == t_invalid) {
  6968. return kind;
  6969. }
  6970. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  6971. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  6972. if (x.mode == Addressing_Invalid) {
  6973. return kind;
  6974. }
  6975. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  6976. if (y.mode == Addressing_Invalid) {
  6977. x.mode = Addressing_Invalid;
  6978. return kind;
  6979. }
  6980. // NOTE(bill, 2023-01-30): Allow for expression like this:
  6981. // x: union{f32} = f32(123) if cond else nil
  6982. if (type_hint && !is_type_any(type_hint)) {
  6983. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  6984. check_cast(c, &x, type_hint);
  6985. check_cast(c, &y, type_hint);
  6986. }
  6987. }
  6988. if (!ternary_compare_types(x.type, y.type)) {
  6989. gbString its = type_to_string(x.type);
  6990. gbString ets = type_to_string(y.type);
  6991. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  6992. gb_string_free(ets);
  6993. gb_string_free(its);
  6994. return kind;
  6995. }
  6996. o->type = x.type;
  6997. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  6998. o->type = y.type;
  6999. }
  7000. o->mode = Addressing_Value;
  7001. o->expr = node;
  7002. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7003. if (check_cast_internal(c, &x, type_hint) &&
  7004. check_cast_internal(c, &y, type_hint)) {
  7005. convert_to_typed(c, o, type_hint);
  7006. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7007. o->type = type_hint;
  7008. }
  7009. }
  7010. return kind;
  7011. }
  7012. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7013. ExprKind kind = Expr_Expr;
  7014. Operand cond = {};
  7015. ast_node(te, TernaryWhenExpr, node);
  7016. check_expr(c, &cond, te->cond);
  7017. node->viral_state_flags |= te->cond->viral_state_flags;
  7018. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7019. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7020. return kind;
  7021. }
  7022. if (cond.value.value_bool) {
  7023. check_expr_or_type(c, o, te->x, type_hint);
  7024. node->viral_state_flags |= te->x->viral_state_flags;
  7025. } else {
  7026. if (te->y != nullptr) {
  7027. check_expr_or_type(c, o, te->y, type_hint);
  7028. node->viral_state_flags |= te->y->viral_state_flags;
  7029. } else {
  7030. error(node, "A ternary when expression must have an else clause");
  7031. return kind;
  7032. }
  7033. }
  7034. return kind;
  7035. }
  7036. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7037. ast_node(oe, OrElseExpr, node);
  7038. String name = oe->token.string;
  7039. Ast *arg = oe->x;
  7040. Ast *default_value = oe->y;
  7041. Operand x = {};
  7042. Operand y = {};
  7043. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7044. if (is_load_directive_call(arg)) {
  7045. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7046. // Allow for chaining of '#load(path) or_else #load(path)'
  7047. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7048. bool y_is_diverging = false;
  7049. check_expr_base(c, &y, default_value, x.type);
  7050. switch (y.mode) {
  7051. case Addressing_NoValue:
  7052. if (is_diverging_expr(y.expr)) {
  7053. // Allow
  7054. y.mode = Addressing_Value;
  7055. y_is_diverging = true;
  7056. } else {
  7057. error_operand_no_value(&y);
  7058. y.mode = Addressing_Invalid;
  7059. }
  7060. break;
  7061. case Addressing_Type:
  7062. error_operand_not_expression(&y);
  7063. y.mode = Addressing_Invalid;
  7064. break;
  7065. }
  7066. if (y.mode == Addressing_Invalid) {
  7067. o->mode = Addressing_Value;
  7068. o->type = t_invalid;
  7069. o->expr = node;
  7070. return Expr_Expr;
  7071. }
  7072. if (!y_is_diverging) {
  7073. check_assignment(c, &y, x.type, name);
  7074. if (y.mode != Addressing_Constant) {
  7075. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7076. }
  7077. }
  7078. }
  7079. if (res == LoadDirective_Success) {
  7080. *o = x;
  7081. } else {
  7082. *o = y;
  7083. }
  7084. o->expr = node;
  7085. return Expr_Expr;
  7086. }
  7087. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7088. if (x.mode == Addressing_Invalid) {
  7089. o->mode = Addressing_Value;
  7090. o->type = t_invalid;
  7091. o->expr = node;
  7092. return Expr_Expr;
  7093. }
  7094. bool y_is_diverging = false;
  7095. check_expr_base(c, &y, default_value, x.type);
  7096. switch (y.mode) {
  7097. case Addressing_NoValue:
  7098. if (is_diverging_expr(y.expr)) {
  7099. // Allow
  7100. y.mode = Addressing_Value;
  7101. y_is_diverging = true;
  7102. } else {
  7103. error_operand_no_value(&y);
  7104. y.mode = Addressing_Invalid;
  7105. }
  7106. break;
  7107. case Addressing_Type:
  7108. error_operand_not_expression(&y);
  7109. y.mode = Addressing_Invalid;
  7110. break;
  7111. }
  7112. if (y.mode == Addressing_Invalid) {
  7113. o->mode = Addressing_Value;
  7114. o->type = t_invalid;
  7115. o->expr = node;
  7116. return Expr_Expr;
  7117. }
  7118. Type *left_type = nullptr;
  7119. Type *right_type = nullptr;
  7120. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7121. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7122. if (left_type != nullptr) {
  7123. if (!y_is_diverging) {
  7124. check_assignment(c, &y, left_type, name);
  7125. }
  7126. } else {
  7127. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7128. }
  7129. if (left_type == nullptr) {
  7130. left_type = t_invalid;
  7131. }
  7132. o->mode = Addressing_Value;
  7133. o->type = left_type;
  7134. o->expr = node;
  7135. return Expr_Expr;
  7136. }
  7137. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7138. ast_node(re, OrReturnExpr, node);
  7139. String name = re->token.string;
  7140. Operand x = {};
  7141. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7142. if (x.mode == Addressing_Invalid) {
  7143. o->mode = Addressing_Value;
  7144. o->type = t_invalid;
  7145. o->expr = node;
  7146. return Expr_Expr;
  7147. }
  7148. Type *left_type = nullptr;
  7149. Type *right_type = nullptr;
  7150. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7151. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7152. if (right_type == nullptr) {
  7153. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7154. } else {
  7155. Type *proc_type = base_type(c->curr_proc_sig);
  7156. GB_ASSERT(proc_type->kind == Type_Proc);
  7157. Type *result_type = proc_type->Proc.results;
  7158. if (result_type == nullptr) {
  7159. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7160. } else {
  7161. GB_ASSERT(result_type->kind == Type_Tuple);
  7162. auto const &vars = result_type->Tuple.variables;
  7163. Type *end_type = vars[vars.count-1]->type;
  7164. if (vars.count > 1) {
  7165. if (!proc_type->Proc.has_named_results) {
  7166. 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));
  7167. }
  7168. }
  7169. Operand rhs = {};
  7170. rhs.type = right_type;
  7171. rhs.mode = Addressing_Value;
  7172. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7173. // NOTE(bill): allow implicit conversion between boolean types
  7174. // within 'or_return' to improve the experience using third-party code
  7175. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7176. // TODO(bill): better error message
  7177. gbString a = type_to_string(right_type);
  7178. gbString b = type_to_string(end_type);
  7179. gbString ret_type = type_to_string(result_type);
  7180. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7181. if (vars.count == 1) {
  7182. error_line("\tProcedure return value type: %s\n", ret_type);
  7183. } else {
  7184. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7185. }
  7186. gb_string_free(ret_type);
  7187. gb_string_free(b);
  7188. gb_string_free(a);
  7189. }
  7190. }
  7191. }
  7192. o->expr = node;
  7193. o->type = left_type;
  7194. if (left_type != nullptr) {
  7195. o->mode = Addressing_Value;
  7196. } else {
  7197. o->mode = Addressing_NoValue;
  7198. }
  7199. if (c->curr_proc_sig == nullptr) {
  7200. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7201. }
  7202. if (c->in_defer) {
  7203. error(node, "'or_return' cannot be used within a defer statement");
  7204. }
  7205. return Expr_Expr;
  7206. }
  7207. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7208. ast_node(be, OrBranchExpr, node);
  7209. String name = be->token.string;
  7210. Operand x = {};
  7211. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7212. if (x.mode == Addressing_Invalid) {
  7213. o->mode = Addressing_Value;
  7214. o->type = t_invalid;
  7215. o->expr = node;
  7216. return Expr_Expr;
  7217. }
  7218. Type *left_type = nullptr;
  7219. Type *right_type = nullptr;
  7220. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7221. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7222. if (right_type == nullptr) {
  7223. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7224. } else {
  7225. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7226. // okay
  7227. } else {
  7228. gbString s = type_to_string(right_type);
  7229. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7230. gb_string_free(s);
  7231. }
  7232. }
  7233. o->expr = node;
  7234. o->type = left_type;
  7235. if (left_type != nullptr) {
  7236. o->mode = Addressing_Value;
  7237. } else {
  7238. o->mode = Addressing_NoValue;
  7239. }
  7240. if (c->curr_proc_sig == nullptr) {
  7241. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7242. }
  7243. Ast *label = be->label;
  7244. switch (be->token.kind) {
  7245. case Token_or_break:
  7246. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7247. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7248. }
  7249. break;
  7250. case Token_or_continue:
  7251. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7252. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7253. }
  7254. break;
  7255. }
  7256. if (label != nullptr) {
  7257. if (label->kind != Ast_Ident) {
  7258. error(label, "A branch statement's label name must be an identifier");
  7259. return Expr_Expr;
  7260. }
  7261. Ast *ident = label;
  7262. String name = ident->Ident.token.string;
  7263. Operand o = {};
  7264. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7265. if (e == nullptr) {
  7266. error(ident, "Undeclared label name: %.*s", LIT(name));
  7267. return Expr_Expr;
  7268. }
  7269. add_entity_use(c, ident, e);
  7270. if (e->kind != Entity_Label) {
  7271. error(ident, "'%.*s' is not a label", LIT(name));
  7272. return Expr_Expr;
  7273. }
  7274. Ast *parent = e->Label.parent;
  7275. GB_ASSERT(parent != nullptr);
  7276. switch (parent->kind) {
  7277. case Ast_BlockStmt:
  7278. case Ast_IfStmt:
  7279. case Ast_SwitchStmt:
  7280. if (be->token.kind != Token_or_break) {
  7281. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7282. }
  7283. break;
  7284. case Ast_RangeStmt:
  7285. case Ast_ForStmt:
  7286. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7287. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7288. }
  7289. break;
  7290. }
  7291. }
  7292. return Expr_Expr;
  7293. }
  7294. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7295. Type *bt = base_type(type);
  7296. StringSet fields_visited = {};
  7297. defer (string_set_destroy(&fields_visited));
  7298. StringMap<String> fields_visited_through_raw_union = {};
  7299. defer (string_map_destroy(&fields_visited_through_raw_union));
  7300. for (Ast *elem : elems) {
  7301. if (elem->kind != Ast_FieldValue) {
  7302. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7303. continue;
  7304. }
  7305. ast_node(fv, FieldValue, elem);
  7306. if (fv->field->kind != Ast_Ident) {
  7307. gbString expr_str = expr_to_string(fv->field);
  7308. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7309. gb_string_free(expr_str);
  7310. continue;
  7311. }
  7312. String name = fv->field->Ident.token.string;
  7313. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7314. bool is_unknown = sel.entity == nullptr;
  7315. if (is_unknown) {
  7316. error(fv->field, "Unknown field '%.*s' in structure literal", LIT(name));
  7317. continue;
  7318. }
  7319. Entity *field = bt->Struct.fields[sel.index[0]];
  7320. add_entity_use(c, fv->field, field);
  7321. if (string_set_update(&fields_visited, name)) {
  7322. if (sel.index.count > 1) {
  7323. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7324. 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));
  7325. } else {
  7326. error(fv->field, "Duplicate or reused field '%.*s' in structure literal", LIT(sel.entity->token.string));
  7327. }
  7328. } else {
  7329. error(fv->field, "Duplicate field '%.*s' in structure literal", LIT(field->token.string));
  7330. }
  7331. continue;
  7332. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7333. 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));
  7334. continue;
  7335. }
  7336. if (sel.indirect) {
  7337. 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));
  7338. continue;
  7339. }
  7340. if (sel.index.count > 1) {
  7341. if (is_constant) {
  7342. Type *ft = type;
  7343. for (i32 index : sel.index) {
  7344. Type *bt = base_type(ft);
  7345. switch (bt->kind) {
  7346. case Type_Struct:
  7347. if (bt->Struct.is_raw_union) {
  7348. is_constant = false;
  7349. break;
  7350. }
  7351. ft = bt->Struct.fields[index]->type;
  7352. break;
  7353. case Type_Array:
  7354. ft = bt->Array.elem;
  7355. break;
  7356. default:
  7357. GB_PANIC("invalid type: %s", type_to_string(ft));
  7358. break;
  7359. }
  7360. }
  7361. if (is_constant &&
  7362. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7363. is_constant = false;
  7364. }
  7365. }
  7366. Type *nested_ft = bt;
  7367. for (i32 index : sel.index) {
  7368. Type *bt = base_type(nested_ft);
  7369. switch (bt->kind) {
  7370. case Type_Struct:
  7371. if (bt->Struct.is_raw_union) {
  7372. for (Entity *re : bt->Struct.fields) {
  7373. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7374. }
  7375. }
  7376. nested_ft = bt->Struct.fields[index]->type;
  7377. break;
  7378. case Type_Array:
  7379. nested_ft = bt->Array.elem;
  7380. break;
  7381. default:
  7382. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7383. break;
  7384. }
  7385. }
  7386. field = sel.entity;
  7387. }
  7388. Operand o = {};
  7389. check_expr_or_type(c, &o, fv->value, field->type);
  7390. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7391. is_constant = false;
  7392. }
  7393. if (is_constant) {
  7394. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7395. }
  7396. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7397. }
  7398. }
  7399. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7400. ExprKind kind = Expr_Expr;
  7401. ast_node(cl, CompoundLit, node);
  7402. Type *type = type_hint;
  7403. if (type != nullptr && is_type_untyped(type)) {
  7404. type = nullptr;
  7405. }
  7406. bool is_to_be_determined_array_count = false;
  7407. bool is_constant = true;
  7408. if (cl->type != nullptr) {
  7409. type = nullptr;
  7410. // [?]Type
  7411. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  7412. Ast *count = cl->type->ArrayType.count;
  7413. if (count->kind == Ast_UnaryExpr &&
  7414. count->UnaryExpr.op.kind == Token_Question) {
  7415. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  7416. is_to_be_determined_array_count = true;
  7417. }
  7418. if (cl->elems.count > 0) {
  7419. if (cl->type->ArrayType.tag != nullptr) {
  7420. Ast *tag = cl->type->ArrayType.tag;
  7421. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7422. String name = tag->BasicDirective.name.string;
  7423. if (name == "soa") {
  7424. error(node, "#soa arrays are not supported for compound literals");
  7425. return kind;
  7426. }
  7427. }
  7428. }
  7429. }
  7430. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  7431. if (cl->elems.count > 0) {
  7432. Ast *tag = cl->type->DynamicArrayType.tag;
  7433. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7434. String name = tag->BasicDirective.name.string;
  7435. if (name == "soa") {
  7436. error(node, "#soa arrays are not supported for compound literals");
  7437. return kind;
  7438. }
  7439. }
  7440. }
  7441. if (type == nullptr) {
  7442. type = check_type(c, cl->type);
  7443. }
  7444. }
  7445. if (type == nullptr) {
  7446. error(node, "Missing type in compound literal");
  7447. return kind;
  7448. }
  7449. Type *t = base_type(type);
  7450. if (is_type_polymorphic(t)) {
  7451. gbString str = type_to_string(type);
  7452. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7453. o->expr = node;
  7454. o->type = type;
  7455. gb_string_free(str);
  7456. return kind;
  7457. }
  7458. switch (t->kind) {
  7459. case Type_Struct: {
  7460. if (cl->elems.count == 0) {
  7461. break; // NOTE(bill): No need to init
  7462. }
  7463. if (t->Struct.is_raw_union) {
  7464. if (cl->elems.count > 0) {
  7465. // NOTE: unions cannot be constant
  7466. is_constant = false;
  7467. if (cl->elems[0]->kind != Ast_FieldValue) {
  7468. gbString type_str = type_to_string(type);
  7469. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7470. gb_string_free(type_str);
  7471. } else {
  7472. if (cl->elems.count != 1) {
  7473. gbString type_str = type_to_string(type);
  7474. 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);
  7475. gb_string_free(type_str);
  7476. } else {
  7477. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7478. }
  7479. }
  7480. }
  7481. break;
  7482. }
  7483. isize field_count = t->Struct.fields.count;
  7484. isize min_field_count = t->Struct.fields.count;
  7485. for (isize i = min_field_count-1; i >= 0; i--) {
  7486. Entity *e = t->Struct.fields[i];
  7487. GB_ASSERT(e->kind == Entity_Variable);
  7488. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7489. min_field_count--;
  7490. } else {
  7491. break;
  7492. }
  7493. }
  7494. if (cl->elems[0]->kind == Ast_FieldValue) {
  7495. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7496. } else {
  7497. bool seen_field_value = false;
  7498. for_array(index, cl->elems) {
  7499. Entity *field = nullptr;
  7500. Ast *elem = cl->elems[index];
  7501. if (elem->kind == Ast_FieldValue) {
  7502. seen_field_value = true;
  7503. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7504. continue;
  7505. } else if (seen_field_value) {
  7506. error(elem, "Value elements cannot be used after a 'field = value'");
  7507. continue;
  7508. }
  7509. if (index >= field_count) {
  7510. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7511. break;
  7512. }
  7513. if (field == nullptr) {
  7514. field = t->Struct.fields[index];
  7515. }
  7516. Operand o = {};
  7517. check_expr_or_type(c, &o, elem, field->type);
  7518. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7519. is_constant = false;
  7520. }
  7521. if (is_constant) {
  7522. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7523. }
  7524. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7525. }
  7526. if (cl->elems.count < field_count) {
  7527. if (min_field_count < field_count) {
  7528. if (cl->elems.count < min_field_count) {
  7529. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7530. }
  7531. } else {
  7532. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7533. }
  7534. }
  7535. }
  7536. break;
  7537. }
  7538. case Type_Slice:
  7539. case Type_Array:
  7540. case Type_DynamicArray:
  7541. case Type_SimdVector:
  7542. case Type_Matrix:
  7543. {
  7544. Type *elem_type = nullptr;
  7545. String context_name = {};
  7546. i64 max_type_count = -1;
  7547. if (t->kind == Type_Slice) {
  7548. elem_type = t->Slice.elem;
  7549. context_name = str_lit("slice literal");
  7550. } else if (t->kind == Type_Array) {
  7551. elem_type = t->Array.elem;
  7552. context_name = str_lit("array literal");
  7553. if (!is_to_be_determined_array_count) {
  7554. max_type_count = t->Array.count;
  7555. }
  7556. } else if (t->kind == Type_DynamicArray) {
  7557. elem_type = t->DynamicArray.elem;
  7558. context_name = str_lit("dynamic array literal");
  7559. is_constant = false;
  7560. if (!build_context.no_dynamic_literals) {
  7561. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7562. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7563. }
  7564. } else if (t->kind == Type_SimdVector) {
  7565. elem_type = t->SimdVector.elem;
  7566. context_name = str_lit("simd vector literal");
  7567. max_type_count = t->SimdVector.count;
  7568. } else if (t->kind == Type_Matrix) {
  7569. elem_type = t->Matrix.elem;
  7570. context_name = str_lit("matrix literal");
  7571. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7572. } else {
  7573. GB_PANIC("unreachable");
  7574. }
  7575. i64 max = 0;
  7576. Type *bet = base_type(elem_type);
  7577. if (!elem_type_can_be_constant(bet)) {
  7578. is_constant = false;
  7579. }
  7580. if (bet == t_invalid) {
  7581. break;
  7582. }
  7583. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7584. RangeCache rc = range_cache_make(heap_allocator());
  7585. defer (range_cache_destroy(&rc));
  7586. for (Ast *elem : cl->elems) {
  7587. if (elem->kind != Ast_FieldValue) {
  7588. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7589. continue;
  7590. }
  7591. ast_node(fv, FieldValue, elem);
  7592. if (is_ast_range(fv->field)) {
  7593. Token op = fv->field->BinaryExpr.op;
  7594. Operand x = {};
  7595. Operand y = {};
  7596. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7597. if (!ok) {
  7598. continue;
  7599. }
  7600. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7601. error(x.expr, "Expected a constant integer as an array field");
  7602. continue;
  7603. }
  7604. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7605. error(y.expr, "Expected a constant integer as an array field");
  7606. continue;
  7607. }
  7608. i64 lo = exact_value_to_i64(x.value);
  7609. i64 hi = exact_value_to_i64(y.value);
  7610. i64 max_index = hi;
  7611. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7612. hi -= 1;
  7613. } else { // .. (inclusive)
  7614. max_index += 1;
  7615. }
  7616. bool new_range = range_cache_add_range(&rc, lo, hi);
  7617. if (!new_range) {
  7618. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7619. continue;
  7620. }
  7621. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7622. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7623. continue;
  7624. }
  7625. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7626. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7627. continue;
  7628. }
  7629. if (max < hi) {
  7630. max = max_index;
  7631. }
  7632. Operand operand = {};
  7633. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7634. check_assignment(c, &operand, elem_type, context_name);
  7635. is_constant = is_constant && operand.mode == Addressing_Constant;
  7636. } else {
  7637. Operand op_index = {};
  7638. check_expr(c, &op_index, fv->field);
  7639. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7640. error(elem, "Expected a constant integer as an array field");
  7641. continue;
  7642. }
  7643. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7644. i64 index = exact_value_to_i64(op_index.value);
  7645. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7646. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7647. continue;
  7648. }
  7649. bool new_index = range_cache_add_index(&rc, index);
  7650. if (!new_index) {
  7651. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7652. continue;
  7653. }
  7654. if (max < index+1) {
  7655. max = index+1;
  7656. }
  7657. Operand operand = {};
  7658. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7659. check_assignment(c, &operand, elem_type, context_name);
  7660. is_constant = is_constant && operand.mode == Addressing_Constant;
  7661. }
  7662. }
  7663. cl->max_count = max;
  7664. } else {
  7665. isize index = 0;
  7666. for (; index < cl->elems.count; index++) {
  7667. Ast *e = cl->elems[index];
  7668. if (e == nullptr) {
  7669. error(node, "Invalid literal element");
  7670. continue;
  7671. }
  7672. if (e->kind == Ast_FieldValue) {
  7673. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7674. continue;
  7675. }
  7676. if (0 <= max_type_count && max_type_count <= index) {
  7677. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7678. }
  7679. Operand operand = {};
  7680. check_expr_with_type_hint(c, &operand, e, elem_type);
  7681. check_assignment(c, &operand, elem_type, context_name);
  7682. is_constant = is_constant && operand.mode == Addressing_Constant;
  7683. }
  7684. if (max < index) {
  7685. max = index;
  7686. }
  7687. }
  7688. if (t->kind == Type_Array) {
  7689. if (is_to_be_determined_array_count) {
  7690. t->Array.count = max;
  7691. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7692. if (0 < max && max < t->Array.count) {
  7693. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7694. }
  7695. }
  7696. }
  7697. if (t->kind == Type_SimdVector) {
  7698. if (!is_constant) {
  7699. // error(node, "Expected all constant elements for a simd vector");
  7700. }
  7701. }
  7702. if (t->kind == Type_DynamicArray) {
  7703. if (build_context.no_dynamic_literals && cl->elems.count) {
  7704. error(node, "Compound literals of dynamic types have been disabled");
  7705. }
  7706. }
  7707. if (t->kind == Type_Matrix) {
  7708. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7709. if (0 < max && max < max_type_count) {
  7710. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7711. }
  7712. }
  7713. }
  7714. break;
  7715. }
  7716. case Type_EnumeratedArray:
  7717. {
  7718. Type *elem_type = t->EnumeratedArray.elem;
  7719. Type *index_type = t->EnumeratedArray.index;
  7720. String context_name = str_lit("enumerated array literal");
  7721. i64 max_type_count = t->EnumeratedArray.count;
  7722. gbString index_type_str = type_to_string(index_type);
  7723. defer (gb_string_free(index_type_str));
  7724. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7725. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7726. String total_lo_string = {};
  7727. String total_hi_string = {};
  7728. GB_ASSERT(is_type_enum(index_type));
  7729. {
  7730. Type *bt = base_type(index_type);
  7731. GB_ASSERT(bt->kind == Type_Enum);
  7732. for (Entity *f : bt->Enum.fields) {
  7733. if (f->kind != Entity_Constant) {
  7734. continue;
  7735. }
  7736. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7737. total_lo_string = f->token.string;
  7738. }
  7739. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7740. total_hi_string = f->token.string;
  7741. }
  7742. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  7743. break;
  7744. }
  7745. }
  7746. }
  7747. i64 max = 0;
  7748. Type *bet = base_type(elem_type);
  7749. if (!elem_type_can_be_constant(bet)) {
  7750. is_constant = false;
  7751. }
  7752. if (bet == t_invalid) {
  7753. break;
  7754. }
  7755. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  7756. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  7757. defer (map_destroy(&seen));
  7758. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7759. RangeCache rc = range_cache_make(heap_allocator());
  7760. defer (range_cache_destroy(&rc));
  7761. for (Ast *elem : cl->elems) {
  7762. if (elem->kind != Ast_FieldValue) {
  7763. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7764. continue;
  7765. }
  7766. ast_node(fv, FieldValue, elem);
  7767. if (is_ast_range(fv->field)) {
  7768. Token op = fv->field->BinaryExpr.op;
  7769. Operand x = {};
  7770. Operand y = {};
  7771. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  7772. if (!ok) {
  7773. continue;
  7774. }
  7775. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7776. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7777. continue;
  7778. }
  7779. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7780. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7781. continue;
  7782. }
  7783. i64 lo = exact_value_to_i64(x.value);
  7784. i64 hi = exact_value_to_i64(y.value);
  7785. i64 max_index = hi;
  7786. if (op.kind == Token_RangeHalf) {
  7787. hi -= 1;
  7788. }
  7789. bool new_range = range_cache_add_range(&rc, lo, hi);
  7790. if (!new_range) {
  7791. gbString lo_str = expr_to_string(x.expr);
  7792. gbString hi_str = expr_to_string(y.expr);
  7793. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  7794. gb_string_free(hi_str);
  7795. gb_string_free(lo_str);
  7796. continue;
  7797. }
  7798. // NOTE(bill): These are sanity checks for invalid enum values
  7799. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  7800. gbString lo_str = expr_to_string(x.expr);
  7801. 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));
  7802. gb_string_free(lo_str);
  7803. continue;
  7804. }
  7805. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  7806. gbString hi_str = expr_to_string(y.expr);
  7807. 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));
  7808. gb_string_free(hi_str);
  7809. continue;
  7810. }
  7811. if (max < hi) {
  7812. max = max_index;
  7813. }
  7814. Operand operand = {};
  7815. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7816. check_assignment(c, &operand, elem_type, context_name);
  7817. is_constant = is_constant && operand.mode == Addressing_Constant;
  7818. TokenKind upper_op = Token_LtEq;
  7819. if (op.kind == Token_RangeHalf) {
  7820. upper_op = Token_Lt;
  7821. }
  7822. add_to_seen_map(c, &seen, upper_op, x, x, y);
  7823. } else {
  7824. Operand op_index = {};
  7825. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  7826. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  7827. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7828. continue;
  7829. }
  7830. i64 index = exact_value_to_i64(op_index.value);
  7831. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  7832. gbString idx_str = expr_to_string(op_index.expr);
  7833. 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));
  7834. gb_string_free(idx_str);
  7835. continue;
  7836. }
  7837. bool new_index = range_cache_add_index(&rc, index);
  7838. if (!new_index) {
  7839. gbString idx_str = expr_to_string(op_index.expr);
  7840. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  7841. gb_string_free(idx_str);
  7842. continue;
  7843. }
  7844. if (max < index+1) {
  7845. max = index+1;
  7846. }
  7847. Operand operand = {};
  7848. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7849. check_assignment(c, &operand, elem_type, context_name);
  7850. is_constant = is_constant && operand.mode == Addressing_Constant;
  7851. add_to_seen_map(c, &seen, op_index);
  7852. }
  7853. }
  7854. cl->max_count = max;
  7855. } else {
  7856. isize index = 0;
  7857. for (; index < cl->elems.count; index++) {
  7858. Ast *e = cl->elems[index];
  7859. if (e == nullptr) {
  7860. error(node, "Invalid literal element");
  7861. continue;
  7862. }
  7863. if (e->kind == Ast_FieldValue) {
  7864. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7865. continue;
  7866. }
  7867. if (0 <= max_type_count && max_type_count <= index) {
  7868. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7869. }
  7870. Operand operand = {};
  7871. check_expr_with_type_hint(c, &operand, e, elem_type);
  7872. check_assignment(c, &operand, elem_type, context_name);
  7873. is_constant = is_constant && operand.mode == Addressing_Constant;
  7874. }
  7875. if (max < index) {
  7876. max = index;
  7877. }
  7878. }
  7879. bool was_error = false;
  7880. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7881. if (0 < max && max < t->EnumeratedArray.count) {
  7882. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  7883. was_error = true;
  7884. } else {
  7885. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  7886. was_error = true;
  7887. }
  7888. }
  7889. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  7890. if (cl->elems.count > 0 && !was_error && !is_partial) {
  7891. TEMPORARY_ALLOCATOR_GUARD();
  7892. Type *et = base_type(index_type);
  7893. GB_ASSERT(et->kind == Type_Enum);
  7894. auto fields = et->Enum.fields;
  7895. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  7896. for (Entity *f : fields) {
  7897. if (f->kind != Entity_Constant) {
  7898. continue;
  7899. }
  7900. ExactValue v = f->Constant.value;
  7901. auto found = map_get(&seen, hash_exact_value(v));
  7902. if (!found) {
  7903. array_add(&unhandled, f);
  7904. }
  7905. }
  7906. if (unhandled.count > 0) {
  7907. begin_error_block();
  7908. defer (end_error_block());
  7909. if (unhandled.count == 1) {
  7910. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  7911. } else {
  7912. error(node, "Unhandled enumerated array cases:");
  7913. for_array(i, unhandled) {
  7914. Entity *f = unhandled[i];
  7915. error_line("\t%.*s\n", LIT(f->token.string));
  7916. }
  7917. }
  7918. error_line("\n");
  7919. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  7920. }
  7921. }
  7922. break;
  7923. }
  7924. case Type_Basic: {
  7925. if (!is_type_any(t)) {
  7926. if (cl->elems.count != 0) {
  7927. gbString s = type_to_string(t);
  7928. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  7929. gb_string_free(s);
  7930. is_constant = false;
  7931. }
  7932. break;
  7933. }
  7934. if (cl->elems.count == 0) {
  7935. break; // NOTE(bill): No need to init
  7936. }
  7937. { // Checker values
  7938. Type *field_types[2] = {t_rawptr, t_typeid};
  7939. isize field_count = 2;
  7940. if (cl->elems[0]->kind == Ast_FieldValue) {
  7941. bool fields_visited[2] = {};
  7942. for_array(i, cl->elems) {
  7943. Ast *elem = cl->elems[i];
  7944. if (elem->kind != Ast_FieldValue) {
  7945. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7946. continue;
  7947. }
  7948. ast_node(fv, FieldValue, elem);
  7949. if (fv->field->kind != Ast_Ident) {
  7950. gbString expr_str = expr_to_string(fv->field);
  7951. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  7952. gb_string_free(expr_str);
  7953. continue;
  7954. }
  7955. String name = fv->field->Ident.token.string;
  7956. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7957. if (sel.entity == nullptr) {
  7958. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  7959. continue;
  7960. }
  7961. isize index = sel.index[0];
  7962. if (fields_visited[index]) {
  7963. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  7964. continue;
  7965. }
  7966. fields_visited[index] = true;
  7967. check_expr(c, o, fv->value);
  7968. // NOTE(bill): 'any' literals can never be constant
  7969. is_constant = false;
  7970. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7971. }
  7972. } else {
  7973. for_array(index, cl->elems) {
  7974. Ast *elem = cl->elems[index];
  7975. if (elem->kind == Ast_FieldValue) {
  7976. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7977. continue;
  7978. }
  7979. check_expr(c, o, elem);
  7980. if (index >= field_count) {
  7981. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  7982. break;
  7983. }
  7984. // NOTE(bill): 'any' literals can never be constant
  7985. is_constant = false;
  7986. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7987. }
  7988. if (cl->elems.count < field_count) {
  7989. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  7990. }
  7991. }
  7992. }
  7993. break;
  7994. }
  7995. case Type_Map: {
  7996. if (cl->elems.count == 0) {
  7997. break;
  7998. }
  7999. is_constant = false;
  8000. { // Checker values
  8001. bool key_is_typeid = is_type_typeid(t->Map.key);
  8002. bool value_is_typeid = is_type_typeid(t->Map.value);
  8003. for (Ast *elem : cl->elems) {
  8004. if (elem->kind != Ast_FieldValue) {
  8005. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8006. continue;
  8007. }
  8008. ast_node(fv, FieldValue, elem);
  8009. if (key_is_typeid) {
  8010. check_expr_or_type(c, o, fv->field, t->Map.key);
  8011. } else {
  8012. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8013. }
  8014. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8015. if (o->mode == Addressing_Invalid) {
  8016. continue;
  8017. }
  8018. if (value_is_typeid) {
  8019. check_expr_or_type(c, o, fv->value, t->Map.value);
  8020. } else {
  8021. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8022. }
  8023. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8024. }
  8025. }
  8026. if (build_context.no_dynamic_literals && cl->elems.count) {
  8027. error(node, "Compound literals of dynamic types have been disabled");
  8028. } else {
  8029. add_map_reserve_dependencies(c);
  8030. add_map_set_dependencies(c);
  8031. }
  8032. break;
  8033. }
  8034. case Type_BitSet: {
  8035. if (cl->elems.count == 0) {
  8036. break; // NOTE(bill): No need to init
  8037. }
  8038. Type *et = base_type(t->BitSet.elem);
  8039. isize field_count = 0;
  8040. if (et->kind == Type_Enum) {
  8041. field_count = et->Enum.fields.count;
  8042. }
  8043. if (cl->elems[0]->kind == Ast_FieldValue) {
  8044. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8045. is_constant = false;
  8046. } else {
  8047. for (Ast *elem : cl->elems) {
  8048. if (elem->kind == Ast_FieldValue) {
  8049. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8050. continue;
  8051. }
  8052. check_expr_with_type_hint(c, o, elem, et);
  8053. if (is_constant) {
  8054. is_constant = o->mode == Addressing_Constant;
  8055. }
  8056. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8057. if (o->mode == Addressing_Constant) {
  8058. i64 lower = t->BitSet.lower;
  8059. i64 upper = t->BitSet.upper;
  8060. i64 v = exact_value_to_i64(o->value);
  8061. if (lower <= v && v <= upper) {
  8062. // okay
  8063. } else {
  8064. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8065. continue;
  8066. }
  8067. }
  8068. }
  8069. }
  8070. break;
  8071. }
  8072. default: {
  8073. if (cl->elems.count == 0) {
  8074. break; // NOTE(bill): No need to init
  8075. }
  8076. gbString str = type_to_string(type);
  8077. error(node, "Invalid compound literal type '%s'", str);
  8078. gb_string_free(str);
  8079. return kind;
  8080. }
  8081. }
  8082. if (is_constant) {
  8083. o->mode = Addressing_Constant;
  8084. if (is_type_bit_set(type)) {
  8085. // NOTE(bill): Encode as an integer
  8086. Type *bt = base_type(type);
  8087. BigInt bits = {};
  8088. BigInt one = {};
  8089. big_int_from_u64(&one, 1);
  8090. for (Ast *e : cl->elems) {
  8091. GB_ASSERT(e->kind != Ast_FieldValue);
  8092. TypeAndValue tav = e->tav;
  8093. if (tav.mode != Addressing_Constant) {
  8094. continue;
  8095. }
  8096. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8097. i64 v = big_int_to_i64(&tav.value.value_integer);
  8098. i64 lower = bt->BitSet.lower;
  8099. u64 index = cast(u64)(v-lower);
  8100. BigInt bit = {};
  8101. big_int_from_u64(&bit, index);
  8102. big_int_shl(&bit, &one, &bit);
  8103. big_int_or(&bits, &bits, &bit);
  8104. }
  8105. o->value.kind = ExactValue_Integer;
  8106. o->value.value_integer = bits;
  8107. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8108. ExactValue value = exact_value_compound(node);
  8109. Type *bt = core_type(type);
  8110. if (bt->kind == Type_Basic) {
  8111. if (bt->Basic.flags & BasicFlag_Boolean) {
  8112. value = exact_value_bool(false);
  8113. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8114. value = exact_value_i64(0);
  8115. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8116. value = exact_value_i64(0);
  8117. } else if (bt->Basic.flags & BasicFlag_Float) {
  8118. value = exact_value_float(0);
  8119. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8120. value = exact_value_complex(0, 0);
  8121. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8122. value = exact_value_quaternion(0, 0, 0, 0);
  8123. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8124. value = exact_value_pointer(0);
  8125. } else if (bt->Basic.flags & BasicFlag_String) {
  8126. String empty_string = {};
  8127. value = exact_value_string(empty_string);
  8128. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8129. value = exact_value_i64(0);
  8130. }
  8131. }
  8132. o->value = value;
  8133. } else {
  8134. o->value = exact_value_compound(node);
  8135. }
  8136. } else {
  8137. o->mode = Addressing_Value;
  8138. }
  8139. o->type = type;
  8140. return kind;
  8141. }
  8142. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8143. ExprKind kind = Expr_Expr;
  8144. ast_node(ta, TypeAssertion, node);
  8145. check_expr(c, o, ta->expr);
  8146. node->viral_state_flags |= ta->expr->viral_state_flags;
  8147. if (o->mode == Addressing_Invalid) {
  8148. o->expr = node;
  8149. return kind;
  8150. }
  8151. if (o->mode == Addressing_Constant) {
  8152. gbString expr_str = expr_to_string(o->expr);
  8153. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8154. gb_string_free(expr_str);
  8155. o->mode = Addressing_Invalid;
  8156. o->expr = node;
  8157. return kind;
  8158. }
  8159. if (is_type_untyped(o->type)) {
  8160. gbString expr_str = expr_to_string(o->expr);
  8161. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8162. gb_string_free(expr_str);
  8163. o->mode = Addressing_Invalid;
  8164. o->expr = node;
  8165. return kind;
  8166. }
  8167. Type *src = type_deref(o->type);
  8168. Type *bsrc = base_type(src);
  8169. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8170. if (!is_type_union(src)) {
  8171. gbString str = type_to_string(o->type);
  8172. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8173. gb_string_free(str);
  8174. o->mode = Addressing_Invalid;
  8175. o->expr = node;
  8176. return kind;
  8177. }
  8178. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8179. bool allowed = false;
  8180. for (Type *vt : bsrc->Union.variants) {
  8181. if (are_types_identical(vt, type_hint)) {
  8182. allowed = true;
  8183. add_type_info_type(c, vt);
  8184. break;
  8185. }
  8186. }
  8187. if (allowed) {
  8188. add_type_info_type(c, o->type);
  8189. o->type = type_hint;
  8190. o->mode = Addressing_OptionalOk;
  8191. return kind;
  8192. }
  8193. }
  8194. if (bsrc->Union.variants.count != 1) {
  8195. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8196. o->mode = Addressing_Invalid;
  8197. o->expr = node;
  8198. return kind;
  8199. }
  8200. add_type_info_type(c, o->type);
  8201. add_type_info_type(c, bsrc->Union.variants[0]);
  8202. o->type = bsrc->Union.variants[0];
  8203. o->mode = Addressing_OptionalOk;
  8204. } else {
  8205. Type *t = check_type(c, ta->type);
  8206. Type *dst = t;
  8207. if (is_type_union(src)) {
  8208. bool ok = false;
  8209. for (Type *vt : bsrc->Union.variants) {
  8210. if (are_types_identical(vt, dst)) {
  8211. ok = true;
  8212. break;
  8213. }
  8214. }
  8215. if (!ok) {
  8216. gbString expr_str = expr_to_string(o->expr);
  8217. gbString dst_type_str = type_to_string(t);
  8218. defer (gb_string_free(expr_str));
  8219. defer (gb_string_free(dst_type_str));
  8220. if (bsrc->Union.variants.count == 0) {
  8221. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8222. } else {
  8223. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8224. }
  8225. o->mode = Addressing_Invalid;
  8226. o->expr = node;
  8227. return kind;
  8228. }
  8229. add_type_info_type(c, o->type);
  8230. add_type_info_type(c, t);
  8231. o->type = t;
  8232. o->mode = Addressing_OptionalOk;
  8233. } else if (is_type_any(src)) {
  8234. o->type = t;
  8235. o->mode = Addressing_OptionalOk;
  8236. add_type_info_type(c, o->type);
  8237. add_type_info_type(c, t);
  8238. } else {
  8239. gbString str = type_to_string(o->type);
  8240. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8241. gb_string_free(str);
  8242. o->mode = Addressing_Invalid;
  8243. o->expr = node;
  8244. return kind;
  8245. }
  8246. }
  8247. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8248. add_package_dependency(c, "runtime", "type_assertion_check");
  8249. add_package_dependency(c, "runtime", "type_assertion_check2");
  8250. }
  8251. return kind;
  8252. }
  8253. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8254. ast_node(se, SelectorCallExpr, node);
  8255. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8256. // COM APIs is a great example of where this kind of thing is extremely useful
  8257. // General idea:
  8258. //
  8259. // x->y(123) == x.y(x, 123)
  8260. //
  8261. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8262. // Just regenerating a new AST aids things
  8263. //
  8264. // TODO(bill): Is this a good hack or not?
  8265. //
  8266. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8267. if (se->modified_call) {
  8268. // Prevent double evaluation
  8269. o->expr = node;
  8270. o->type = node->tav.type;
  8271. o->value = node->tav.value;
  8272. o->mode = node->tav.mode;
  8273. return Expr_Expr;
  8274. }
  8275. bool allow_arrow_right_selector_expr;
  8276. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8277. c->allow_arrow_right_selector_expr = true;
  8278. Operand x = {};
  8279. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8280. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8281. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8282. o->mode = Addressing_Invalid;
  8283. o->type = t_invalid;
  8284. o->expr = node;
  8285. return kind;
  8286. }
  8287. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8288. gbString type_str = type_to_string(x.type);
  8289. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8290. gb_string_free(type_str);
  8291. o->mode = Addressing_Invalid;
  8292. o->type = t_invalid;
  8293. o->expr = node;
  8294. return Expr_Stmt;
  8295. }
  8296. ast_node(ce, CallExpr, se->call);
  8297. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8298. Ast *first_arg = x.expr->SelectorExpr.expr;
  8299. GB_ASSERT(first_arg != nullptr);
  8300. Entity *e = entity_of_node(se->expr);
  8301. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8302. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8303. }
  8304. if (e->kind != Entity_ProcGroup) {
  8305. Type *pt = base_type(x.type);
  8306. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8307. Type *first_type = nullptr;
  8308. String first_arg_name = {};
  8309. if (pt->Proc.param_count > 0) {
  8310. Entity *f = pt->Proc.params->Tuple.variables[0];
  8311. first_type = f->type;
  8312. first_arg_name = f->token.string;
  8313. }
  8314. if (first_arg_name.len == 0) {
  8315. first_arg_name = str_lit("_");
  8316. }
  8317. if (first_type == nullptr) {
  8318. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8319. o->mode = Addressing_Invalid;
  8320. o->type = t_invalid;
  8321. o->expr = node;
  8322. return Expr_Stmt;
  8323. }
  8324. Operand y = {};
  8325. y.mode = first_arg->tav.mode;
  8326. y.type = first_arg->tav.type;
  8327. y.value = first_arg->tav.value;
  8328. if (check_is_assignable_to(c, &y, first_type)) {
  8329. // Do nothing, it's valid
  8330. } else {
  8331. Operand z = y;
  8332. z.type = type_deref(y.type);
  8333. if (check_is_assignable_to(c, &z, first_type)) {
  8334. // NOTE(bill): AST GENERATION HACK!
  8335. Token op = {Token_Pointer};
  8336. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8337. } else if (y.mode == Addressing_Variable) {
  8338. Operand w = y;
  8339. w.type = alloc_type_pointer(y.type);
  8340. if (check_is_assignable_to(c, &w, first_type)) {
  8341. // NOTE(bill): AST GENERATION HACK!
  8342. Token op = {Token_And};
  8343. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8344. }
  8345. }
  8346. }
  8347. if (ce->args.count > 0) {
  8348. bool fail = false;
  8349. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8350. for (Ast *arg : ce->args) {
  8351. bool mix = false;
  8352. if (first_is_field_value) {
  8353. mix = arg->kind != Ast_FieldValue;
  8354. } else {
  8355. mix = arg->kind == Ast_FieldValue;
  8356. }
  8357. if (mix) {
  8358. fail = true;
  8359. break;
  8360. }
  8361. }
  8362. if (!fail && first_is_field_value) {
  8363. Token op = {Token_Eq};
  8364. AstFile *f = first_arg->file();
  8365. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8366. }
  8367. }
  8368. }
  8369. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8370. modified_args[0] = first_arg;
  8371. slice_copy(&modified_args, ce->args, 1);
  8372. ce->args = modified_args;
  8373. se->modified_call = true;
  8374. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8375. c->allow_arrow_right_selector_expr = true;
  8376. check_expr_base(c, o, se->call, type_hint);
  8377. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8378. o->expr = node;
  8379. return Expr_Expr;
  8380. }
  8381. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8382. ExprKind kind = Expr_Expr;
  8383. ast_node(ie, IndexExpr, node);
  8384. check_expr(c, o, ie->expr);
  8385. node->viral_state_flags |= ie->expr->viral_state_flags;
  8386. if (o->mode == Addressing_Invalid) {
  8387. o->expr = node;
  8388. return kind;
  8389. }
  8390. Type *t = base_type(type_deref(o->type));
  8391. bool is_ptr = is_type_pointer(o->type);
  8392. bool is_const = o->mode == Addressing_Constant;
  8393. if (is_type_map(t)) {
  8394. Operand key = {};
  8395. if (is_type_typeid(t->Map.key)) {
  8396. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8397. } else {
  8398. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8399. }
  8400. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8401. if (key.mode == Addressing_Invalid) {
  8402. o->mode = Addressing_Invalid;
  8403. o->expr = node;
  8404. return kind;
  8405. }
  8406. o->mode = Addressing_MapIndex;
  8407. o->type = t->Map.value;
  8408. o->expr = node;
  8409. add_map_get_dependencies(c);
  8410. add_map_set_dependencies(c);
  8411. return Expr_Expr;
  8412. }
  8413. i64 max_count = -1;
  8414. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8415. if (is_const) {
  8416. if (is_type_array(t)) {
  8417. // Okay
  8418. } else if (is_type_slice(t)) {
  8419. // Okay
  8420. } else if (is_type_enumerated_array(t)) {
  8421. // Okay
  8422. } else if (is_type_string(t)) {
  8423. // Okay
  8424. } else if (is_type_relative_multi_pointer(t)) {
  8425. // Okay
  8426. } else if (is_type_matrix(t)) {
  8427. // Okay
  8428. } else {
  8429. valid = false;
  8430. }
  8431. }
  8432. if (!valid) {
  8433. gbString str = expr_to_string(o->expr);
  8434. gbString type_str = type_to_string(o->type);
  8435. defer (gb_string_free(str));
  8436. defer (gb_string_free(type_str));
  8437. if (is_const) {
  8438. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8439. } else {
  8440. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8441. }
  8442. o->mode = Addressing_Invalid;
  8443. o->expr = node;
  8444. return kind;
  8445. }
  8446. if (ie->index == nullptr) {
  8447. gbString str = expr_to_string(o->expr);
  8448. error(o->expr, "Missing index for '%s'", str);
  8449. gb_string_free(str);
  8450. o->mode = Addressing_Invalid;
  8451. o->expr = node;
  8452. return kind;
  8453. }
  8454. Type *index_type_hint = nullptr;
  8455. if (is_type_enumerated_array(t)) {
  8456. Type *bt = base_type(t);
  8457. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8458. index_type_hint = bt->EnumeratedArray.index;
  8459. }
  8460. i64 index = 0;
  8461. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8462. if (is_const) {
  8463. if (index < 0) {
  8464. gbString str = expr_to_string(o->expr);
  8465. error(o->expr, "Cannot index a constant '%s'", str);
  8466. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8467. gb_string_free(str);
  8468. o->mode = Addressing_Invalid;
  8469. o->expr = node;
  8470. return kind;
  8471. } else if (ok) {
  8472. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8473. o->mode = Addressing_Constant;
  8474. bool success = false;
  8475. bool finish = false;
  8476. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8477. if (!success) {
  8478. gbString str = expr_to_string(o->expr);
  8479. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8480. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8481. gb_string_free(str);
  8482. o->mode = Addressing_Invalid;
  8483. o->expr = node;
  8484. return kind;
  8485. }
  8486. }
  8487. }
  8488. if (type_hint != nullptr && is_type_matrix(t)) {
  8489. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8490. // if a type hint exists
  8491. }
  8492. return kind;
  8493. }
  8494. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8495. ExprKind kind = Expr_Stmt;
  8496. ast_node(se, SliceExpr, node);
  8497. check_expr(c, o, se->expr);
  8498. node->viral_state_flags |= se->expr->viral_state_flags;
  8499. if (o->mode == Addressing_Invalid) {
  8500. o->mode = Addressing_Invalid;
  8501. o->expr = node;
  8502. return kind;
  8503. }
  8504. bool valid = false;
  8505. i64 max_count = -1;
  8506. Type *t = base_type(type_deref(o->type));
  8507. switch (t->kind) {
  8508. case Type_Basic:
  8509. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8510. valid = true;
  8511. if (o->mode == Addressing_Constant) {
  8512. max_count = o->value.value_string.len;
  8513. }
  8514. o->type = type_deref(o->type);
  8515. }
  8516. break;
  8517. case Type_Array:
  8518. valid = true;
  8519. max_count = t->Array.count;
  8520. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8521. gbString str = expr_to_string(node);
  8522. error(node, "Cannot slice array '%s', value is not addressable", str);
  8523. gb_string_free(str);
  8524. o->mode = Addressing_Invalid;
  8525. o->expr = node;
  8526. return kind;
  8527. }
  8528. o->type = alloc_type_slice(t->Array.elem);
  8529. break;
  8530. case Type_MultiPointer:
  8531. valid = true;
  8532. o->type = type_deref(o->type);
  8533. break;
  8534. case Type_Slice:
  8535. valid = true;
  8536. o->type = type_deref(o->type);
  8537. break;
  8538. case Type_DynamicArray:
  8539. valid = true;
  8540. o->type = alloc_type_slice(t->DynamicArray.elem);
  8541. break;
  8542. case Type_Struct:
  8543. if (is_type_soa_struct(t)) {
  8544. valid = true;
  8545. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8546. }
  8547. break;
  8548. case Type_RelativeMultiPointer:
  8549. valid = true;
  8550. o->type = type_deref(o->type);
  8551. break;
  8552. case Type_EnumeratedArray:
  8553. {
  8554. gbString str = expr_to_string(o->expr);
  8555. gbString type_str = type_to_string(o->type);
  8556. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8557. gb_string_free(type_str);
  8558. gb_string_free(str);
  8559. o->mode = Addressing_Invalid;
  8560. o->expr = node;
  8561. return kind;
  8562. }
  8563. break;
  8564. }
  8565. if (!valid) {
  8566. gbString str = expr_to_string(o->expr);
  8567. gbString type_str = type_to_string(o->type);
  8568. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8569. gb_string_free(type_str);
  8570. gb_string_free(str);
  8571. o->mode = Addressing_Invalid;
  8572. o->expr = node;
  8573. return kind;
  8574. }
  8575. if (se->low == nullptr && se->high != nullptr) {
  8576. // It is okay to continue as it will assume the 1st index is zero
  8577. }
  8578. i64 indices[2] = {};
  8579. Ast *nodes[2] = {se->low, se->high};
  8580. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8581. i64 index = max_count;
  8582. if (nodes[i] != nullptr) {
  8583. i64 capacity = -1;
  8584. if (max_count >= 0) {
  8585. capacity = max_count;
  8586. }
  8587. i64 j = 0;
  8588. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8589. index = j;
  8590. }
  8591. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8592. } else if (i == 0) {
  8593. index = 0;
  8594. }
  8595. indices[i] = index;
  8596. }
  8597. for (isize i = 0; i < gb_count_of(indices); i++) {
  8598. i64 a = indices[i];
  8599. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8600. i64 b = indices[j];
  8601. if (a > b && b >= 0) {
  8602. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8603. }
  8604. }
  8605. }
  8606. if (max_count < 0) {
  8607. if (o->mode == Addressing_Constant) {
  8608. gbString s = expr_to_string(se->expr);
  8609. error(se->expr, "Cannot slice constant value '%s'", s);
  8610. gb_string_free(s);
  8611. }
  8612. }
  8613. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8614. /*
  8615. x[:] -> [^]T
  8616. x[i:] -> [^]T
  8617. x[:n] -> []T
  8618. x[i:n] -> []T
  8619. */
  8620. o->type = alloc_type_slice(t->MultiPointer.elem);
  8621. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  8622. /*
  8623. x[:] -> [^]T
  8624. x[i:] -> [^]T
  8625. x[:n] -> []T
  8626. x[i:n] -> []T
  8627. */
  8628. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  8629. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  8630. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  8631. }
  8632. o->mode = Addressing_Value;
  8633. if (is_type_string(t) && max_count >= 0) {
  8634. bool all_constant = true;
  8635. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8636. if (nodes[i] != nullptr) {
  8637. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8638. if (tav.mode != Addressing_Constant) {
  8639. all_constant = false;
  8640. break;
  8641. }
  8642. }
  8643. }
  8644. if (!all_constant) {
  8645. gbString str = expr_to_string(o->expr);
  8646. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8647. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8648. gb_string_free(str);
  8649. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8650. o->expr = node;
  8651. return kind;
  8652. }
  8653. String s = {};
  8654. if (o->value.kind == ExactValue_String) {
  8655. s = o->value.value_string;
  8656. }
  8657. o->mode = Addressing_Constant;
  8658. o->type = t;
  8659. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8660. }
  8661. return kind;
  8662. }
  8663. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8664. u32 prev_state_flags = c->state_flags;
  8665. defer (c->state_flags = prev_state_flags);
  8666. if (node->state_flags != 0) {
  8667. u32 in = node->state_flags;
  8668. u32 out = c->state_flags;
  8669. if (in & StateFlag_no_bounds_check) {
  8670. out |= StateFlag_no_bounds_check;
  8671. out &= ~StateFlag_bounds_check;
  8672. } else if (in & StateFlag_bounds_check) {
  8673. out |= StateFlag_bounds_check;
  8674. out &= ~StateFlag_no_bounds_check;
  8675. }
  8676. if (in & StateFlag_no_type_assert) {
  8677. out |= StateFlag_no_type_assert;
  8678. out &= ~StateFlag_type_assert;
  8679. } else if (in & StateFlag_type_assert) {
  8680. out |= StateFlag_type_assert;
  8681. out &= ~StateFlag_no_type_assert;
  8682. }
  8683. c->state_flags = out;
  8684. }
  8685. ExprKind kind = Expr_Stmt;
  8686. o->mode = Addressing_Invalid;
  8687. o->type = t_invalid;
  8688. o->value = {ExactValue_Invalid};
  8689. switch (node->kind) {
  8690. default:
  8691. return kind;
  8692. case_ast_node(be, BadExpr, node)
  8693. return kind;
  8694. case_end;
  8695. case_ast_node(i, Implicit, node)
  8696. switch (i->kind) {
  8697. case Token_context:
  8698. {
  8699. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8700. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8701. return kind;
  8702. }
  8703. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8704. c->scope->flags |= ScopeFlag_ContextDefined;
  8705. }
  8706. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8707. error(node, "'context' has not been defined within this scope");
  8708. // Continue with value
  8709. }
  8710. init_core_context(c->checker);
  8711. o->mode = Addressing_Context;
  8712. o->type = t_context;
  8713. }
  8714. break;
  8715. default:
  8716. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8717. return kind;
  8718. }
  8719. case_end;
  8720. case_ast_node(i, Ident, node);
  8721. check_ident(c, o, node, nullptr, type_hint, false);
  8722. case_end;
  8723. case_ast_node(u, Uninit, node);
  8724. o->mode = Addressing_Value;
  8725. o->type = t_untyped_uninit;
  8726. error(node, "Use of --- outside of variable declaration");
  8727. case_end;
  8728. case_ast_node(bl, BasicLit, node);
  8729. Type *t = t_invalid;
  8730. switch (node->tav.value.kind) {
  8731. case ExactValue_String: t = t_untyped_string; break;
  8732. case ExactValue_Float: t = t_untyped_float; break;
  8733. case ExactValue_Complex: t = t_untyped_complex; break;
  8734. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  8735. case ExactValue_Integer:
  8736. t = t_untyped_integer;
  8737. if (bl->token.kind == Token_Rune) {
  8738. t = t_untyped_rune;
  8739. }
  8740. break;
  8741. default:
  8742. GB_PANIC("Unhandled value type for basic literal");
  8743. break;
  8744. }
  8745. o->mode = Addressing_Constant;
  8746. o->type = t;
  8747. o->value = node->tav.value;
  8748. case_end;
  8749. case_ast_node(bd, BasicDirective, node);
  8750. kind = check_basic_directive_expr(c, o, node, type_hint);
  8751. case_end;
  8752. case_ast_node(pg, ProcGroup, node);
  8753. error(node, "Illegal use of a procedure group");
  8754. o->mode = Addressing_Invalid;
  8755. case_end;
  8756. case_ast_node(pl, ProcLit, node);
  8757. CheckerContext ctx = *c;
  8758. DeclInfo *decl = nullptr;
  8759. Type *type = alloc_type(Type_Proc);
  8760. check_open_scope(&ctx, pl->type);
  8761. {
  8762. decl = make_decl_info(ctx.scope, ctx.decl);
  8763. decl->proc_lit = node;
  8764. ctx.decl = decl;
  8765. defer (ctx.decl = ctx.decl->parent);
  8766. if (pl->tags != 0) {
  8767. error(node, "A procedure literal cannot have tags");
  8768. pl->tags = 0; // TODO(bill): Should I zero this?!
  8769. }
  8770. check_procedure_type(&ctx, type, pl->type);
  8771. if (!is_type_proc(type)) {
  8772. gbString str = expr_to_string(node);
  8773. error(node, "Invalid procedure literal '%s'", str);
  8774. gb_string_free(str);
  8775. check_close_scope(&ctx);
  8776. return kind;
  8777. }
  8778. if (pl->body == nullptr) {
  8779. error(node, "A procedure literal must have a body");
  8780. return kind;
  8781. }
  8782. pl->decl = decl;
  8783. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  8784. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  8785. array_add(&ctx.checker->nested_proc_lits, decl);
  8786. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  8787. }
  8788. check_close_scope(&ctx);
  8789. o->mode = Addressing_Value;
  8790. o->type = type;
  8791. case_end;
  8792. case_ast_node(te, TernaryIfExpr, node);
  8793. kind = check_ternary_if_expr(c, o, node, type_hint);
  8794. case_end;
  8795. case_ast_node(te, TernaryWhenExpr, node);
  8796. kind = check_ternary_when_expr(c, o, node, type_hint);
  8797. case_end;
  8798. case_ast_node(oe, OrElseExpr, node);
  8799. return check_or_else_expr(c, o, node, type_hint);
  8800. case_end;
  8801. case_ast_node(re, OrReturnExpr, node);
  8802. return check_or_return_expr(c, o, node, type_hint);
  8803. case_end;
  8804. case_ast_node(re, OrBranchExpr, node);
  8805. return check_or_branch_expr(c, o, node, type_hint);
  8806. case_end;
  8807. case_ast_node(cl, CompoundLit, node);
  8808. kind = check_compound_literal(c, o, node, type_hint);
  8809. case_end;
  8810. case_ast_node(pe, ParenExpr, node);
  8811. kind = check_expr_base(c, o, pe->expr, type_hint);
  8812. node->viral_state_flags |= pe->expr->viral_state_flags;
  8813. o->expr = node;
  8814. case_end;
  8815. case_ast_node(te, TagExpr, node);
  8816. String name = te->name.string;
  8817. error(node, "Unknown tag expression, #%.*s", LIT(name));
  8818. if (te->expr) {
  8819. kind = check_expr_base(c, o, te->expr, type_hint);
  8820. node->viral_state_flags |= te->expr->viral_state_flags;
  8821. }
  8822. o->expr = node;
  8823. case_end;
  8824. case_ast_node(ta, TypeAssertion, node);
  8825. kind = check_type_assertion(c, o, node, type_hint);
  8826. case_end;
  8827. case_ast_node(tc, TypeCast, node);
  8828. check_expr_or_type(c, o, tc->type);
  8829. if (o->mode != Addressing_Type) {
  8830. gbString str = expr_to_string(tc->type);
  8831. error(tc->type, "Expected a type, got %s", str);
  8832. gb_string_free(str);
  8833. o->mode = Addressing_Invalid;
  8834. }
  8835. if (o->mode == Addressing_Invalid) {
  8836. o->expr = node;
  8837. return kind;
  8838. }
  8839. Type *type = o->type;
  8840. check_expr_base(c, o, tc->expr, type);
  8841. node->viral_state_flags |= tc->expr->viral_state_flags;
  8842. if (o->mode != Addressing_Invalid) {
  8843. switch (tc->token.kind) {
  8844. case Token_transmute:
  8845. check_transmute(c, node, o, type);
  8846. break;
  8847. case Token_cast:
  8848. check_cast(c, o, type);
  8849. break;
  8850. default:
  8851. error(node, "Invalid AST: Invalid casting expression");
  8852. o->mode = Addressing_Invalid;
  8853. break;
  8854. }
  8855. }
  8856. return Expr_Expr;
  8857. case_end;
  8858. case_ast_node(ac, AutoCast, node);
  8859. check_expr_base(c, o, ac->expr, type_hint);
  8860. node->viral_state_flags |= ac->expr->viral_state_flags;
  8861. if (o->mode == Addressing_Invalid) {
  8862. o->expr = node;
  8863. return kind;
  8864. }
  8865. if (type_hint) {
  8866. check_cast(c, o, type_hint);
  8867. }
  8868. o->expr = node;
  8869. return Expr_Expr;
  8870. case_end;
  8871. case_ast_node(ue, UnaryExpr, node);
  8872. Type *th = type_hint;
  8873. if (ue->op.kind == Token_And) {
  8874. th = type_deref(th);
  8875. }
  8876. check_expr_base(c, o, ue->expr, th);
  8877. node->viral_state_flags |= ue->expr->viral_state_flags;
  8878. if (o->mode != Addressing_Invalid) {
  8879. check_unary_expr(c, o, ue->op, node);
  8880. }
  8881. o->expr = node;
  8882. return Expr_Expr;
  8883. case_end;
  8884. case_ast_node(be, BinaryExpr, node);
  8885. check_binary_expr(c, o, node, type_hint, true);
  8886. if (o->mode == Addressing_Invalid) {
  8887. o->expr = node;
  8888. return kind;
  8889. }
  8890. case_end;
  8891. case_ast_node(se, SelectorExpr, node);
  8892. check_selector(c, o, node, type_hint);
  8893. node->viral_state_flags |= se->expr->viral_state_flags;
  8894. case_end;
  8895. case_ast_node(se, SelectorCallExpr, node);
  8896. return check_selector_call_expr(c, o, node, type_hint);
  8897. case_end;
  8898. case_ast_node(ise, ImplicitSelectorExpr, node);
  8899. return check_implicit_selector_expr(c, o, node, type_hint);
  8900. case_end;
  8901. case_ast_node(ie, IndexExpr, node);
  8902. kind = check_index_expr(c, o, node, type_hint);
  8903. case_end;
  8904. case_ast_node(se, SliceExpr, node);
  8905. kind = check_slice_expr(c, o, node, type_hint);
  8906. case_end;
  8907. case_ast_node(mie, MatrixIndexExpr, node);
  8908. check_matrix_index_expr(c, o, node, type_hint);
  8909. o->expr = node;
  8910. return Expr_Expr;
  8911. case_end;
  8912. case_ast_node(ce, CallExpr, node);
  8913. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  8914. case_end;
  8915. case_ast_node(de, DerefExpr, node);
  8916. check_expr_or_type(c, o, de->expr);
  8917. node->viral_state_flags |= de->expr->viral_state_flags;
  8918. if (o->mode == Addressing_Invalid) {
  8919. o->mode = Addressing_Invalid;
  8920. o->expr = node;
  8921. return kind;
  8922. } else {
  8923. Type *t = base_type(o->type);
  8924. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  8925. o->mode = Addressing_Variable;
  8926. o->type = t->Pointer.elem;
  8927. } else if (t->kind == Type_SoaPointer) {
  8928. o->mode = Addressing_SoaVariable;
  8929. o->type = type_deref(t);
  8930. } else if (t->kind == Type_RelativePointer) {
  8931. if (o->mode != Addressing_Variable) {
  8932. gbString str = expr_to_string(o->expr);
  8933. gbString typ = type_to_string(o->type);
  8934. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  8935. gb_string_free(typ);
  8936. gb_string_free(str);
  8937. }
  8938. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  8939. add_type_info_type(c, o->type);
  8940. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  8941. GB_ASSERT(ptr_type->kind == Type_Pointer);
  8942. o->mode = Addressing_Variable;
  8943. o->type = ptr_type->Pointer.elem;
  8944. } else {
  8945. gbString str = expr_to_string(o->expr);
  8946. gbString typ = type_to_string(o->type);
  8947. begin_error_block();
  8948. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  8949. if (o->type && is_type_multi_pointer(o->type)) {
  8950. error_line("\tDid you mean '%s[0]'?\n", str);
  8951. }
  8952. end_error_block();
  8953. gb_string_free(typ);
  8954. gb_string_free(str);
  8955. o->mode = Addressing_Invalid;
  8956. o->expr = node;
  8957. return kind;
  8958. }
  8959. }
  8960. case_end;
  8961. case_ast_node(ia, InlineAsmExpr, node);
  8962. if (c->curr_proc_decl == nullptr) {
  8963. error(node, "Inline asm expressions are only allowed within a procedure body");
  8964. }
  8965. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  8966. Type *return_type = nullptr;
  8967. for_array(i, ia->param_types) {
  8968. param_types[i] = check_type(c, ia->param_types[i]);
  8969. }
  8970. if (ia->return_type != nullptr) {
  8971. return_type = check_type(c, ia->return_type);
  8972. }
  8973. Operand x = {};
  8974. check_expr(c, &x, ia->asm_string);
  8975. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8976. error(x.expr, "Expected a constant string for the inline asm main parameter");
  8977. }
  8978. check_expr(c, &x, ia->constraints_string);
  8979. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8980. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  8981. }
  8982. Scope *scope = create_scope(c->info, c->scope);
  8983. scope->flags |= ScopeFlag_Proc;
  8984. Type *params = alloc_type_tuple();
  8985. Type *results = alloc_type_tuple();
  8986. if (param_types.count != 0) {
  8987. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  8988. for_array(i, param_types) {
  8989. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  8990. }
  8991. }
  8992. if (return_type != nullptr) {
  8993. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  8994. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  8995. }
  8996. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  8997. o->type = pt;
  8998. o->mode = Addressing_Value;
  8999. o->expr = node;
  9000. return Expr_Expr;
  9001. case_end;
  9002. case Ast_TypeidType:
  9003. case Ast_PolyType:
  9004. case Ast_ProcType:
  9005. case Ast_PointerType:
  9006. case Ast_MultiPointerType:
  9007. case Ast_ArrayType:
  9008. case Ast_DynamicArrayType:
  9009. case Ast_StructType:
  9010. case Ast_UnionType:
  9011. case Ast_EnumType:
  9012. case Ast_MapType:
  9013. case Ast_BitSetType:
  9014. case Ast_MatrixType:
  9015. case Ast_RelativeType:
  9016. o->mode = Addressing_Type;
  9017. o->type = check_type(c, node);
  9018. break;
  9019. }
  9020. kind = Expr_Expr;
  9021. o->expr = node;
  9022. return kind;
  9023. }
  9024. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9025. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9026. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9027. o->type = t_invalid;
  9028. gbString xs = expr_to_string(o->expr);
  9029. if (o->mode == Addressing_Type) {
  9030. error(o->expr, "Invalid type usage '%s'", xs);
  9031. } else {
  9032. error(o->expr, "Invalid expression '%s'", xs);
  9033. }
  9034. gb_string_free(xs);
  9035. }
  9036. if (o->type != nullptr && is_type_untyped(o->type)) {
  9037. add_untyped(c, node, o->mode, o->type, o->value);
  9038. }
  9039. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9040. add_type_and_value(c, node, o->mode, o->type, o->value);
  9041. return kind;
  9042. }
  9043. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9044. check_expr_base(c, o, e, nullptr);
  9045. switch (o->mode) {
  9046. default:
  9047. return; // NOTE(bill): Valid
  9048. case Addressing_NoValue:
  9049. error_operand_no_value(o);
  9050. break;
  9051. }
  9052. o->mode = Addressing_Invalid;
  9053. }
  9054. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9055. check_expr_base(c, o, e, nullptr);
  9056. switch (o->mode) {
  9057. default:
  9058. return; // NOTE(bill): Valid
  9059. case Addressing_NoValue:
  9060. error_operand_no_value(o);
  9061. break;
  9062. case Addressing_Type:
  9063. error_operand_not_expression(o);
  9064. break;
  9065. }
  9066. o->mode = Addressing_Invalid;
  9067. }
  9068. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9069. check_expr_base(c, o, e, type_hint);
  9070. switch (o->mode) {
  9071. default:
  9072. return; // NOTE(bill): Valid
  9073. case Addressing_NoValue:
  9074. error_operand_no_value(o);
  9075. break;
  9076. case Addressing_Type:
  9077. error_operand_not_expression(o);
  9078. break;
  9079. }
  9080. o->mode = Addressing_Invalid;
  9081. }
  9082. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9083. if (o->mode == Addressing_Value) {
  9084. // NOTE(bill): Tuples are not first class thus never named
  9085. if (o->type->kind == Type_Tuple) {
  9086. isize count = o->type->Tuple.variables.count;
  9087. error(o->expr,
  9088. "%td-valued expression found where single value expected", count);
  9089. o->mode = Addressing_Invalid;
  9090. GB_ASSERT(count != 1);
  9091. }
  9092. }
  9093. }
  9094. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9095. check_multi_expr(c, o, e);
  9096. check_not_tuple(c, o);
  9097. }
  9098. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9099. check_expr_base(c, o, e, type_hint);
  9100. check_not_tuple(c, o);
  9101. error_operand_no_value(o);
  9102. }
  9103. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9104. switch (v.kind) {
  9105. case ExactValue_Invalid:
  9106. return true;
  9107. case ExactValue_Bool:
  9108. return !v.value_bool;
  9109. case ExactValue_String:
  9110. return v.value_string.len == 0;
  9111. case ExactValue_Integer:
  9112. return big_int_is_zero(&v.value_integer);
  9113. case ExactValue_Float:
  9114. return v.value_float == 0.0;
  9115. case ExactValue_Complex:
  9116. if (v.value_complex) {
  9117. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9118. }
  9119. return true;
  9120. case ExactValue_Quaternion:
  9121. if (v.value_quaternion) {
  9122. return v.value_quaternion->real == 0.0 &&
  9123. v.value_quaternion->imag == 0.0 &&
  9124. v.value_quaternion->jmag == 0.0 &&
  9125. v.value_quaternion->kmag == 0.0;
  9126. }
  9127. return true;
  9128. case ExactValue_Pointer:
  9129. return v.value_pointer == 0;
  9130. case ExactValue_Compound:
  9131. if (v.value_compound == nullptr) {
  9132. return true;
  9133. } else {
  9134. ast_node(cl, CompoundLit, v.value_compound);
  9135. if (cl->elems.count == 0) {
  9136. return true;
  9137. } else {
  9138. for (Ast *elem : cl->elems) {
  9139. if (elem->tav.mode != Addressing_Constant) {
  9140. return false;
  9141. }
  9142. if (!is_exact_value_zero(elem->tav.value)) {
  9143. return false;
  9144. }
  9145. }
  9146. return true;
  9147. }
  9148. }
  9149. case ExactValue_Procedure:
  9150. return v.value_procedure == nullptr;
  9151. case ExactValue_Typeid:
  9152. return v.value_typeid == nullptr;
  9153. }
  9154. return true;
  9155. }
  9156. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9157. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9158. for_array(i, params) {
  9159. if (i > 0) {
  9160. str = gb_string_appendc(str, ", ");
  9161. }
  9162. str = write_expr_to_string(str, params[i], false);
  9163. }
  9164. return str;
  9165. }
  9166. gb_internal gbString string_append_string(gbString str, String string) {
  9167. if (string.len > 0) {
  9168. return gb_string_append_length(str, &string[0], string.len);
  9169. }
  9170. return str;
  9171. }
  9172. gb_internal gbString string_append_token(gbString str, Token token) {
  9173. str = string_append_string(str, token.string);
  9174. return str;
  9175. }
  9176. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9177. if (node == nullptr)
  9178. return str;
  9179. if (is_ast_stmt(node)) {
  9180. GB_ASSERT("stmt passed to write_expr_to_string");
  9181. }
  9182. switch (node->kind) {
  9183. default:
  9184. str = gb_string_appendc(str, "(BadExpr)");
  9185. break;
  9186. case_ast_node(i, Ident, node);
  9187. str = string_append_token(str, i->token);
  9188. case_end;
  9189. case_ast_node(i, Implicit, node);
  9190. str = string_append_token(str, *i);
  9191. case_end;
  9192. case_ast_node(bl, BasicLit, node);
  9193. str = string_append_token(str, bl->token);
  9194. case_end;
  9195. case_ast_node(bd, BasicDirective, node);
  9196. str = gb_string_append_rune(str, '#');
  9197. str = string_append_string(str, bd->name.string);
  9198. case_end;
  9199. case_ast_node(ud, Uninit, node);
  9200. str = gb_string_appendc(str, "---");
  9201. case_end;
  9202. case_ast_node(pg, ProcGroup, node);
  9203. str = gb_string_appendc(str, "proc{");
  9204. for_array(i, pg->args) {
  9205. if (i > 0) str = gb_string_appendc(str, ", ");
  9206. str = write_expr_to_string(str, pg->args[i], shorthand);
  9207. }
  9208. str = gb_string_append_rune(str, '}');
  9209. case_end;
  9210. case_ast_node(pl, ProcLit, node);
  9211. str = write_expr_to_string(str, pl->type, shorthand);
  9212. if (pl->body) {
  9213. str = gb_string_appendc(str, " {...}");
  9214. } else {
  9215. str = gb_string_appendc(str, " ---");
  9216. }
  9217. case_end;
  9218. case_ast_node(cl, CompoundLit, node);
  9219. str = write_expr_to_string(str, cl->type, shorthand);
  9220. str = gb_string_append_rune(str, '{');
  9221. if (shorthand) {
  9222. str = gb_string_appendc(str, "...");
  9223. } else {
  9224. for_array(i, cl->elems) {
  9225. if (i > 0) str = gb_string_appendc(str, ", ");
  9226. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9227. }
  9228. }
  9229. str = gb_string_append_rune(str, '}');
  9230. case_end;
  9231. case_ast_node(te, TagExpr, node);
  9232. str = gb_string_append_rune(str, '#');
  9233. str = string_append_token(str, te->name);
  9234. str = write_expr_to_string(str, te->expr, shorthand);
  9235. case_end;
  9236. case_ast_node(ue, UnaryExpr, node);
  9237. str = string_append_token(str, ue->op);
  9238. str = write_expr_to_string(str, ue->expr, shorthand);
  9239. case_end;
  9240. case_ast_node(de, DerefExpr, node);
  9241. str = write_expr_to_string(str, de->expr, shorthand);
  9242. str = gb_string_append_rune(str, '^');
  9243. case_end;
  9244. case_ast_node(be, BinaryExpr, node);
  9245. str = write_expr_to_string(str, be->left, shorthand);
  9246. str = gb_string_append_rune(str, ' ');
  9247. str = string_append_token(str, be->op);
  9248. str = gb_string_append_rune(str, ' ');
  9249. str = write_expr_to_string(str, be->right, shorthand);
  9250. case_end;
  9251. case_ast_node(te, TernaryIfExpr, node);
  9252. TokenPos x = ast_token(te->x).pos;
  9253. TokenPos cond = ast_token(te->cond).pos;
  9254. if (x < cond) {
  9255. str = write_expr_to_string(str, te->x, shorthand);
  9256. str = gb_string_appendc(str, " if ");
  9257. str = write_expr_to_string(str, te->cond, shorthand);
  9258. str = gb_string_appendc(str, " else ");
  9259. str = write_expr_to_string(str, te->y, shorthand);
  9260. } else {
  9261. str = write_expr_to_string(str, te->cond, shorthand);
  9262. str = gb_string_appendc(str, " ? ");
  9263. str = write_expr_to_string(str, te->x, shorthand);
  9264. str = gb_string_appendc(str, " : ");
  9265. str = write_expr_to_string(str, te->y, shorthand);
  9266. }
  9267. case_end;
  9268. case_ast_node(te, TernaryWhenExpr, node);
  9269. str = write_expr_to_string(str, te->x, shorthand);
  9270. str = gb_string_appendc(str, " when ");
  9271. str = write_expr_to_string(str, te->cond, shorthand);
  9272. str = gb_string_appendc(str, " else ");
  9273. str = write_expr_to_string(str, te->y, shorthand);
  9274. case_end;
  9275. case_ast_node(oe, OrElseExpr, node);
  9276. str = write_expr_to_string(str, oe->x, shorthand);
  9277. str = gb_string_appendc(str, " or_else ");
  9278. str = write_expr_to_string(str, oe->y, shorthand);
  9279. case_end;
  9280. case_ast_node(oe, OrReturnExpr, node);
  9281. str = write_expr_to_string(str, oe->expr, shorthand);
  9282. str = gb_string_appendc(str, " or_return");
  9283. case_end;
  9284. case_ast_node(oe, OrBranchExpr, node);
  9285. str = write_expr_to_string(str, oe->expr, shorthand);
  9286. str = gb_string_append_rune(str, ' ');
  9287. str = string_append_token(str, oe->token);
  9288. if (oe->label) {
  9289. str = gb_string_append_rune(str, ' ');
  9290. str = write_expr_to_string(str, oe->label, shorthand);
  9291. }
  9292. case_end;
  9293. case_ast_node(pe, ParenExpr, node);
  9294. str = gb_string_append_rune(str, '(');
  9295. str = write_expr_to_string(str, pe->expr, shorthand);
  9296. str = gb_string_append_rune(str, ')');
  9297. case_end;
  9298. case_ast_node(se, SelectorExpr, node);
  9299. str = write_expr_to_string(str, se->expr, shorthand);
  9300. str = string_append_token(str, se->token);
  9301. str = write_expr_to_string(str, se->selector, shorthand);
  9302. case_end;
  9303. case_ast_node(se, ImplicitSelectorExpr, node);
  9304. str = gb_string_append_rune(str, '.');
  9305. str = write_expr_to_string(str, se->selector, shorthand);
  9306. case_end;
  9307. case_ast_node(se, SelectorCallExpr, node);
  9308. str = write_expr_to_string(str, se->expr, shorthand);
  9309. str = gb_string_appendc(str, "(");
  9310. ast_node(ce, CallExpr, se->call);
  9311. isize start = se->modified_call ? 1 : 0;
  9312. for (isize i = start; i < ce->args.count; i++) {
  9313. Ast *arg = ce->args[i];
  9314. if (i > start) {
  9315. str = gb_string_appendc(str, ", ");
  9316. }
  9317. str = write_expr_to_string(str, arg, shorthand);
  9318. }
  9319. str = gb_string_appendc(str, ")");
  9320. case_end;
  9321. case_ast_node(ta, TypeAssertion, node);
  9322. str = write_expr_to_string(str, ta->expr, shorthand);
  9323. if (ta->type != nullptr &&
  9324. ta->type->kind == Ast_UnaryExpr &&
  9325. ta->type->UnaryExpr.op.kind == Token_Question) {
  9326. str = gb_string_appendc(str, ".?");
  9327. } else {
  9328. str = gb_string_appendc(str, ".(");
  9329. str = write_expr_to_string(str, ta->type, shorthand);
  9330. str = gb_string_append_rune(str, ')');
  9331. }
  9332. case_end;
  9333. case_ast_node(tc, TypeCast, node);
  9334. str = string_append_token(str, tc->token);
  9335. str = gb_string_append_rune(str, '(');
  9336. str = write_expr_to_string(str, tc->type, shorthand);
  9337. str = gb_string_append_rune(str, ')');
  9338. str = write_expr_to_string(str, tc->expr, shorthand);
  9339. case_end;
  9340. case_ast_node(ac, AutoCast, node);
  9341. str = string_append_token(str, ac->token);
  9342. str = gb_string_append_rune(str, ' ');
  9343. str = write_expr_to_string(str, ac->expr, shorthand);
  9344. case_end;
  9345. case_ast_node(ie, IndexExpr, node);
  9346. str = write_expr_to_string(str, ie->expr, shorthand);
  9347. str = gb_string_append_rune(str, '[');
  9348. str = write_expr_to_string(str, ie->index, shorthand);
  9349. str = gb_string_append_rune(str, ']');
  9350. case_end;
  9351. case_ast_node(se, SliceExpr, node);
  9352. str = write_expr_to_string(str, se->expr, shorthand);
  9353. str = gb_string_append_rune(str, '[');
  9354. str = write_expr_to_string(str, se->low, shorthand);
  9355. str = string_append_token(str, se->interval);
  9356. str = write_expr_to_string(str, se->high, shorthand);
  9357. str = gb_string_append_rune(str, ']');
  9358. case_end;
  9359. case_ast_node(mie, MatrixIndexExpr, node);
  9360. str = write_expr_to_string(str, mie->expr, shorthand);
  9361. str = gb_string_append_rune(str, '[');
  9362. str = write_expr_to_string(str, mie->row_index, shorthand);
  9363. str = gb_string_appendc(str, ", ");
  9364. str = write_expr_to_string(str, mie->column_index, shorthand);
  9365. str = gb_string_append_rune(str, ']');
  9366. case_end;
  9367. case_ast_node(e, Ellipsis, node);
  9368. str = gb_string_appendc(str, "..");
  9369. str = write_expr_to_string(str, e->expr, shorthand);
  9370. case_end;
  9371. case_ast_node(fv, FieldValue, node);
  9372. str = write_expr_to_string(str, fv->field, shorthand);
  9373. str = gb_string_appendc(str, " = ");
  9374. str = write_expr_to_string(str, fv->value, shorthand);
  9375. case_end;
  9376. case_ast_node(fv, EnumFieldValue, node);
  9377. str = write_expr_to_string(str, fv->name, shorthand);
  9378. if (fv->value) {
  9379. str = gb_string_appendc(str, " = ");
  9380. str = write_expr_to_string(str, fv->value, shorthand);
  9381. }
  9382. case_end;
  9383. case_ast_node(ht, HelperType, node);
  9384. str = gb_string_appendc(str, "#type ");
  9385. str = write_expr_to_string(str, ht->type, shorthand);
  9386. case_end;
  9387. case_ast_node(ht, DistinctType, node);
  9388. str = gb_string_appendc(str, "distinct ");
  9389. str = write_expr_to_string(str, ht->type, shorthand);
  9390. case_end;
  9391. case_ast_node(pt, PolyType, node);
  9392. str = gb_string_append_rune(str, '$');
  9393. str = write_expr_to_string(str, pt->type, shorthand);
  9394. if (pt->specialization != nullptr) {
  9395. str = gb_string_append_rune(str, '/');
  9396. str = write_expr_to_string(str, pt->specialization, shorthand);
  9397. }
  9398. case_end;
  9399. case_ast_node(pt, PointerType, node);
  9400. str = gb_string_append_rune(str, '^');
  9401. str = write_expr_to_string(str, pt->type, shorthand);
  9402. case_end;
  9403. case_ast_node(pt, MultiPointerType, node);
  9404. str = gb_string_appendc(str, "[^]");
  9405. str = write_expr_to_string(str, pt->type, shorthand);
  9406. case_end;
  9407. case_ast_node(at, ArrayType, node);
  9408. str = gb_string_append_rune(str, '[');
  9409. if (at->count != nullptr &&
  9410. at->count->kind == Ast_UnaryExpr &&
  9411. at->count->UnaryExpr.op.kind == Token_Question) {
  9412. str = gb_string_appendc(str, "?");
  9413. } else {
  9414. str = write_expr_to_string(str, at->count, shorthand);
  9415. }
  9416. str = gb_string_append_rune(str, ']');
  9417. str = write_expr_to_string(str, at->elem, shorthand);
  9418. case_end;
  9419. case_ast_node(at, DynamicArrayType, node);
  9420. str = gb_string_appendc(str, "[dynamic]");
  9421. str = write_expr_to_string(str, at->elem, shorthand);
  9422. case_end;
  9423. case_ast_node(bs, BitSetType, node);
  9424. str = gb_string_appendc(str, "bit_set[");
  9425. str = write_expr_to_string(str, bs->elem, shorthand);
  9426. str = gb_string_appendc(str, "]");
  9427. case_end;
  9428. case_ast_node(mt, MapType, node);
  9429. str = gb_string_appendc(str, "map[");
  9430. str = write_expr_to_string(str, mt->key, shorthand);
  9431. str = gb_string_append_rune(str, ']');
  9432. str = write_expr_to_string(str, mt->value, shorthand);
  9433. case_end;
  9434. case_ast_node(mt, MatrixType, node);
  9435. str = gb_string_appendc(str, "matrix[");
  9436. str = write_expr_to_string(str, mt->row_count, shorthand);
  9437. str = gb_string_appendc(str, ", ");
  9438. str = write_expr_to_string(str, mt->column_count, shorthand);
  9439. str = gb_string_append_rune(str, ']');
  9440. str = write_expr_to_string(str, mt->elem, shorthand);
  9441. case_end;
  9442. case_ast_node(f, Field, node);
  9443. if (f->flags&FieldFlag_using) {
  9444. str = gb_string_appendc(str, "using ");
  9445. }
  9446. if (f->flags&FieldFlag_no_alias) {
  9447. str = gb_string_appendc(str, "#no_alias ");
  9448. }
  9449. if (f->flags&FieldFlag_c_vararg) {
  9450. str = gb_string_appendc(str, "#c_vararg ");
  9451. }
  9452. if (f->flags&FieldFlag_any_int) {
  9453. str = gb_string_appendc(str, "#any_int ");
  9454. }
  9455. if (f->flags&FieldFlag_const) {
  9456. str = gb_string_appendc(str, "#const ");
  9457. }
  9458. if (f->flags&FieldFlag_subtype) {
  9459. str = gb_string_appendc(str, "#subtype ");
  9460. }
  9461. for_array(i, f->names) {
  9462. Ast *name = f->names[i];
  9463. if (i > 0) str = gb_string_appendc(str, ", ");
  9464. str = write_expr_to_string(str, name, shorthand);
  9465. }
  9466. if (f->names.count > 0) {
  9467. if (f->type == nullptr && f->default_value != nullptr) {
  9468. str = gb_string_append_rune(str, ' ');
  9469. }
  9470. str = gb_string_appendc(str, ":");
  9471. }
  9472. if (f->type != nullptr) {
  9473. str = gb_string_append_rune(str, ' ');
  9474. str = write_expr_to_string(str, f->type, shorthand);
  9475. }
  9476. if (f->default_value != nullptr) {
  9477. if (f->type != nullptr) {
  9478. str = gb_string_append_rune(str, ' ');
  9479. }
  9480. str = gb_string_appendc(str, "= ");
  9481. str = write_expr_to_string(str, f->default_value, shorthand);
  9482. }
  9483. case_end;
  9484. case_ast_node(f, FieldList, node);
  9485. bool has_name = false;
  9486. for_array(i, f->list) {
  9487. ast_node(field, Field, f->list[i]);
  9488. if (field->names.count > 1) {
  9489. has_name = true;
  9490. break;
  9491. }
  9492. if (field->names.count == 0) {
  9493. continue;
  9494. }
  9495. if (!is_blank_ident(field->names[0])) {
  9496. has_name = true;
  9497. break;
  9498. }
  9499. }
  9500. for_array(i, f->list) {
  9501. if (i > 0) str = gb_string_appendc(str, ", ");
  9502. if (has_name) {
  9503. str = write_expr_to_string(str, f->list[i], shorthand);
  9504. } else {
  9505. ast_node(field, Field, f->list[i]);
  9506. if (field->flags&FieldFlag_using) {
  9507. str = gb_string_appendc(str, "using ");
  9508. }
  9509. if (field->flags&FieldFlag_no_alias) {
  9510. str = gb_string_appendc(str, "#no_alias ");
  9511. }
  9512. if (field->flags&FieldFlag_c_vararg) {
  9513. str = gb_string_appendc(str, "#c_vararg ");
  9514. }
  9515. str = write_expr_to_string(str, field->type, shorthand);
  9516. }
  9517. }
  9518. case_end;
  9519. case_ast_node(ce, CallExpr, node);
  9520. switch (ce->inlining) {
  9521. case ProcInlining_inline:
  9522. str = gb_string_appendc(str, "#force_inline ");
  9523. break;
  9524. case ProcInlining_no_inline:
  9525. str = gb_string_appendc(str, "#force_no_inline ");
  9526. break;
  9527. }
  9528. str = write_expr_to_string(str, ce->proc, shorthand);
  9529. str = gb_string_appendc(str, "(");
  9530. isize idx0 = cast(isize)ce->was_selector;
  9531. for (isize i = idx0; i < ce->args.count; i++) {
  9532. Ast *arg = ce->args[i];
  9533. if (i > idx0) {
  9534. str = gb_string_appendc(str, ", ");
  9535. }
  9536. str = write_expr_to_string(str, arg, shorthand);
  9537. }
  9538. str = gb_string_appendc(str, ")");
  9539. case_end;
  9540. case_ast_node(tt, TypeidType, node);
  9541. str = gb_string_appendc(str, "typeid");
  9542. if (tt->specialization) {
  9543. str = gb_string_appendc(str, "/");
  9544. str = write_expr_to_string(str, tt->specialization, shorthand);
  9545. }
  9546. case_end;
  9547. case_ast_node(pt, ProcType, node);
  9548. str = gb_string_appendc(str, "proc(");
  9549. str = write_expr_to_string(str, pt->params, shorthand);
  9550. str = gb_string_appendc(str, ")");
  9551. if (pt->results != nullptr) {
  9552. str = gb_string_appendc(str, " -> ");
  9553. bool parens_needed = false;
  9554. if (pt->results && pt->results->kind == Ast_FieldList) {
  9555. for (Ast *field : pt->results->FieldList.list) {
  9556. ast_node(f, Field, field);
  9557. if (f->names.count != 0) {
  9558. parens_needed = true;
  9559. break;
  9560. }
  9561. }
  9562. }
  9563. if (parens_needed) {
  9564. str = gb_string_append_rune(str, '(');
  9565. }
  9566. str = write_expr_to_string(str, pt->results, shorthand);
  9567. if (parens_needed) {
  9568. str = gb_string_append_rune(str, ')');
  9569. }
  9570. }
  9571. case_end;
  9572. case_ast_node(st, StructType, node);
  9573. str = gb_string_appendc(str, "struct ");
  9574. if (st->polymorphic_params) {
  9575. str = gb_string_append_rune(str, '(');
  9576. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9577. str = gb_string_appendc(str, ") ");
  9578. }
  9579. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9580. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9581. if (st->align) {
  9582. str = gb_string_appendc(str, "#align ");
  9583. str = write_expr_to_string(str, st->align, shorthand);
  9584. str = gb_string_append_rune(str, ' ');
  9585. }
  9586. str = gb_string_append_rune(str, '{');
  9587. if (shorthand) {
  9588. str = gb_string_appendc(str, "...");
  9589. } else {
  9590. str = write_struct_fields_to_string(str, st->fields);
  9591. }
  9592. str = gb_string_append_rune(str, '}');
  9593. case_end;
  9594. case_ast_node(st, UnionType, node);
  9595. str = gb_string_appendc(str, "union ");
  9596. if (st->polymorphic_params) {
  9597. str = gb_string_append_rune(str, '(');
  9598. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9599. str = gb_string_appendc(str, ") ");
  9600. }
  9601. switch (st->kind) {
  9602. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9603. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9604. }
  9605. if (st->align) {
  9606. str = gb_string_appendc(str, "#align ");
  9607. str = write_expr_to_string(str, st->align, shorthand);
  9608. str = gb_string_append_rune(str, ' ');
  9609. }
  9610. str = gb_string_append_rune(str, '{');
  9611. if (shorthand) {
  9612. str = gb_string_appendc(str, "...");
  9613. } else {
  9614. str = write_struct_fields_to_string(str, st->variants);
  9615. }
  9616. str = gb_string_append_rune(str, '}');
  9617. case_end;
  9618. case_ast_node(et, EnumType, node);
  9619. str = gb_string_appendc(str, "enum ");
  9620. if (et->base_type != nullptr) {
  9621. str = write_expr_to_string(str, et->base_type, shorthand);
  9622. str = gb_string_append_rune(str, ' ');
  9623. }
  9624. str = gb_string_append_rune(str, '{');
  9625. if (shorthand) {
  9626. str = gb_string_appendc(str, "...");
  9627. } else {
  9628. for_array(i, et->fields) {
  9629. if (i > 0) {
  9630. str = gb_string_appendc(str, ", ");
  9631. }
  9632. str = write_expr_to_string(str, et->fields[i], shorthand);
  9633. }
  9634. }
  9635. str = gb_string_append_rune(str, '}');
  9636. case_end;
  9637. case_ast_node(rt, RelativeType, node);
  9638. str = write_expr_to_string(str, rt->tag, shorthand);
  9639. str = gb_string_appendc(str, "" );
  9640. str = write_expr_to_string(str, rt->type, shorthand);
  9641. case_end;
  9642. case_ast_node(ia, InlineAsmExpr, node);
  9643. str = gb_string_appendc(str, "asm(");
  9644. for_array(i, ia->param_types) {
  9645. if (i > 0) {
  9646. str = gb_string_appendc(str, ", ");
  9647. }
  9648. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9649. }
  9650. str = gb_string_appendc(str, ")");
  9651. if (ia->return_type != nullptr) {
  9652. str = gb_string_appendc(str, " -> ");
  9653. str = write_expr_to_string(str, ia->return_type, shorthand);
  9654. }
  9655. if (ia->has_side_effects) {
  9656. str = gb_string_appendc(str, " #side_effects");
  9657. }
  9658. if (ia->is_align_stack) {
  9659. str = gb_string_appendc(str, " #stack_align");
  9660. }
  9661. if (ia->dialect) {
  9662. str = gb_string_appendc(str, " #");
  9663. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9664. }
  9665. str = gb_string_appendc(str, " {");
  9666. if (shorthand) {
  9667. str = gb_string_appendc(str, "...");
  9668. } else {
  9669. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9670. str = gb_string_appendc(str, ", ");
  9671. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9672. }
  9673. str = gb_string_appendc(str, "}");
  9674. case_end;
  9675. }
  9676. return str;
  9677. }
  9678. gb_internal gbString expr_to_string(Ast *expression) {
  9679. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9680. }
  9681. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  9682. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  9683. }
  9684. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  9685. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9686. }