check_expr.cpp 313 KB

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