check_expr.cpp 359 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280
  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 void check_not_tuple (CheckerContext *c, Operand *operand);
  73. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gb_internal gbString expr_to_string (Ast *expression);
  75. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  76. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. gb_internal bool check_is_terminating (Ast *node, String const &label);
  78. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  84. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  89. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  90. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  91. gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
  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_, bool change_operand=true);
  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. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  103. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  104. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  105. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y);
  106. gb_internal bool is_exact_value_zero(ExactValue const &v);
  107. enum LoadDirectiveResult {
  108. LoadDirective_Success = 0,
  109. LoadDirective_Error = 1,
  110. LoadDirective_NotFound = 2,
  111. };
  112. gb_internal bool is_load_directive_call(Ast *call) {
  113. call = unparen_expr(call);
  114. if (call->kind != Ast_CallExpr) {
  115. return false;
  116. }
  117. ast_node(ce, CallExpr, call);
  118. if (ce->proc->kind != Ast_BasicDirective) {
  119. return false;
  120. }
  121. ast_node(bd, BasicDirective, ce->proc);
  122. String name = bd->name.string;
  123. return name == "load";
  124. }
  125. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  126. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  127. auto results = did_you_mean_results(d);
  128. if (results.count != 0) {
  129. error_line("\tSuggestion: Did you mean?\n");
  130. for (auto const &result : results) {
  131. String const &target = result.target;
  132. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  133. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  134. }
  135. }
  136. }
  137. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  138. if (e->kind != Entity_TypeName) {
  139. return;
  140. }
  141. if (e->TypeName.objc_metadata == nullptr) {
  142. return;
  143. }
  144. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  145. Type *t = base_type(e->type);
  146. GB_ASSERT(t->kind == Type_Struct);
  147. if (is_type) {
  148. for (auto const &entry : objc_metadata->type_entries) {
  149. string_set_add(set, entry.name);
  150. }
  151. } else {
  152. for (auto const &entry : objc_metadata->value_entries) {
  153. string_set_add(set, entry.name);
  154. }
  155. }
  156. for (Entity *f : t->Struct.fields) {
  157. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  158. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  159. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  160. }
  161. }
  162. }
  163. }
  164. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  165. if (build_context.terse_errors) { return; }
  166. ERROR_BLOCK();
  167. GB_ASSERT(e->kind == Entity_TypeName);
  168. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  169. auto *objc_metadata = e->TypeName.objc_metadata;
  170. MUTEX_GUARD(objc_metadata->mutex);
  171. StringSet set = {};
  172. defer (string_set_destroy(&set));
  173. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  174. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  175. defer (did_you_mean_destroy(&d));
  176. for (String const &target : set) {
  177. did_you_mean_append(&d, target);
  178. }
  179. check_did_you_mean_print(&d, prefix);
  180. }
  181. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  182. if (build_context.terse_errors) { return; }
  183. ERROR_BLOCK();
  184. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  185. defer (did_you_mean_destroy(&d));
  186. for (Entity *e : fields) {
  187. did_you_mean_append(&d, e->token.string);
  188. }
  189. check_did_you_mean_print(&d, prefix);
  190. }
  191. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  192. if (build_context.terse_errors) { return; }
  193. ERROR_BLOCK();
  194. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  195. defer (did_you_mean_destroy(&d));
  196. for (Entity *e : fields) {
  197. did_you_mean_append(&d, e->token.string);
  198. }
  199. check_did_you_mean_print(&d, prefix);
  200. }
  201. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  202. if (build_context.terse_errors) { return; }
  203. ERROR_BLOCK();
  204. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  205. defer (did_you_mean_destroy(&d));
  206. rw_mutex_shared_lock(&scope->mutex);
  207. for (auto const &entry : scope->elements) {
  208. Entity *e = entry.value;
  209. did_you_mean_append(&d, e->token.string);
  210. }
  211. rw_mutex_shared_unlock(&scope->mutex);
  212. check_did_you_mean_print(&d, prefix);
  213. }
  214. gb_internal Entity *entity_from_expr(Ast *expr) {
  215. expr = unparen_expr(expr);
  216. if (expr == nullptr) {
  217. return nullptr;
  218. }
  219. switch (expr->kind) {
  220. case Ast_Ident:
  221. return expr->Ident.entity;
  222. case Ast_SelectorExpr:
  223. return entity_from_expr(expr->SelectorExpr.selector);
  224. }
  225. return nullptr;
  226. }
  227. gb_internal void error_operand_not_expression(Operand *o) {
  228. if (o->mode == Addressing_Type) {
  229. gbString err = expr_to_string(o->expr);
  230. error(o->expr, "'%s' is not an expression but a type", err);
  231. gb_string_free(err);
  232. o->mode = Addressing_Invalid;
  233. }
  234. }
  235. gb_internal void error_operand_no_value(Operand *o) {
  236. if (o->mode == Addressing_NoValue) {
  237. Ast *x = unparen_expr(o->expr);
  238. if (x != nullptr && x->kind == Ast_CallExpr) {
  239. Ast *p = unparen_expr(x->CallExpr.proc);
  240. if (p->kind == Ast_BasicDirective) {
  241. String tag = p->BasicDirective.name.string;
  242. if (tag == "panic" ||
  243. tag == "assert") {
  244. return;
  245. }
  246. }
  247. }
  248. gbString err = expr_to_string(o->expr);
  249. if (x != nullptr && x->kind == Ast_CallExpr) {
  250. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  251. } else {
  252. error(o->expr, "'%s' used as a value", err);
  253. }
  254. gb_string_free(err);
  255. o->mode = Addressing_Invalid;
  256. }
  257. }
  258. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  259. if (build_context.dynamic_map_calls) {
  260. add_package_dependency(c, "runtime", "__dynamic_map_get");
  261. } else {
  262. add_package_dependency(c, "runtime", "map_desired_position");
  263. add_package_dependency(c, "runtime", "map_probe_distance");
  264. }
  265. }
  266. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  267. init_core_source_code_location(c->checker);
  268. if (t_map_set_proc == nullptr) {
  269. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  270. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  271. }
  272. if (build_context.dynamic_map_calls) {
  273. add_package_dependency(c, "runtime", "__dynamic_map_set");
  274. } else {
  275. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  276. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  277. }
  278. }
  279. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  280. init_core_source_code_location(c->checker);
  281. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  282. }
  283. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  284. Scope *s = c->scope;
  285. check_collect_entities(c, nodes);
  286. for (auto const &entry : s->elements) {
  287. Entity *e = entry.value;\
  288. switch (e->kind) {
  289. case Entity_Constant:
  290. case Entity_TypeName:
  291. case Entity_Procedure:
  292. break;
  293. default:
  294. continue;
  295. }
  296. DeclInfo *d = decl_info_of_entity(e);
  297. if (d != nullptr) {
  298. check_entity_decl(c, e, d, nullptr);
  299. }
  300. }
  301. }
  302. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  303. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  304. ///////////////////////////////////////////////////////////////////////////////
  305. // //
  306. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  307. // //
  308. ///////////////////////////////////////////////////////////////////////////////
  309. CheckerInfo *info = old_c->info;
  310. if (base_entity == nullptr) {
  311. return false;
  312. }
  313. if (!is_type_proc(base_entity->type)) {
  314. return false;
  315. }
  316. if (base_entity->flags & EntityFlag_Disabled) {
  317. return false;
  318. }
  319. String name = base_entity->token.string;
  320. Type *src = base_type(base_entity->type);
  321. Type *dst = nullptr;
  322. if (type != nullptr) {
  323. dst = base_type(type);
  324. }
  325. if (param_operands == nullptr) {
  326. GB_ASSERT(dst != nullptr);
  327. }
  328. if (param_operands != nullptr) {
  329. GB_ASSERT(dst == nullptr);
  330. }
  331. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  332. return false;
  333. }
  334. if (dst != nullptr) {
  335. if (dst->Proc.is_polymorphic) {
  336. return false;
  337. }
  338. if (dst->Proc.param_count != src->Proc.param_count ||
  339. dst->Proc.result_count != src->Proc.result_count) {
  340. return false;
  341. }
  342. }
  343. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  344. if (old_decl == nullptr) {
  345. return false;
  346. }
  347. gbAllocator a = heap_allocator();
  348. Array<Operand> operands = {};
  349. if (param_operands) {
  350. operands = *param_operands;
  351. } else {
  352. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  353. for (isize i = 0; i < dst->Proc.param_count; i++) {
  354. Entity *param = dst->Proc.params->Tuple.variables[i];
  355. Operand o = {Addressing_Value};
  356. o.type = param->type;
  357. array_add(&operands, o);
  358. }
  359. }
  360. defer (if (param_operands == nullptr) {
  361. array_free(&operands);
  362. });
  363. CheckerContext nctx = *old_c;
  364. Scope *scope = create_scope(info, base_entity->scope);
  365. scope->flags |= ScopeFlag_Proc;
  366. nctx.scope = scope;
  367. nctx.allow_polymorphic_types = true;
  368. if (nctx.polymorphic_scope == nullptr) {
  369. nctx.polymorphic_scope = scope;
  370. }
  371. auto *pt = &src->Proc;
  372. // NOTE(bill): This is slightly memory leaking if the type already exists
  373. // Maybe it's better to check with the previous types first?
  374. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  375. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  376. if (!success) {
  377. return false;
  378. }
  379. GenProcsData *gen_procs = nullptr;
  380. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  381. GB_ASSERT(base_entity->kind == Entity_Procedure);
  382. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  383. gen_procs = base_entity->Procedure.gen_procs;
  384. if (gen_procs) {
  385. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  386. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  387. for (Entity *other : gen_procs->procs) {
  388. Type *pt = base_type(other->type);
  389. if (are_types_identical(pt, final_proc_type)) {
  390. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  391. if (poly_proc_data) {
  392. poly_proc_data->gen_entity = other;
  393. }
  394. return true;
  395. }
  396. }
  397. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  398. } else {
  399. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  400. gen_procs->procs.allocator = heap_allocator();
  401. base_entity->Procedure.gen_procs = gen_procs;
  402. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  403. }
  404. {
  405. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  406. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  407. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  408. nctx.no_polymorphic_errors = false;
  409. // NOTE(bill): Reset scope from the failed procedure type
  410. scope->head_child.store(nullptr, std::memory_order_relaxed);
  411. string_map_clear(&scope->elements);
  412. ptr_set_clear(&scope->imported);
  413. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  414. Ast *cloned_proc_type_node = clone_ast(pt->node);
  415. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  416. if (!success) {
  417. return false;
  418. }
  419. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  420. for (Entity *other : gen_procs->procs) {
  421. Type *pt = base_type(other->type);
  422. if (are_types_identical(pt, final_proc_type)) {
  423. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  424. if (poly_proc_data) {
  425. poly_proc_data->gen_entity = other;
  426. }
  427. DeclInfo *decl = other->decl_info;
  428. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  429. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  430. proc_info->file = other->file;
  431. proc_info->token = other->token;
  432. proc_info->decl = decl;
  433. proc_info->type = other->type;
  434. proc_info->body = decl->proc_lit->ProcLit.body;
  435. proc_info->tags = other->Procedure.tags;;
  436. proc_info->generated_from_polymorphic = true;
  437. proc_info->poly_def_node = poly_def_node;
  438. check_procedure_later(nctx.checker, proc_info);
  439. }
  440. return true;
  441. }
  442. }
  443. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  444. }
  445. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  446. ast_node(pl, ProcLit, proc_lit);
  447. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  448. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  449. final_proc_type->Proc.is_poly_specialized = true;
  450. final_proc_type->Proc.is_polymorphic = true;
  451. final_proc_type->Proc.variadic = src->Proc.variadic;
  452. final_proc_type->Proc.require_results = src->Proc.require_results;
  453. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  454. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  455. final_proc_type->Proc.diverging = src->Proc.diverging;
  456. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  457. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  458. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  459. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  460. for (isize i = 0; i < operands.count; i++) {
  461. Operand o = operands[i];
  462. if (final_proc_type == o.type ||
  463. base_entity->type == o.type) {
  464. // NOTE(bill): Cycle
  465. final_proc_type->Proc.is_poly_specialized = false;
  466. break;
  467. }
  468. }
  469. u64 tags = base_entity->Procedure.tags;
  470. Ast *ident = clone_ast(base_entity->identifier);
  471. Token token = ident->Ident.token;
  472. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  473. d->gen_proc_type = final_proc_type;
  474. d->type_expr = pl->type;
  475. d->proc_lit = proc_lit;
  476. d->proc_checked_state = ProcCheckedState_Unchecked;
  477. d->defer_use_checked = false;
  478. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  479. entity->state.store(EntityState_Resolved);
  480. entity->identifier = ident;
  481. add_entity_and_decl_info(&nctx, ident, entity, d);
  482. // NOTE(bill): Set the scope afterwards as this is not real overloading
  483. entity->scope = scope->parent;
  484. entity->file = base_entity->file;
  485. entity->pkg = base_entity->pkg;
  486. entity->flags = 0;
  487. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  488. if (base_entity->flags & EntityFlag_Cold) {
  489. entity->flags |= EntityFlag_Cold;
  490. }
  491. if (base_entity->flags & EntityFlag_Disabled) {
  492. entity->flags |= EntityFlag_Disabled;
  493. }
  494. d->entity = entity;
  495. AstFile *file = nullptr;
  496. {
  497. Scope *s = entity->scope;
  498. while (s != nullptr && s->file == nullptr) {
  499. file = s->file;
  500. s = s->parent;
  501. }
  502. }
  503. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  504. array_add(&gen_procs->procs, entity);
  505. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  506. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  507. proc_info->file = file;
  508. proc_info->token = token;
  509. proc_info->decl = d;
  510. proc_info->type = final_proc_type;
  511. proc_info->body = pl->body;
  512. proc_info->tags = tags;
  513. proc_info->generated_from_polymorphic = true;
  514. proc_info->poly_def_node = poly_def_node;
  515. if (poly_proc_data) {
  516. poly_proc_data->gen_entity = entity;
  517. poly_proc_data->proc_info = proc_info;
  518. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  519. }
  520. // NOTE(bill): Check the newly generated procedure body
  521. check_procedure_later(nctx.checker, proc_info);
  522. return true;
  523. }
  524. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  525. if (operand->expr == nullptr) return false;
  526. Entity *base_entity = entity_from_expr(operand->expr);
  527. if (base_entity == nullptr) return false;
  528. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  529. }
  530. 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) {
  531. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  532. }
  533. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  534. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  535. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  536. #define MAXIMUM_TYPE_DISTANCE 10
  537. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  538. if (c == nullptr) {
  539. GB_ASSERT(operand->mode == Addressing_Value);
  540. GB_ASSERT(is_type_typed(operand->type));
  541. }
  542. if (operand->mode == Addressing_Invalid ||
  543. type == t_invalid) {
  544. return -1;
  545. }
  546. if (operand->mode == Addressing_Builtin) {
  547. return -1;
  548. }
  549. if (operand->mode == Addressing_Type) {
  550. if (is_type_typeid(type)) {
  551. if (is_type_polymorphic(operand->type)) {
  552. return -1;
  553. }
  554. add_type_info_type(c, operand->type);
  555. return 4;
  556. }
  557. return -1;
  558. }
  559. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  560. return -1;
  561. }
  562. Type *s = operand->type;
  563. if (are_types_identical(s, type)) {
  564. return 0;
  565. }
  566. Type *src = base_type(s);
  567. Type *dst = base_type(type);
  568. if (is_type_untyped_uninit(src)) {
  569. return 1;
  570. }
  571. if (is_type_untyped_nil(src)) {
  572. if (type_has_nil(dst)) {
  573. return 1;
  574. }
  575. return -1;
  576. }
  577. if (is_type_untyped(src)) {
  578. if (is_type_any(dst)) {
  579. // NOTE(bill): Anything can cast to 'Any'
  580. add_type_info_type(c, s);
  581. return MAXIMUM_TYPE_DISTANCE;
  582. }
  583. if (dst->kind == Type_Basic) {
  584. if (operand->mode == Addressing_Constant) {
  585. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  586. if (is_type_typed(dst) && src->kind == Type_Basic) {
  587. switch (src->Basic.kind) {
  588. case Basic_UntypedBool:
  589. if (is_type_boolean(dst)) {
  590. return 1;
  591. }
  592. break;
  593. case Basic_UntypedRune:
  594. if (is_type_integer(dst) || is_type_rune(dst)) {
  595. return 1;
  596. }
  597. break;
  598. case Basic_UntypedInteger:
  599. if (is_type_integer(dst) || is_type_rune(dst)) {
  600. return 1;
  601. }
  602. break;
  603. case Basic_UntypedString:
  604. if (is_type_string(dst)) {
  605. return 1;
  606. }
  607. break;
  608. case Basic_UntypedFloat:
  609. if (is_type_float(dst)) {
  610. return 1;
  611. }
  612. break;
  613. case Basic_UntypedComplex:
  614. if (is_type_complex(dst)) {
  615. return 1;
  616. }
  617. if (is_type_quaternion(dst)) {
  618. return 2;
  619. }
  620. break;
  621. case Basic_UntypedQuaternion:
  622. if (is_type_quaternion(dst)) {
  623. return 1;
  624. }
  625. break;
  626. }
  627. }
  628. return 2;
  629. }
  630. return -1;
  631. }
  632. if (src->kind == Type_Basic) {
  633. Type *d = base_array_type(dst);
  634. i64 score = -1;
  635. switch (src->Basic.kind) {
  636. case Basic_UntypedBool:
  637. if (is_type_boolean(d)) {
  638. score = 1;
  639. }
  640. break;
  641. case Basic_UntypedRune:
  642. if (is_type_integer(d) || is_type_rune(d)) {
  643. score = 1;
  644. }
  645. break;
  646. case Basic_UntypedInteger:
  647. if (is_type_integer(d) || is_type_rune(d)) {
  648. score = 1;
  649. }
  650. break;
  651. case Basic_UntypedString:
  652. if (is_type_string(d)) {
  653. score = 1;
  654. }
  655. break;
  656. case Basic_UntypedFloat:
  657. if (is_type_float(d)) {
  658. score = 1;
  659. }
  660. break;
  661. case Basic_UntypedComplex:
  662. if (is_type_complex(d)) {
  663. score = 1;
  664. }
  665. if (is_type_quaternion(d)) {
  666. score = 2;
  667. }
  668. break;
  669. case Basic_UntypedQuaternion:
  670. if (is_type_quaternion(d)) {
  671. score = 1;
  672. }
  673. break;
  674. }
  675. if (score > 0) {
  676. if (is_type_typed(d)) {
  677. score += 1;
  678. }
  679. if (d != dst) {
  680. score += 6;
  681. }
  682. }
  683. return score;
  684. }
  685. }
  686. }
  687. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  688. if (c->in_enum_type) {
  689. return 3;
  690. }
  691. }
  692. {
  693. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  694. if (subtype_level > 0) {
  695. return 4 + subtype_level;
  696. }
  697. }
  698. // rawptr <- ^T
  699. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  700. return 5;
  701. }
  702. // rawptr <- [^]T
  703. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  704. return 5;
  705. }
  706. // ^T <- [^]T
  707. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  708. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  709. return 4;
  710. }
  711. }
  712. // [^]T <- ^T
  713. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  714. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  715. return 4;
  716. }
  717. }
  718. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  719. bool modify_type = !c->no_polymorphic_errors;
  720. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  721. return 2;
  722. }
  723. }
  724. if (is_type_union(dst)) {
  725. for (Type *vt : dst->Union.variants) {
  726. if (are_types_identical(vt, s)) {
  727. return 1;
  728. }
  729. if (is_type_proc(vt)) {
  730. if (are_types_identical(base_type(vt), src)) {
  731. return 1;
  732. }
  733. }
  734. }
  735. if (dst->Union.variants.count == 1) {
  736. Type *vt = dst->Union.variants[0];
  737. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  738. if (score >= 0) {
  739. return score+2;
  740. }
  741. } else if (is_type_untyped(src)) {
  742. i64 prev_lowest_score = -1;
  743. i64 lowest_score = -1;
  744. for (Type *vt : dst->Union.variants) {
  745. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  746. if (score >= 0) {
  747. if (lowest_score < 0) {
  748. lowest_score = score;
  749. } else {
  750. if (prev_lowest_score < 0) {
  751. prev_lowest_score = lowest_score;
  752. } else {
  753. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  754. }
  755. lowest_score = gb_min(lowest_score, score);
  756. }
  757. }
  758. }
  759. if (lowest_score >= 0) {
  760. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  761. return lowest_score+2;
  762. }
  763. }
  764. }
  765. }
  766. if (is_type_proc(dst)) {
  767. if (are_types_identical(src, dst)) {
  768. return 3;
  769. }
  770. PolyProcData poly_proc_data = {};
  771. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  772. Entity *e = poly_proc_data.gen_entity;
  773. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  774. add_entity_use(c, operand->expr, e);
  775. return 4;
  776. }
  777. }
  778. if (is_type_complex_or_quaternion(dst)) {
  779. Type *elem = base_complex_elem_type(dst);
  780. if (are_types_identical(elem, base_type(src))) {
  781. return 5;
  782. }
  783. }
  784. if (allow_array_programming) {
  785. if (is_type_array(dst)) {
  786. Type *elem = base_array_type(dst);
  787. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  788. if (distance >= 0) {
  789. return distance + 6;
  790. }
  791. }
  792. if (is_type_simd_vector(dst)) {
  793. Type *dst_elem = base_array_type(dst);
  794. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  795. if (distance >= 0) {
  796. return distance + 6;
  797. }
  798. }
  799. }
  800. if (is_type_matrix(dst)) {
  801. if (are_types_identical(src, dst)) {
  802. return 5;
  803. }
  804. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  805. Type *dst_elem = base_array_type(dst);
  806. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  807. if (distance >= 0) {
  808. return distance + 7;
  809. }
  810. }
  811. }
  812. if (is_type_any(dst)) {
  813. if (!is_type_polymorphic(src)) {
  814. if (operand->mode == Addressing_Context && operand->type == t_context) {
  815. return -1;
  816. } else {
  817. // NOTE(bill): Anything can cast to 'Any'
  818. add_type_info_type(c, s);
  819. return MAXIMUM_TYPE_DISTANCE;
  820. }
  821. }
  822. }
  823. Ast *expr = unparen_expr(operand->expr);
  824. if (expr != nullptr) {
  825. if (expr->kind == Ast_AutoCast) {
  826. Operand x = *operand;
  827. x.expr = expr->AutoCast.expr;
  828. if (check_cast_internal(c, &x, type)) {
  829. return MAXIMUM_TYPE_DISTANCE;
  830. }
  831. }
  832. }
  833. return -1;
  834. }
  835. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  836. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  837. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  838. // TODO(bill): A decent score function
  839. i64 d = distance*distance; // x^2
  840. if (is_variadic && d >= 0) {
  841. d += distance + 1; // x^2 + x + 1
  842. }
  843. return gb_max(c - d, 0);
  844. }
  845. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false, bool allow_array_programming=true) {
  846. if (c == nullptr) {
  847. GB_ASSERT(operand->mode == Addressing_Value);
  848. GB_ASSERT(is_type_typed(operand->type));
  849. }
  850. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  851. if (score_) *score_ = 0;
  852. return false;
  853. }
  854. // Handle polymorphic procedure used as default parameter
  855. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  856. Entity *e = entity_from_expr(operand->expr);
  857. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  858. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  859. // during the initial check. It will be properly instantiated when actually used.
  860. if (score_) *score_ = assign_score_function(1);
  861. return true;
  862. }
  863. }
  864. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  865. if (score >= 0) {
  866. if (score_) *score_ = assign_score_function(score, is_variadic);
  867. return true;
  868. }
  869. if (score_) *score_ = 0;
  870. return false;
  871. }
  872. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  873. i64 score = 0;
  874. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  875. }
  876. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  877. Operand x = {};
  878. x.type = src;
  879. x.mode = Addressing_Value;
  880. return check_is_assignable_to(nullptr, &x, dst);
  881. }
  882. gb_internal AstPackage *get_package_of_type(Type *type) {
  883. for (;;) {
  884. if (type == nullptr) {
  885. return nullptr;
  886. }
  887. switch (type->kind) {
  888. case Type_Basic:
  889. return builtin_pkg;
  890. case Type_Named:
  891. if (type->Named.type_name != nullptr) {
  892. return type->Named.type_name->pkg;
  893. }
  894. return nullptr;
  895. case Type_Pointer:
  896. type = type->Pointer.elem;
  897. continue;
  898. case Type_Array:
  899. type = type->Array.elem;
  900. continue;
  901. case Type_Slice:
  902. type = type->Slice.elem;
  903. continue;
  904. case Type_DynamicArray:
  905. type = type->DynamicArray.elem;
  906. continue;
  907. }
  908. return nullptr;
  909. }
  910. }
  911. // NOTE(bill): 'context_name' is for debugging and error messages
  912. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  913. check_not_tuple(c, operand);
  914. if (operand->mode == Addressing_Invalid) {
  915. return;
  916. }
  917. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  918. String article = error_article(context_name);
  919. if (is_type_untyped(operand->type)) {
  920. Type *target_type = type;
  921. if (type == nullptr || is_type_any(type)) {
  922. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  923. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  924. operand->mode = Addressing_Invalid;
  925. return;
  926. }
  927. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  928. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  929. operand->mode = Addressing_Invalid;
  930. return;
  931. }
  932. target_type = default_type(operand->type);
  933. if (type != nullptr && !is_type_any(type)) {
  934. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  935. }
  936. add_type_info_type(c, type);
  937. add_type_info_type(c, target_type);
  938. }
  939. convert_to_typed(c, operand, target_type);
  940. if (operand->mode == Addressing_Invalid) {
  941. return;
  942. }
  943. }
  944. if (type == nullptr) {
  945. return;
  946. }
  947. if (operand->mode == Addressing_ProcGroup) {
  948. bool good = false;
  949. if (type != nullptr && is_type_proc(type)) {
  950. Array<Entity *> procs = proc_group_entities(c, *operand);
  951. // NOTE(bill): These should be done
  952. for (Entity *e : procs) {
  953. Type *t = base_type(e->type);
  954. if (t == t_invalid) {
  955. continue;
  956. }
  957. Operand x = {};
  958. x.mode = Addressing_Value;
  959. x.type = t;
  960. if (check_is_assignable_to(c, &x, type)) {
  961. add_entity_use(c, operand->expr, e);
  962. good = true;
  963. break;
  964. }
  965. }
  966. }
  967. if (!good) {
  968. gbString expr_str = expr_to_string(operand->expr);
  969. gbString op_type_str = type_to_string(operand->type);
  970. gbString type_str = type_to_string(type);
  971. defer (gb_string_free(type_str));
  972. defer (gb_string_free(op_type_str));
  973. defer (gb_string_free(expr_str));
  974. // TODO(bill): is this a good enough error message?
  975. error(operand->expr,
  976. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  977. expr_str,
  978. op_type_str,
  979. LIT(article),
  980. LIT(context_name));
  981. operand->mode = Addressing_Invalid;
  982. }
  983. convert_to_typed(c, operand, type);
  984. return;
  985. }
  986. if (check_is_assignable_to(c, operand, type)) {
  987. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  988. add_type_info_type(c, operand->type);
  989. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  990. }
  991. } else {
  992. gbString expr_str = expr_to_string(operand->expr);
  993. gbString op_type_str = type_to_string(operand->type);
  994. gbString type_str = type_to_string(type);
  995. defer (gb_string_free(type_str));
  996. defer (gb_string_free(op_type_str));
  997. defer (gb_string_free(expr_str));
  998. switch (operand->mode) {
  999. case Addressing_Builtin:
  1000. error(operand->expr,
  1001. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1002. expr_str,
  1003. LIT(article),
  1004. LIT(context_name));
  1005. break;
  1006. case Addressing_Type:
  1007. if (is_type_polymorphic(operand->type)) {
  1008. error(operand->expr,
  1009. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1010. op_type_str,
  1011. LIT(article),
  1012. LIT(context_name));
  1013. } else {
  1014. ERROR_BLOCK();
  1015. error(operand->expr,
  1016. "Cannot assign '%s', a type, to %.*s%.*s",
  1017. op_type_str,
  1018. LIT(article),
  1019. LIT(context_name));
  1020. if (type && are_types_identical(type, t_any)) {
  1021. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1022. }
  1023. }
  1024. break;
  1025. default:
  1026. // TODO(bill): is this a good enough error message?
  1027. {
  1028. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1029. gbString type_extra = gb_string_make(heap_allocator(), "");
  1030. defer (gb_string_free(op_type_extra));
  1031. defer (gb_string_free(type_extra));
  1032. isize on = gb_string_length(op_type_str);
  1033. isize tn = gb_string_length(type_str);
  1034. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1035. AstPackage *op_pkg = get_package_of_type(operand->type);
  1036. AstPackage *type_pkg = get_package_of_type(type);
  1037. if (op_pkg != nullptr) {
  1038. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1039. }
  1040. if (type_pkg != nullptr) {
  1041. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1042. }
  1043. }
  1044. ERROR_BLOCK();
  1045. error(operand->expr,
  1046. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1047. expr_str,
  1048. op_type_str, op_type_extra,
  1049. type_str, type_extra,
  1050. LIT(article),
  1051. LIT(context_name));
  1052. check_assignment_error_suggestion(c, operand, type);
  1053. Type *src = base_type(operand->type);
  1054. Type *dst = base_type(type);
  1055. if (context_name == "procedure argument") {
  1056. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1057. gbString a = expr_to_string(operand->expr);
  1058. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1059. gb_string_free(a);
  1060. }
  1061. }
  1062. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1063. Type *x = src;
  1064. Type *y = dst;
  1065. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1066. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1067. if (same_inputs && same_outputs &&
  1068. x->Proc.calling_convention != y->Proc.calling_convention) {
  1069. gbString s_expected = type_to_string(y);
  1070. gbString s_got = type_to_string(x);
  1071. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1072. error_line("\t Expected \"%s\", got \"%s\"\n",
  1073. proc_calling_convention_strings[y->Proc.calling_convention],
  1074. proc_calling_convention_strings[x->Proc.calling_convention]);
  1075. error_line("\t Expected: %s\n", s_expected);
  1076. error_line("\t Got: %s\n", s_got);
  1077. gb_string_free(s_got);
  1078. gb_string_free(s_expected);
  1079. } else if (same_inputs && same_outputs &&
  1080. x->Proc.diverging != y->Proc.diverging) {
  1081. gbString s_expected = type_to_string(y);
  1082. if (y->Proc.diverging) {
  1083. s_expected = gb_string_appendc(s_expected, " -> !");
  1084. }
  1085. gbString s_got = type_to_string(x);
  1086. if (x->Proc.diverging) {
  1087. s_got = gb_string_appendc(s_got, " -> !");
  1088. }
  1089. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1090. error_line("\t Expected: %s\n", s_expected);
  1091. error_line("\t Got: %s\n", s_got);
  1092. gb_string_free(s_got);
  1093. gb_string_free(s_expected);
  1094. } else if (same_inputs && !same_outputs) {
  1095. gbString s_expected = type_to_string(y->Proc.results);
  1096. gbString s_got = type_to_string(x->Proc.results);
  1097. error_line("\tNote: The return types differ between the procedure signature types\n");
  1098. error_line("\t Expected: %s\n", s_expected);
  1099. error_line("\t Got: %s\n", s_got);
  1100. gb_string_free(s_got);
  1101. gb_string_free(s_expected);
  1102. } else if (!same_inputs && same_outputs) {
  1103. gbString s_expected = type_to_string(y->Proc.params);
  1104. gbString s_got = type_to_string(x->Proc.params);
  1105. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1106. error_line("\t Expected: %s\n", s_expected);
  1107. error_line("\t Got: %s\n", s_got);
  1108. gb_string_free(s_got);
  1109. gb_string_free(s_expected);
  1110. } else {
  1111. gbString s_expected = type_to_string(y);
  1112. gbString s_got = type_to_string(x);
  1113. error_line("\tNote: The signature type do not match whatsoever\n");
  1114. error_line("\t Expected: %s\n", s_expected);
  1115. error_line("\t Got: %s\n", s_got);
  1116. gb_string_free(s_got);
  1117. gb_string_free(s_expected);
  1118. }
  1119. }
  1120. }
  1121. break;
  1122. }
  1123. operand->mode = Addressing_Invalid;
  1124. return;
  1125. }
  1126. }
  1127. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1128. Type *gt = *gt_;
  1129. GB_ASSERT(gt->kind == Type_Generic);
  1130. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1131. GB_ASSERT(e != nullptr);
  1132. if (e->kind == Entity_TypeName) {
  1133. *gt_ = nullptr;
  1134. *dst_count = source_count;
  1135. e->kind = Entity_Constant;
  1136. e->Constant.value = exact_value_i64(source_count);
  1137. e->type = t_untyped_integer;
  1138. return true;
  1139. } else if (e->kind == Entity_Constant) {
  1140. *gt_ = nullptr;
  1141. if (e->Constant.value.kind != ExactValue_Integer) {
  1142. return false;
  1143. }
  1144. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1145. if (count != source_count) {
  1146. return false;
  1147. }
  1148. *dst_count = source_count;
  1149. return true;
  1150. }
  1151. return false;
  1152. }
  1153. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1154. Operand o = {Addressing_Value};
  1155. o.type = source;
  1156. switch (poly->kind) {
  1157. case Type_Basic:
  1158. if (compound) return are_types_identical(poly, source);
  1159. return check_is_assignable_to(c, &o, poly);
  1160. case Type_Named: {
  1161. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1162. return true;
  1163. }
  1164. if (compound || !is_type_generic(poly)) {
  1165. return are_types_identical(poly, source);
  1166. }
  1167. return check_is_assignable_to(c, &o, poly);
  1168. }
  1169. case Type_Generic: {
  1170. if (poly->Generic.specialized != nullptr) {
  1171. Type *s = poly->Generic.specialized;
  1172. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1173. return false;
  1174. }
  1175. }
  1176. if (modify_type) {
  1177. Type *ds = default_type(source);
  1178. gb_memmove(poly, ds, gb_size_of(Type));
  1179. }
  1180. return true;
  1181. }
  1182. case Type_Pointer:
  1183. if (source->kind == Type_Pointer) {
  1184. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1185. if (level > 0) {
  1186. return true;
  1187. }
  1188. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1189. } else if (source->kind == Type_MultiPointer) {
  1190. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1191. if (level > 0) {
  1192. return true;
  1193. }
  1194. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1195. }
  1196. return false;
  1197. case Type_MultiPointer:
  1198. if (source->kind == Type_MultiPointer) {
  1199. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1200. if (level > 0) {
  1201. return true;
  1202. }
  1203. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1204. } else if (source->kind == Type_Pointer) {
  1205. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1206. if (level > 0) {
  1207. return true;
  1208. }
  1209. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1210. }
  1211. return false;
  1212. case Type_Array:
  1213. if (source->kind == Type_Array) {
  1214. if (poly->Array.generic_count != nullptr) {
  1215. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1216. return false;
  1217. }
  1218. }
  1219. if (poly->Array.count == source->Array.count) {
  1220. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1221. }
  1222. } else if (source->kind == Type_EnumeratedArray) {
  1223. if (poly->Array.generic_count != nullptr) {
  1224. Type *gt = poly->Array.generic_count;
  1225. GB_ASSERT(gt->kind == Type_Generic);
  1226. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1227. GB_ASSERT(e != nullptr);
  1228. if (e->kind == Entity_TypeName) {
  1229. Type *index = source->EnumeratedArray.index;
  1230. Type *it = base_type(index);
  1231. if (it->kind != Type_Enum) {
  1232. return false;
  1233. }
  1234. poly->kind = Type_EnumeratedArray;
  1235. poly->cached_size = -1;
  1236. poly->cached_align = -1;
  1237. poly->flags.exchange(source->flags);
  1238. poly->failure = false;
  1239. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1240. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1241. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1242. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1243. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1244. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1245. e->kind = Entity_TypeName;
  1246. e->TypeName.is_type_alias = true;
  1247. e->type = index;
  1248. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1249. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return false;
  1255. case Type_EnumeratedArray:
  1256. if (source->kind == Type_EnumeratedArray) {
  1257. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1258. return false;
  1259. }
  1260. if (poly->EnumeratedArray.op) {
  1261. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1262. return false;
  1263. }
  1264. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1265. return false;
  1266. }
  1267. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1268. return false;
  1269. }
  1270. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1271. }
  1272. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1273. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1274. return index || elem;
  1275. }
  1276. return false;
  1277. case Type_DynamicArray:
  1278. if (source->kind == Type_DynamicArray) {
  1279. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1280. }
  1281. return false;
  1282. case Type_Slice:
  1283. if (source->kind == Type_Slice) {
  1284. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1285. }
  1286. return false;
  1287. case Type_Enum:
  1288. return false;
  1289. case Type_BitSet:
  1290. if (source->kind == Type_BitSet) {
  1291. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1292. return false;
  1293. }
  1294. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1295. // it could not figure that stuff out when the poly type was created.
  1296. if (poly->BitSet.upper == 0 && modify_type) {
  1297. poly->BitSet.upper = source->BitSet.upper;
  1298. }
  1299. if (poly->BitSet.lower == 0 && modify_type) {
  1300. poly->BitSet.lower = source->BitSet.lower;
  1301. }
  1302. if (poly->BitSet.underlying == nullptr) {
  1303. if (modify_type) {
  1304. poly->BitSet.underlying = source->BitSet.underlying;
  1305. }
  1306. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1307. return false;
  1308. }
  1309. return true;
  1310. }
  1311. return false;
  1312. case Type_Union:
  1313. if (source->kind == Type_Union) {
  1314. TypeUnion *x = &poly->Union;
  1315. TypeUnion *y = &source->Union;
  1316. if (x->variants.count != y->variants.count) {
  1317. return false;
  1318. }
  1319. for_array(i, x->variants) {
  1320. Type *a = x->variants[i];
  1321. Type *b = y->variants[i];
  1322. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1323. if (!ok) return false;
  1324. }
  1325. return true;
  1326. }
  1327. return false;
  1328. case Type_Struct:
  1329. if (source->kind == Type_Struct) {
  1330. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1331. poly->Struct.soa_kind != StructSoa_None) {
  1332. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1333. if (ok) switch (source->Struct.soa_kind) {
  1334. case StructSoa_None:
  1335. default:
  1336. GB_PANIC("Unhandled SOA Kind");
  1337. break;
  1338. case StructSoa_Fixed:
  1339. if (modify_type) {
  1340. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1341. gb_memmove(poly, type, gb_size_of(*type));
  1342. }
  1343. break;
  1344. case StructSoa_Slice:
  1345. if (modify_type) {
  1346. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1347. gb_memmove(poly, type, gb_size_of(*type));
  1348. }
  1349. break;
  1350. case StructSoa_Dynamic:
  1351. if (modify_type) {
  1352. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1353. gb_memmove(poly, type, gb_size_of(*type));
  1354. }
  1355. break;
  1356. }
  1357. return ok;
  1358. }
  1359. // NOTE(bill): Check for subtypes of
  1360. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1361. }
  1362. return false;
  1363. case Type_BitField:
  1364. if (source->kind == Type_BitField) {
  1365. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1366. }
  1367. return false;
  1368. case Type_Tuple:
  1369. GB_PANIC("This should never happen");
  1370. return false;
  1371. case Type_Proc:
  1372. if (source->kind == Type_Proc) {
  1373. TypeProc *x = &poly->Proc;
  1374. TypeProc *y = &source->Proc;
  1375. if (x->calling_convention != y->calling_convention) {
  1376. return false;
  1377. }
  1378. if (x->c_vararg != y->c_vararg) {
  1379. return false;
  1380. }
  1381. if (x->variadic != y->variadic) {
  1382. return false;
  1383. }
  1384. if (x->param_count != y->param_count) {
  1385. return false;
  1386. }
  1387. if (x->result_count != y->result_count) {
  1388. return false;
  1389. }
  1390. for (isize i = 0; i < x->param_count; i++) {
  1391. Entity *a = x->params->Tuple.variables[i];
  1392. Entity *b = y->params->Tuple.variables[i];
  1393. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1394. if (!ok) return false;
  1395. }
  1396. for (isize i = 0; i < x->result_count; i++) {
  1397. Entity *a = x->results->Tuple.variables[i];
  1398. Entity *b = y->results->Tuple.variables[i];
  1399. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1400. if (!ok) return false;
  1401. }
  1402. return true;
  1403. }
  1404. return false;
  1405. case Type_Map:
  1406. if (source->kind == Type_Map) {
  1407. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1408. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1409. if (key || value) {
  1410. poly->Map.lookup_result_type = nullptr;
  1411. init_map_internal_types(poly);
  1412. return true;
  1413. }
  1414. }
  1415. return false;
  1416. case Type_Matrix:
  1417. if (source->kind == Type_Matrix) {
  1418. if (poly->Matrix.generic_row_count != nullptr) {
  1419. poly->Matrix.stride_in_bytes = 0;
  1420. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1421. return false;
  1422. }
  1423. }
  1424. if (poly->Matrix.generic_column_count != nullptr) {
  1425. poly->Matrix.stride_in_bytes = 0;
  1426. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1427. return false;
  1428. }
  1429. }
  1430. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1431. poly->Matrix.column_count == source->Matrix.column_count) {
  1432. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1433. }
  1434. }
  1435. return false;
  1436. case Type_SimdVector:
  1437. if (source->kind == Type_SimdVector) {
  1438. if (poly->SimdVector.generic_count != nullptr) {
  1439. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1440. return false;
  1441. }
  1442. }
  1443. if (poly->SimdVector.count == source->SimdVector.count) {
  1444. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1445. }
  1446. }
  1447. return false;
  1448. }
  1449. return false;
  1450. }
  1451. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1452. if (curr->state != EntityState_InProgress) {
  1453. return false;
  1454. }
  1455. for_array(i, *c->type_path) {
  1456. Entity *prev = c->type_path->data[i];
  1457. if (prev == curr) {
  1458. if (report) {
  1459. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1460. for (isize j = i; j < c->type_path->count; j++) {
  1461. Entity *curr = (*c->type_path)[j];
  1462. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1463. }
  1464. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1465. curr->type = t_invalid;
  1466. }
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. struct CIdentSuggestion {
  1473. String name;
  1474. String msg;
  1475. };
  1476. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1477. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1478. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1479. {str_lit("sizeof"), str_lit("'size_of'?")},
  1480. {str_lit("alignof"), str_lit("'align_of'?")},
  1481. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1482. {str_lit("_Bool"), str_lit("'bool'?")},
  1483. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1484. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1485. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1486. {str_lit("float"), str_lit("'f32'?")},
  1487. {str_lit("double"), str_lit("'f64'?")},
  1488. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1489. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1490. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1491. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1492. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1493. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1494. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1495. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1496. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1497. {str_lit("uint8_t"), str_lit("'u8'?")},
  1498. {str_lit("int8_t"), str_lit("'i8'?")},
  1499. {str_lit("uint16_t"), str_lit("'u16'?")},
  1500. {str_lit("int16_t"), str_lit("'i16'?")},
  1501. {str_lit("uint32_t"), str_lit("'u32'?")},
  1502. {str_lit("int32_t"), str_lit("'i32'?")},
  1503. {str_lit("uint64_t"), str_lit("'u64'?")},
  1504. {str_lit("int64_t"), str_lit("'i64'?")},
  1505. {str_lit("uint128_t"), str_lit("'u128'?")},
  1506. {str_lit("int128_t"), str_lit("'i128'?")},
  1507. {str_lit("float32"), str_lit("'f32'?")},
  1508. {str_lit("float64"), str_lit("'f64'?")},
  1509. {str_lit("float32_t"), str_lit("'f32'?")},
  1510. {str_lit("float64_t"), str_lit("'f64'?")},
  1511. };
  1512. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1513. GB_ASSERT(n->kind == Ast_Ident);
  1514. o->mode = Addressing_Invalid;
  1515. o->expr = n;
  1516. String name = n->Ident.token.string;
  1517. Entity *e = scope_lookup(c->scope, name);
  1518. if (e == nullptr) {
  1519. if (is_blank_ident(name)) {
  1520. error(n, "'_' cannot be used as a value");
  1521. } else {
  1522. ERROR_BLOCK();
  1523. error(n, "Undeclared name: %.*s", LIT(name));
  1524. // NOTE(bill): Loads of checks for C programmers
  1525. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1526. if (name == suggestion.name) {
  1527. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1528. }
  1529. }
  1530. }
  1531. o->type = t_invalid;
  1532. o->mode = Addressing_Invalid;
  1533. if (named_type != nullptr) {
  1534. set_base_type(named_type, t_invalid);
  1535. }
  1536. return nullptr;
  1537. }
  1538. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1539. if (e->parent_proc_decl != nullptr &&
  1540. e->parent_proc_decl != c->curr_proc_decl) {
  1541. if (e->kind == Entity_Variable) {
  1542. if ((e->flags & EntityFlag_Static) == 0) {
  1543. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1544. return nullptr;
  1545. }
  1546. } else if (e->kind == Entity_Label) {
  1547. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1548. return nullptr;
  1549. }
  1550. }
  1551. if (e->kind == Entity_ProcGroup) {
  1552. auto *pge = &e->ProcGroup;
  1553. DeclInfo *d = decl_info_of_entity(e);
  1554. check_entity_decl(c, e, d, nullptr);
  1555. Array<Entity *> procs = pge->entities;
  1556. bool skip = false;
  1557. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1558. // NOTE(bill): These should be done
  1559. for (Entity *proc : procs) {
  1560. Type *t = base_type(proc->type);
  1561. if (t == t_invalid) {
  1562. continue;
  1563. }
  1564. Operand x = {};
  1565. x.mode = Addressing_Value;
  1566. x.type = t;
  1567. if (check_is_assignable_to(c, &x, type_hint)) {
  1568. e = proc;
  1569. add_entity_use(c, n, e);
  1570. skip = true;
  1571. break;
  1572. }
  1573. }
  1574. }
  1575. if (!skip) {
  1576. o->mode = Addressing_ProcGroup;
  1577. o->type = t_invalid;
  1578. o->proc_group = e;
  1579. return nullptr;
  1580. }
  1581. }
  1582. add_entity_use(c, n, e);
  1583. if (e->state == EntityState_Unresolved) {
  1584. check_entity_decl(c, e, nullptr, named_type);
  1585. }
  1586. if (e->type == nullptr) {
  1587. // TODO(bill): Which is correct? return or compiler_error?
  1588. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1589. return nullptr;
  1590. }
  1591. e->flags |= EntityFlag_Used;
  1592. Type *type = e->type;
  1593. o->type = type;
  1594. switch (e->kind) {
  1595. case Entity_Constant:
  1596. if (type == t_invalid) {
  1597. o->type = t_invalid;
  1598. return e;
  1599. }
  1600. o->value = e->Constant.value;
  1601. if (o->value.kind == ExactValue_Invalid) {
  1602. return e;
  1603. }
  1604. if (o->value.kind == ExactValue_Procedure) {
  1605. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1606. if (proc != nullptr) {
  1607. o->mode = Addressing_Value;
  1608. o->type = proc->type;
  1609. return proc;
  1610. }
  1611. }
  1612. o->mode = Addressing_Constant;
  1613. break;
  1614. case Entity_Variable:
  1615. e->flags |= EntityFlag_Used;
  1616. if (type == t_invalid) {
  1617. o->type = t_invalid;
  1618. return e;
  1619. }
  1620. o->mode = Addressing_Variable;
  1621. if (e->flags & EntityFlag_Value) {
  1622. o->mode = Addressing_Value;
  1623. }
  1624. break;
  1625. case Entity_Procedure:
  1626. o->mode = Addressing_Value;
  1627. o->value = exact_value_procedure(n);
  1628. break;
  1629. case Entity_Builtin:
  1630. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1631. o->mode = Addressing_Builtin;
  1632. break;
  1633. case Entity_TypeName:
  1634. o->mode = Addressing_Type;
  1635. if (check_cycle(c, e, true)) {
  1636. o->type = t_invalid;
  1637. }
  1638. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1639. Type *bt = base_type(o->type);
  1640. if (bt != nullptr) {
  1641. o->type = bt;
  1642. }
  1643. }
  1644. break;
  1645. case Entity_ImportName:
  1646. if (!allow_import_name) {
  1647. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1648. }
  1649. return e;
  1650. case Entity_LibraryName:
  1651. if (!allow_import_name) {
  1652. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1653. }
  1654. return e;
  1655. case Entity_Label:
  1656. o->mode = Addressing_NoValue;
  1657. break;
  1658. case Entity_Nil:
  1659. o->mode = Addressing_Value;
  1660. break;
  1661. default:
  1662. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1663. break;
  1664. }
  1665. return e;
  1666. }
  1667. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1668. if (o->type == nullptr) {
  1669. gbString str = expr_to_string(o->expr);
  1670. error(o->expr, "Expression has no value '%s'", str);
  1671. gb_string_free(str);
  1672. return false;
  1673. }
  1674. if (o->mode == Addressing_Type) {
  1675. gbString str = type_to_string(o->type);
  1676. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1677. gb_string_free(str);
  1678. return false;
  1679. }
  1680. Type *type = base_type(core_array_type(o->type));
  1681. gbString str = nullptr;
  1682. switch (op.kind) {
  1683. case Token_Add:
  1684. case Token_Sub:
  1685. if (!is_type_numeric(type)) {
  1686. str = expr_to_string(o->expr);
  1687. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1688. gb_string_free(str);
  1689. }
  1690. break;
  1691. case Token_Xor:
  1692. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1693. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1694. }
  1695. break;
  1696. case Token_Not:
  1697. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1698. ERROR_BLOCK();
  1699. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1700. if (is_type_integer(type)) {
  1701. str = expr_to_string(o->expr);
  1702. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1703. error_line("\t\t'%s == 0'?\n", str);
  1704. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1705. gb_string_free(str);
  1706. }
  1707. } else {
  1708. o->type = t_untyped_bool;
  1709. }
  1710. break;
  1711. case Token_Mul:
  1712. {
  1713. ERROR_BLOCK();
  1714. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1715. if (is_type_pointer(o->type)) {
  1716. str = expr_to_string(o->expr);
  1717. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1718. o->type = type_deref(o->type);
  1719. } else if (is_type_multi_pointer(o->type)) {
  1720. str = expr_to_string(o->expr);
  1721. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1722. o->type = type_deref(o->type, true);
  1723. }
  1724. }
  1725. break;
  1726. default:
  1727. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1728. return false;
  1729. }
  1730. return true;
  1731. }
  1732. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1733. Type *main_type = o->type;
  1734. Type *type = base_type(core_array_type(main_type));
  1735. Type *ct = core_type(type);
  1736. switch (op.kind) {
  1737. case Token_Sub:
  1738. case Token_SubEq:
  1739. if (is_type_bit_set(type)) {
  1740. return true;
  1741. } else if (!is_type_numeric(type)) {
  1742. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1743. return false;
  1744. }
  1745. break;
  1746. case Token_Quo:
  1747. case Token_QuoEq:
  1748. if (is_type_matrix(main_type)) {
  1749. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1750. return false;
  1751. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1752. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1753. return false;
  1754. }
  1755. /*fallthrough*/
  1756. case Token_Mul:
  1757. case Token_MulEq:
  1758. case Token_AddEq:
  1759. if (is_type_bit_set(type)) {
  1760. return true;
  1761. } else if (!is_type_numeric(type)) {
  1762. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1763. return false;
  1764. }
  1765. break;
  1766. case Token_Add:
  1767. if (is_type_string(type)) {
  1768. if (o->mode == Addressing_Constant) {
  1769. return true;
  1770. }
  1771. error(op, "String concatenation is only allowed with constant strings");
  1772. return false;
  1773. } else if (is_type_bit_set(type)) {
  1774. return true;
  1775. } else if (!is_type_numeric(type)) {
  1776. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1777. return false;
  1778. }
  1779. break;
  1780. case Token_And:
  1781. case Token_Or:
  1782. case Token_AndEq:
  1783. case Token_OrEq:
  1784. case Token_Xor:
  1785. case Token_XorEq:
  1786. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1787. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1788. return false;
  1789. }
  1790. break;
  1791. case Token_Mod:
  1792. case Token_ModMod:
  1793. case Token_ModEq:
  1794. case Token_ModModEq:
  1795. if (is_type_matrix(main_type)) {
  1796. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1797. return false;
  1798. }
  1799. if (!is_type_integer(type)) {
  1800. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1801. return false;
  1802. } else if (is_type_simd_vector(main_type)) {
  1803. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1804. return false;
  1805. }
  1806. break;
  1807. case Token_AndNot:
  1808. case Token_AndNotEq:
  1809. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1810. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1811. return false;
  1812. }
  1813. break;
  1814. case Token_CmpAnd:
  1815. case Token_CmpOr:
  1816. case Token_CmpAndEq:
  1817. case Token_CmpOrEq:
  1818. if (!is_type_boolean(type)) {
  1819. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1820. return false;
  1821. }
  1822. break;
  1823. default:
  1824. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1830. if (in_value.kind == ExactValue_Invalid) {
  1831. // NOTE(bill): There's already been an error
  1832. return true;
  1833. }
  1834. type = core_type(type);
  1835. if (type == t_invalid) {
  1836. return false;
  1837. } else if (is_type_boolean(type)) {
  1838. return in_value.kind == ExactValue_Bool;
  1839. } else if (is_type_string(type)) {
  1840. return in_value.kind == ExactValue_String;
  1841. } else if (is_type_integer(type) || is_type_rune(type)) {
  1842. if (in_value.kind == ExactValue_Bool) {
  1843. return false;
  1844. }
  1845. ExactValue v = exact_value_to_integer(in_value);
  1846. if (v.kind != ExactValue_Integer) {
  1847. return false;
  1848. }
  1849. if (out_value) *out_value = v;
  1850. if (is_type_untyped(type)) {
  1851. return true;
  1852. }
  1853. BigInt i = v.value_integer;
  1854. i64 byte_size = type_size_of(type);
  1855. BigInt umax = {};
  1856. BigInt imin = {};
  1857. BigInt imax = {};
  1858. if (c->bit_field_bit_size > 0) {
  1859. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1860. big_int_from_u64(&umax, 1);
  1861. big_int_from_i64(&imin, 1);
  1862. big_int_from_i64(&imax, 1);
  1863. BigInt bu = {};
  1864. BigInt bi = {};
  1865. big_int_from_i64(&bu, bit_size);
  1866. big_int_from_i64(&bi, bit_size-1);
  1867. big_int_shl_eq(&umax, &bu);
  1868. mp_decr(&umax);
  1869. big_int_shl_eq(&imin, &bi);
  1870. big_int_neg(&imin, &imin);
  1871. big_int_shl_eq(&imax, &bi);
  1872. mp_decr(&imax);
  1873. } else {
  1874. if (byte_size < 16) {
  1875. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1876. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1877. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1878. } else {
  1879. big_int_from_u64(&umax, 1);
  1880. big_int_from_i64(&imin, 1);
  1881. big_int_from_i64(&imax, 1);
  1882. BigInt bi128 = {};
  1883. BigInt bi127 = {};
  1884. big_int_from_i64(&bi128, 128);
  1885. big_int_from_i64(&bi127, 127);
  1886. big_int_shl_eq(&umax, &bi128);
  1887. mp_decr(&umax);
  1888. big_int_shl_eq(&imin, &bi127);
  1889. big_int_neg(&imin, &imin);
  1890. big_int_shl_eq(&imax, &bi127);
  1891. mp_decr(&imax);
  1892. }
  1893. }
  1894. switch (type->Basic.kind) {
  1895. case Basic_rune:
  1896. case Basic_i8:
  1897. case Basic_i16:
  1898. case Basic_i32:
  1899. case Basic_i64:
  1900. case Basic_i128:
  1901. case Basic_int:
  1902. case Basic_i16le:
  1903. case Basic_i32le:
  1904. case Basic_i64le:
  1905. case Basic_i128le:
  1906. case Basic_i16be:
  1907. case Basic_i32be:
  1908. case Basic_i64be:
  1909. case Basic_i128be:
  1910. {
  1911. // return imin <= i && i <= imax;
  1912. int a = big_int_cmp(&imin, &i);
  1913. int b = big_int_cmp(&i, &imax);
  1914. return (a <= 0) && (b <= 0);
  1915. }
  1916. case Basic_u8:
  1917. case Basic_u16:
  1918. case Basic_u32:
  1919. case Basic_u64:
  1920. case Basic_u128:
  1921. case Basic_uint:
  1922. case Basic_uintptr:
  1923. case Basic_u16le:
  1924. case Basic_u32le:
  1925. case Basic_u64le:
  1926. case Basic_u128le:
  1927. case Basic_u16be:
  1928. case Basic_u32be:
  1929. case Basic_u64be:
  1930. case Basic_u128be:
  1931. {
  1932. // return 0ull <= i && i <= umax;
  1933. int b = big_int_cmp(&i, &umax);
  1934. return !i.sign && (b <= 0);
  1935. }
  1936. case Basic_UntypedInteger:
  1937. return true;
  1938. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1939. }
  1940. } else if (is_type_float(type)) {
  1941. ExactValue v = exact_value_to_float(in_value);
  1942. if (v.kind != ExactValue_Float) {
  1943. return false;
  1944. }
  1945. if (out_value) *out_value = v;
  1946. switch (type->Basic.kind) {
  1947. case Basic_f16:
  1948. case Basic_f32:
  1949. case Basic_f64:
  1950. return true;
  1951. case Basic_f16le:
  1952. case Basic_f16be:
  1953. case Basic_f32le:
  1954. case Basic_f32be:
  1955. case Basic_f64le:
  1956. case Basic_f64be:
  1957. return true;
  1958. case Basic_UntypedFloat:
  1959. return true;
  1960. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1961. }
  1962. } else if (is_type_complex(type)) {
  1963. ExactValue v = exact_value_to_complex(in_value);
  1964. if (v.kind != ExactValue_Complex) {
  1965. return false;
  1966. }
  1967. switch (type->Basic.kind) {
  1968. case Basic_complex32:
  1969. case Basic_complex64:
  1970. case Basic_complex128: {
  1971. ExactValue real = exact_value_real(v);
  1972. ExactValue imag = exact_value_imag(v);
  1973. if (real.kind != ExactValue_Invalid &&
  1974. imag.kind != ExactValue_Invalid) {
  1975. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1976. return true;
  1977. }
  1978. break;
  1979. }
  1980. case Basic_UntypedComplex:
  1981. return true;
  1982. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1983. }
  1984. return false;
  1985. } else if (is_type_quaternion(type)) {
  1986. ExactValue v = exact_value_to_quaternion(in_value);
  1987. if (v.kind != ExactValue_Quaternion) {
  1988. return false;
  1989. }
  1990. switch (type->Basic.kind) {
  1991. case Basic_quaternion64:
  1992. case Basic_quaternion128:
  1993. case Basic_quaternion256: {
  1994. ExactValue real = exact_value_real(v);
  1995. ExactValue imag = exact_value_imag(v);
  1996. ExactValue jmag = exact_value_jmag(v);
  1997. ExactValue kmag = exact_value_kmag(v);
  1998. if (real.kind != ExactValue_Invalid &&
  1999. imag.kind != ExactValue_Invalid) {
  2000. 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));
  2001. return true;
  2002. }
  2003. break;
  2004. }
  2005. case Basic_UntypedComplex:
  2006. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2007. return true;
  2008. case Basic_UntypedQuaternion:
  2009. return true;
  2010. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2011. }
  2012. return false;
  2013. } else if (is_type_pointer(type)) {
  2014. if (in_value.kind == ExactValue_Pointer) {
  2015. return true;
  2016. }
  2017. if (in_value.kind == ExactValue_Integer) {
  2018. return false;
  2019. // return true;
  2020. }
  2021. if (in_value.kind == ExactValue_String) {
  2022. return false;
  2023. }
  2024. if (out_value) *out_value = in_value;
  2025. } else if (is_type_bit_set(type)) {
  2026. if (in_value.kind == ExactValue_Integer) {
  2027. return true;
  2028. }
  2029. }
  2030. return false;
  2031. }
  2032. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2033. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2034. gbString b = type_to_string(type);
  2035. defer (gb_string_free(b));
  2036. if (is_type_enum(o->type)) {
  2037. if (check_is_castable_to(c, o, type)) {
  2038. gbString ot = type_to_string(o->type);
  2039. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2040. gb_string_free(ot);
  2041. }
  2042. return true;
  2043. }
  2044. i64 sz = type_size_of(type);
  2045. i64 bit_size = 8*sz;
  2046. bool size_changed = false;
  2047. if (max_bit_size > 0) {
  2048. size_changed = (bit_size != max_bit_size);
  2049. bit_size = gb_min(bit_size, max_bit_size);
  2050. }
  2051. BigInt *bi = &o->value.value_integer;
  2052. if (is_type_unsigned(type)) {
  2053. BigInt one = big_int_make_u64(1);
  2054. BigInt max_size = big_int_make_u64(1);
  2055. BigInt bits = big_int_make_i64(bit_size);
  2056. big_int_shl_eq(&max_size, &bits);
  2057. big_int_sub_eq(&max_size, &one);
  2058. if (big_int_is_neg(bi)) {
  2059. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2060. BigInt dst = {};
  2061. big_int_neg(&dst, bi);
  2062. if (big_int_cmp(&dst, &max_size) < 0) {
  2063. big_int_sub_eq(&dst, &one);
  2064. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2065. gbString t = type_to_string(type);
  2066. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2067. gb_string_free(t);
  2068. }
  2069. } else {
  2070. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2071. if (size_changed) {
  2072. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2073. } else {
  2074. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2075. }
  2076. }
  2077. } else {
  2078. BigInt zero = big_int_make_u64(0);
  2079. BigInt one = big_int_make_u64(1);
  2080. BigInt max_size = big_int_make_u64(1);
  2081. BigInt bits = big_int_make_i64(bit_size - 1);
  2082. big_int_shl_eq(&max_size, &bits);
  2083. String max_size_str = {};
  2084. if (big_int_is_neg(bi)) {
  2085. big_int_neg(&max_size, &max_size);
  2086. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2087. } else {
  2088. big_int_sub_eq(&max_size, &one);
  2089. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2090. }
  2091. if (size_changed) {
  2092. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2093. } else {
  2094. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2095. }
  2096. }
  2097. return true;
  2098. }
  2099. return false;
  2100. }
  2101. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2102. gbString a = expr_to_string(o->expr);
  2103. gbString b = type_to_string(type);
  2104. defer(
  2105. gb_string_free(b);
  2106. gb_string_free(a);
  2107. );
  2108. Type *src = base_type(o->type);
  2109. Type *dst = base_type(type);
  2110. if (is_type_array(src) && is_type_slice(dst)) {
  2111. Type *s = src->Array.elem;
  2112. Type *d = dst->Slice.elem;
  2113. if (are_types_identical(s, d)) {
  2114. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2115. }
  2116. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2117. Type *s = src->DynamicArray.elem;
  2118. Type *d = dst->Slice.elem;
  2119. if (are_types_identical(s, d)) {
  2120. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2121. }
  2122. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2123. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2124. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2125. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2126. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2127. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2128. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2129. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2130. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2131. return;
  2132. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2133. gbString s = expr_to_string(c->type_hint_expr);
  2134. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2135. gb_string_free(s);
  2136. } else if (is_type_pointer(type) &&
  2137. o->mode == Addressing_Variable &&
  2138. are_types_identical(type_deref(type), o->type)) {
  2139. gbString s = expr_to_string(o->expr);
  2140. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2141. gb_string_free(s);
  2142. } else if (is_type_pointer(o->type) &&
  2143. are_types_identical(type_deref(o->type), type)) {
  2144. gbString s = expr_to_string(o->expr);
  2145. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2146. gb_string_free(s);
  2147. }
  2148. }
  2149. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2150. gbString a = expr_to_string(o->expr);
  2151. gbString b = type_to_string(type);
  2152. defer(
  2153. gb_string_free(b);
  2154. gb_string_free(a);
  2155. );
  2156. Type *src = base_type(o->type);
  2157. Type *dst = base_type(type);
  2158. if (is_type_array(src) && is_type_slice(dst)) {
  2159. Type *s = src->Array.elem;
  2160. Type *d = dst->Slice.elem;
  2161. if (are_types_identical(s, d)) {
  2162. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2163. }
  2164. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2165. if (is_type_uintptr(type)) {
  2166. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2167. } else {
  2168. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2169. i64 x = type_size_of(o->type);
  2170. i64 y = type_size_of(type);
  2171. if (x != y) {
  2172. 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);
  2173. }
  2174. }
  2175. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2176. if (is_type_uintptr(o->type)) {
  2177. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2178. } else {
  2179. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2180. }
  2181. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2182. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2183. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2184. return;
  2185. }
  2186. }
  2187. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2188. GB_ASSERT(o->mode == Addressing_Constant);
  2189. ExactValue out_value = o->value;
  2190. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2191. o->value = out_value;
  2192. return true;
  2193. } else {
  2194. o->value = out_value;
  2195. gbString a = expr_to_string(o->expr);
  2196. gbString b = type_to_string(type);
  2197. gbString c = type_to_string(o->type);
  2198. gbString s = exact_value_to_string(o->value);
  2199. defer(
  2200. gb_string_free(s);
  2201. gb_string_free(c);
  2202. gb_string_free(b);
  2203. gb_string_free(a);
  2204. o->mode = Addressing_Invalid;
  2205. );
  2206. ERROR_BLOCK();
  2207. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2208. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2209. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2210. } else {
  2211. i64 max_bit_size = 0;
  2212. if (ctx->bit_field_bit_size) {
  2213. max_bit_size = ctx->bit_field_bit_size;
  2214. }
  2215. if (are_types_identical(o->type, type)) {
  2216. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2217. } else {
  2218. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2219. }
  2220. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2221. }
  2222. } else {
  2223. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2224. check_assignment_error_suggestion(ctx, o, type);
  2225. }
  2226. return false;
  2227. }
  2228. }
  2229. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2230. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2231. if (o->expr->SelectorExpr.is_bit_field) {
  2232. return true;
  2233. }
  2234. }
  2235. if (o->mode == Addressing_OptionalOk) {
  2236. Ast *expr = unselector_expr(o->expr);
  2237. if (expr->kind != Ast_TypeAssertion) {
  2238. return true;
  2239. }
  2240. ast_node(ta, TypeAssertion, expr);
  2241. TypeAndValue tv = ta->expr->tav;
  2242. if (is_type_pointer(tv.type)) {
  2243. return false;
  2244. }
  2245. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2246. return false;
  2247. }
  2248. if (is_type_any(tv.type)) {
  2249. return false;
  2250. }
  2251. return true;
  2252. }
  2253. if (o->mode == Addressing_MapIndex) {
  2254. return false;
  2255. }
  2256. Ast *expr = unparen_expr(o->expr);
  2257. if (expr->kind == Ast_CompoundLit) {
  2258. return false;
  2259. }
  2260. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2261. }
  2262. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2263. type = base_type(type);
  2264. GB_ASSERT(type->kind == Type_BitSet);
  2265. i64 lower = type->BitSet.lower;
  2266. i64 upper = type->BitSet.upper;
  2267. Type *elem = type->BitSet.elem;
  2268. Type *underlying = type->BitSet.underlying;
  2269. bool is_backed = underlying != nullptr;
  2270. gb_unused(is_backed);
  2271. BigInt b_lower = {};
  2272. BigInt b_upper = {};
  2273. big_int_from_i64(&b_lower, lower);
  2274. big_int_from_i64(&b_upper, upper);
  2275. BigInt one = {};
  2276. big_int_from_u64(&one, 1);
  2277. BigInt mask = {};
  2278. if (elem == nullptr) {
  2279. big_int_from_i64(&mask, -1);
  2280. } else if (is_type_enum(elem)) {
  2281. Type *e = base_type(elem);
  2282. GB_ASSERT(e->kind == Type_Enum);
  2283. gb_unused(e);
  2284. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2285. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2286. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2287. BigInt b_lower_base = {};
  2288. big_int_from_i64(&b_lower_base, lower_base);
  2289. for (Entity *f : e->Enum.fields) {
  2290. if (f->kind != Entity_Constant) {
  2291. continue;
  2292. }
  2293. if (f->Constant.value.kind != ExactValue_Integer) {
  2294. continue;
  2295. }
  2296. BigInt shift_amount = {};
  2297. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2298. BigInt value = {};
  2299. big_int_shl(&value, &one, &shift_amount);
  2300. big_int_or(&mask, &mask, &value);
  2301. }
  2302. } else {
  2303. // TODO(bill): enum range based");
  2304. big_int_from_i64(&mask, -1);
  2305. }
  2306. } else {
  2307. i64 lower_base = lower;
  2308. for (i64 x = lower; x <= upper; x++) {
  2309. BigInt shift_amount = {};
  2310. big_int_from_i64(&shift_amount, x - lower_base);
  2311. BigInt value = {};
  2312. big_int_shl(&value, &one, &shift_amount);
  2313. big_int_or(&mask, &mask, &value);
  2314. }
  2315. }
  2316. ExactValue res = {};
  2317. res.kind = ExactValue_Integer;
  2318. res.value_integer = mask;
  2319. return res;
  2320. }
  2321. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2322. switch (op.kind) {
  2323. case Token_And: { // Pointer address
  2324. if (check_is_not_addressable(c, o)) {
  2325. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2326. ast_node(ue, UnaryExpr, node);
  2327. gbString str = expr_to_string(ue->expr);
  2328. defer (gb_string_free(str));
  2329. Entity *e = entity_of_node(ue->expr);
  2330. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2331. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2332. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2333. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2334. } else {
  2335. switch (o->mode) {
  2336. case Addressing_Constant:
  2337. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2338. break;
  2339. case Addressing_SwizzleValue:
  2340. case Addressing_SwizzleVariable:
  2341. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2342. break;
  2343. default:
  2344. {
  2345. ERROR_BLOCK();
  2346. error(op, "Cannot take the pointer address of '%s'", str);
  2347. if (e == nullptr) {
  2348. break;
  2349. }
  2350. if ((e->flags & EntityFlag_ForValue) != 0) {
  2351. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2352. if (parent_type != nullptr && is_type_string(parent_type)) {
  2353. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2354. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2355. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2356. } else {
  2357. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2358. }
  2359. if (parent_type != nullptr && is_type_map(parent_type)) {
  2360. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2361. } else {
  2362. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2363. }
  2364. }
  2365. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2366. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2367. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2368. }
  2369. }
  2370. break;
  2371. }
  2372. }
  2373. }
  2374. o->mode = Addressing_Invalid;
  2375. return;
  2376. }
  2377. if (o->mode == Addressing_SoaVariable) {
  2378. ast_node(ue, UnaryExpr, node);
  2379. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2380. ast_node(ie, IndexExpr, ue->expr);
  2381. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2382. GB_ASSERT(is_type_soa_struct(soa_type));
  2383. o->type = alloc_type_soa_pointer(soa_type);
  2384. } else {
  2385. o->type = alloc_type_pointer(o->type);
  2386. }
  2387. } else {
  2388. o->type = alloc_type_pointer(o->type);
  2389. }
  2390. switch (o->mode) {
  2391. case Addressing_OptionalOk:
  2392. case Addressing_MapIndex:
  2393. o->mode = Addressing_OptionalOkPtr;
  2394. break;
  2395. default:
  2396. o->mode = Addressing_Value;
  2397. break;
  2398. }
  2399. return;
  2400. }
  2401. }
  2402. if (!check_unary_op(c, o, op)) {
  2403. o->mode = Addressing_Invalid;
  2404. return;
  2405. }
  2406. if (o->mode == Addressing_Constant) {
  2407. Type *type = base_type(o->type);
  2408. if (!is_type_constant_type(o->type)) {
  2409. if (is_type_array_like(o->type)) {
  2410. o->mode = Addressing_Value;
  2411. return;
  2412. }
  2413. gbString xt = type_to_string(o->type);
  2414. gbString err_str = expr_to_string(node);
  2415. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2416. gb_string_free(err_str);
  2417. gb_string_free(xt);
  2418. o->mode = Addressing_Invalid;
  2419. return;
  2420. }
  2421. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2422. gbString err_str = expr_to_string(node);
  2423. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2424. gb_string_free(err_str);
  2425. o->mode = Addressing_Invalid;
  2426. return;
  2427. }
  2428. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2429. gbString err_str = expr_to_string(node);
  2430. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2431. gb_string_free(err_str);
  2432. o->mode = Addressing_Invalid;
  2433. return;
  2434. }
  2435. i32 precision = 0;
  2436. if (is_type_typed(type)) {
  2437. precision = cast(i32)(8 * type_size_of(type));
  2438. }
  2439. bool is_unsigned = is_type_unsigned(type);
  2440. if (is_type_rune(type)) {
  2441. GB_ASSERT(!is_unsigned);
  2442. }
  2443. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2444. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2445. ExactValue mask = exact_bit_set_all_set_mask(type);
  2446. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2447. }
  2448. if (is_type_typed(type)) {
  2449. if (node != nullptr) {
  2450. o->expr = node;
  2451. }
  2452. check_is_expressible(c, o, type);
  2453. }
  2454. return;
  2455. }
  2456. o->mode = Addressing_Value;
  2457. }
  2458. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2459. if (t == nullptr) {
  2460. return;
  2461. }
  2462. t = base_type(t);
  2463. if (!is_type_comparable(t)) {
  2464. return;
  2465. }
  2466. switch (t->kind) {
  2467. case Type_Basic:
  2468. switch (t->Basic.kind) {
  2469. case Basic_complex32:
  2470. add_package_dependency(c, "runtime", "complex32_eq");
  2471. add_package_dependency(c, "runtime", "complex32_ne");
  2472. break;
  2473. case Basic_complex64:
  2474. add_package_dependency(c, "runtime", "complex64_eq");
  2475. add_package_dependency(c, "runtime", "complex64_ne");
  2476. break;
  2477. case Basic_complex128:
  2478. add_package_dependency(c, "runtime", "complex128_eq");
  2479. add_package_dependency(c, "runtime", "complex128_ne");
  2480. break;
  2481. case Basic_quaternion64:
  2482. add_package_dependency(c, "runtime", "quaternion64_eq");
  2483. add_package_dependency(c, "runtime", "quaternion64_ne");
  2484. break;
  2485. case Basic_quaternion128:
  2486. add_package_dependency(c, "runtime", "quaternion128_eq");
  2487. add_package_dependency(c, "runtime", "quaternion128_ne");
  2488. break;
  2489. case Basic_quaternion256:
  2490. add_package_dependency(c, "runtime", "quaternion256_eq");
  2491. add_package_dependency(c, "runtime", "quaternion256_ne");
  2492. break;
  2493. case Basic_cstring:
  2494. add_package_dependency(c, "runtime", "cstring_eq");
  2495. add_package_dependency(c, "runtime", "cstring_ne");
  2496. break;
  2497. case Basic_string:
  2498. add_package_dependency(c, "runtime", "string_eq");
  2499. add_package_dependency(c, "runtime", "string_ne");
  2500. break;
  2501. }
  2502. break;
  2503. case Type_Struct:
  2504. for (Entity *field : t->Struct.fields) {
  2505. add_comparison_procedures_for_fields(c, field->type);
  2506. }
  2507. break;
  2508. }
  2509. }
  2510. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2511. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2512. bool comp = are_types_identical(x->type, y->type);
  2513. switch (op) {
  2514. case Token_CmpEq: /* comp = comp; */ break;
  2515. case Token_NotEq: comp = !comp; break;
  2516. }
  2517. x->mode = Addressing_Constant;
  2518. x->type = t_untyped_bool;
  2519. x->value = exact_value_bool(comp);
  2520. return;
  2521. }
  2522. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2523. add_type_info_type(c, x->type);
  2524. add_type_info_type(c, y->type);
  2525. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2526. x->mode = Addressing_Value;
  2527. x->type = t_untyped_bool;
  2528. return;
  2529. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2530. add_type_info_type(c, x->type);
  2531. add_type_info_type(c, y->type);
  2532. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2533. x->mode = Addressing_Value;
  2534. x->type = t_untyped_bool;
  2535. return;
  2536. }
  2537. TEMPORARY_ALLOCATOR_GUARD();
  2538. gbString err_str = nullptr;
  2539. if (check_is_assignable_to(c, x, y->type) ||
  2540. check_is_assignable_to(c, y, x->type)) {
  2541. Type *err_type = x->type;
  2542. bool defined = false;
  2543. switch (op) {
  2544. case Token_CmpEq:
  2545. case Token_NotEq:
  2546. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2547. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2548. (is_operand_nil(*y) && type_has_nil(x->type));
  2549. break;
  2550. case Token_Lt:
  2551. case Token_Gt:
  2552. case Token_LtEq:
  2553. case Token_GtEq:
  2554. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2555. defined = true;
  2556. } else {
  2557. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2558. }
  2559. break;
  2560. }
  2561. if (!defined) {
  2562. gbString xs = type_to_string(x->type, temporary_allocator());
  2563. gbString ys = type_to_string(y->type, temporary_allocator());
  2564. if (!is_type_comparable(x->type)) {
  2565. err_str = gb_string_make(temporary_allocator(),
  2566. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2567. );
  2568. } else if (!is_type_comparable(y->type)) {
  2569. err_str = gb_string_make(temporary_allocator(),
  2570. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2571. );
  2572. } else {
  2573. err_str = gb_string_make(temporary_allocator(),
  2574. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2575. );
  2576. }
  2577. } else {
  2578. Type *comparison_type = x->type;
  2579. if (x->type == err_type && is_operand_nil(*x)) {
  2580. comparison_type = y->type;
  2581. }
  2582. add_comparison_procedures_for_fields(c, comparison_type);
  2583. }
  2584. } else {
  2585. gbString xt, yt;
  2586. if (x->mode == Addressing_ProcGroup) {
  2587. xt = gb_string_make(temporary_allocator(), "procedure group");
  2588. } else {
  2589. xt = type_to_string(x->type);
  2590. }
  2591. if (y->mode == Addressing_ProcGroup) {
  2592. yt = gb_string_make(temporary_allocator(), "procedure group");
  2593. } else {
  2594. yt = type_to_string(y->type);
  2595. }
  2596. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2597. }
  2598. if (err_str != nullptr) {
  2599. error(node, "Cannot compare expression. %s.", err_str);
  2600. x->type = t_untyped_bool;
  2601. } else {
  2602. if (x->mode == Addressing_Constant &&
  2603. y->mode == Addressing_Constant) {
  2604. if (is_type_constant_type(x->type)) {
  2605. if (is_type_bit_set(x->type)) {
  2606. switch (op) {
  2607. case Token_CmpEq:
  2608. case Token_NotEq:
  2609. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2610. break;
  2611. case Token_Lt:
  2612. case Token_LtEq:
  2613. {
  2614. ExactValue lhs = x->value;
  2615. ExactValue rhs = y->value;
  2616. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2617. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2618. if (op == Token_Lt) {
  2619. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2620. }
  2621. x->value = res;
  2622. break;
  2623. }
  2624. case Token_Gt:
  2625. case Token_GtEq:
  2626. {
  2627. ExactValue lhs = x->value;
  2628. ExactValue rhs = y->value;
  2629. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2630. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2631. if (op == Token_Gt) {
  2632. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2633. }
  2634. x->value = res;
  2635. break;
  2636. }
  2637. }
  2638. } else {
  2639. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2640. }
  2641. } else {
  2642. x->mode = Addressing_Value;
  2643. }
  2644. } else {
  2645. x->mode = Addressing_Value;
  2646. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2647. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2648. i64 size = 0;
  2649. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2650. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2651. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2652. switch (op) {
  2653. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2654. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2655. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2656. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2657. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2658. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2659. }
  2660. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2661. switch (op) {
  2662. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2663. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2664. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2665. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2666. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2667. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2668. }
  2669. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2670. switch (op) {
  2671. case Token_CmpEq:
  2672. switch (8*size) {
  2673. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2674. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2675. }
  2676. break;
  2677. case Token_NotEq:
  2678. switch (8*size) {
  2679. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2680. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2681. }
  2682. break;
  2683. }
  2684. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2685. switch (op) {
  2686. case Token_CmpEq:
  2687. switch (8*size) {
  2688. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2689. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2690. }
  2691. break;
  2692. case Token_NotEq:
  2693. switch (8*size) {
  2694. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2695. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2696. }
  2697. break;
  2698. }
  2699. }
  2700. }
  2701. x->type = t_untyped_bool;
  2702. }
  2703. }
  2704. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2705. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2706. ast_node(be, BinaryExpr, node);
  2707. bool y_is_untyped = is_type_untyped(y->type);
  2708. if (y_is_untyped) {
  2709. convert_to_typed(c, y, t_untyped_integer);
  2710. if (y->mode == Addressing_Invalid) {
  2711. x->mode = Addressing_Invalid;
  2712. return;
  2713. }
  2714. } else if (!is_type_unsigned(y->type)) {
  2715. gbString y_str = expr_to_string(y->expr);
  2716. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2717. gb_string_free(y_str);
  2718. x->mode = Addressing_Invalid;
  2719. return;
  2720. }
  2721. bool x_is_untyped = is_type_untyped(x->type);
  2722. if (!(x_is_untyped || is_type_integer(x->type))) {
  2723. gbString x_str = expr_to_string(x->expr);
  2724. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2725. gb_string_free(x_str);
  2726. x->mode = Addressing_Invalid;
  2727. return;
  2728. }
  2729. if (y->mode == Addressing_Constant) {
  2730. if (big_int_is_neg(&y->value.value_integer)) {
  2731. gbString y_str = expr_to_string(y->expr);
  2732. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2733. gb_string_free(y_str);
  2734. x->mode = Addressing_Invalid;
  2735. return;
  2736. }
  2737. BigInt max_shift = {};
  2738. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2739. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2740. gbString y_str = expr_to_string(y->expr);
  2741. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2742. gb_string_free(y_str);
  2743. x->mode = Addressing_Invalid;
  2744. return;
  2745. }
  2746. if (x->mode == Addressing_Constant) {
  2747. if (x_is_untyped) {
  2748. convert_to_typed(c, x, t_untyped_integer);
  2749. if (x->mode == Addressing_Invalid) {
  2750. return;
  2751. }
  2752. x->expr = node;
  2753. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2754. return;
  2755. }
  2756. x->expr = node;
  2757. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2758. check_is_expressible(c, x, x->type);
  2759. return;
  2760. }
  2761. if (y_is_untyped) {
  2762. convert_to_typed(c, y, t_uint);
  2763. }
  2764. return;
  2765. }
  2766. if (x->mode == Addressing_Constant) {
  2767. if (x_is_untyped) {
  2768. if (type_hint) {
  2769. if (is_type_integer(type_hint)) {
  2770. convert_to_typed(c, x, type_hint);
  2771. } else if (is_type_any(type_hint)) {
  2772. convert_to_typed(c, x, default_type(t_untyped_integer));
  2773. } else {
  2774. gbString x_str = expr_to_string(x->expr);
  2775. gbString type_str = type_to_string(type_hint);
  2776. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2777. gb_string_free(x_str);
  2778. gb_string_free(type_str);
  2779. x->mode = Addressing_Invalid;
  2780. return;
  2781. }
  2782. } else {
  2783. check_is_expressible(c, x, default_type(t_untyped_integer));
  2784. }
  2785. if (x->mode == Addressing_Invalid) {
  2786. return;
  2787. }
  2788. }
  2789. x->mode = Addressing_Value;
  2790. }
  2791. }
  2792. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2793. if (check_is_assignable_to(c, operand, y)) {
  2794. return true;
  2795. }
  2796. bool is_constant = operand->mode == Addressing_Constant;
  2797. Type *x = operand->type;
  2798. Type *src = core_type(x);
  2799. Type *dst = core_type(y);
  2800. if (are_types_identical(src, dst)) {
  2801. return true;
  2802. }
  2803. // if (is_type_tuple(src)) {
  2804. // Ast *expr = unparen_expr(operand->expr);
  2805. // if (expr && expr->kind == Ast_CallExpr) {
  2806. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2807. // ast_node(ce, CallExpr, expr);
  2808. // Type *pt = base_type(type_of_expr(ce->proc));
  2809. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2810. // if (pt->Proc.result_count > 0) {
  2811. // Operand op = *operand;
  2812. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2813. // bool ok = check_is_castable_to(c, &op, y);
  2814. // if (ok) {
  2815. // ce->optional_ok_one = true;
  2816. // }
  2817. // return ok;
  2818. // }
  2819. // }
  2820. // }
  2821. // }
  2822. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2823. if (is_type_u8_array(dst)) {
  2824. String s = operand->value.value_string;
  2825. return s.len == dst->Array.count;
  2826. }
  2827. if (is_type_rune_array(dst)) {
  2828. String s = operand->value.value_string;
  2829. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2830. }
  2831. }
  2832. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2833. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2834. return dst->Array.count == src->Array.count;
  2835. }
  2836. }
  2837. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2838. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2839. }
  2840. // Cast between booleans and integers
  2841. if (is_type_boolean(src) || is_type_integer(src)) {
  2842. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2843. return true;
  2844. }
  2845. }
  2846. // Cast between numbers
  2847. if (is_type_integer(src) || is_type_float(src)) {
  2848. if (is_type_integer(dst) || is_type_float(dst)) {
  2849. return true;
  2850. }
  2851. }
  2852. if (is_type_bit_field(src)) {
  2853. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2854. }
  2855. if (is_type_bit_field(dst)) {
  2856. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2857. }
  2858. if (is_type_integer(src) && is_type_rune(dst)) {
  2859. return true;
  2860. }
  2861. if (is_type_rune(src) && is_type_integer(dst)) {
  2862. return true;
  2863. }
  2864. if (is_type_complex(src) && is_type_complex(dst)) {
  2865. return true;
  2866. }
  2867. if (is_type_float(src) && is_type_complex(dst)) {
  2868. return true;
  2869. }
  2870. if (is_type_float(src) && is_type_quaternion(dst)) {
  2871. return true;
  2872. }
  2873. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2874. return true;
  2875. }
  2876. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2877. return true;
  2878. }
  2879. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2880. GB_ASSERT(src->kind == Type_Matrix);
  2881. GB_ASSERT(dst->kind == Type_Matrix);
  2882. Operand op = *operand;
  2883. op.type = src->Matrix.elem;
  2884. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2885. return false;
  2886. }
  2887. if (src->Matrix.row_count != src->Matrix.column_count) {
  2888. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2889. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2890. return src_count == dst_count;
  2891. }
  2892. return is_matrix_square(dst) && is_matrix_square(src);
  2893. }
  2894. // Cast between pointers
  2895. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2896. return true;
  2897. }
  2898. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2899. return true;
  2900. }
  2901. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2902. return true;
  2903. }
  2904. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2905. return true;
  2906. }
  2907. // uintptr <-> pointer
  2908. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2909. return true;
  2910. }
  2911. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2912. return true;
  2913. }
  2914. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2915. return true;
  2916. }
  2917. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2918. return true;
  2919. }
  2920. // []byte/[]u8 <-> string (not cstring)
  2921. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2922. return true;
  2923. }
  2924. // cstring -> string
  2925. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2926. if (operand->mode != Addressing_Constant) {
  2927. add_package_dependency(c, "runtime", "cstring_to_string");
  2928. }
  2929. return true;
  2930. }
  2931. // cstring -> ^u8
  2932. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2933. return !is_constant;
  2934. }
  2935. // cstring -> [^]u8
  2936. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2937. return !is_constant;
  2938. }
  2939. // cstring -> rawptr
  2940. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2941. return !is_constant;
  2942. }
  2943. // ^u8 -> cstring
  2944. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2945. return !is_constant;
  2946. }
  2947. // [^]u8 -> cstring
  2948. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2949. return !is_constant;
  2950. }
  2951. // rawptr -> cstring
  2952. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2953. return !is_constant;
  2954. }
  2955. // proc <-> proc
  2956. if (is_type_proc(src) && is_type_proc(dst)) {
  2957. if (is_type_polymorphic(dst)) {
  2958. if (is_type_polymorphic(src) &&
  2959. operand->mode == Addressing_Variable) {
  2960. return true;
  2961. }
  2962. return false;
  2963. }
  2964. return true;
  2965. }
  2966. // proc -> rawptr
  2967. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2968. return true;
  2969. }
  2970. // rawptr -> proc
  2971. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2972. return true;
  2973. }
  2974. if (is_type_array(dst)) {
  2975. Type *elem = base_array_type(dst);
  2976. if (check_is_castable_to(c, operand, elem)) {
  2977. return true;
  2978. }
  2979. }
  2980. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2981. if (src->SimdVector.count != dst->SimdVector.count) {
  2982. return false;
  2983. }
  2984. Type *elem_src = base_array_type(src);
  2985. Type *elem_dst = base_array_type(dst);
  2986. Operand x = {};
  2987. x.type = elem_src;
  2988. x.mode = Addressing_Value;
  2989. return check_is_castable_to(c, &x, elem_dst);
  2990. }
  2991. if (is_type_simd_vector(dst)) {
  2992. Type *elem = base_array_type(dst);
  2993. if (check_is_castable_to(c, operand, elem)) {
  2994. return true;
  2995. }
  2996. }
  2997. return false;
  2998. }
  2999. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3000. bool is_const_expr = x->mode == Addressing_Constant;
  3001. Type *bt = base_type(type);
  3002. if (is_const_expr && is_type_constant_type(bt)) {
  3003. if (core_type(bt)->kind == Type_Basic) {
  3004. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3005. return true;
  3006. } else if (check_is_castable_to(c, x, type)) {
  3007. if (is_type_pointer(type)) {
  3008. return true;
  3009. }
  3010. }
  3011. } else if (check_is_castable_to(c, x, type)) {
  3012. x->value = {};
  3013. x->mode = Addressing_Value;
  3014. return true;
  3015. }
  3016. } else if (check_is_castable_to(c, x, type)) {
  3017. if (x->mode != Addressing_Constant) {
  3018. x->mode = Addressing_Value;
  3019. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3020. x->mode = Addressing_Value;
  3021. } else if (is_type_union(type)) {
  3022. x->mode = Addressing_Value;
  3023. }
  3024. if (x->mode == Addressing_Value) {
  3025. x->value = {};
  3026. }
  3027. return true;
  3028. }
  3029. return false;
  3030. }
  3031. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3032. if (!is_operand_value(*x)) {
  3033. error(x->expr, "Only values can be casted");
  3034. x->mode = Addressing_Invalid;
  3035. return;
  3036. }
  3037. bool is_const_expr = x->mode == Addressing_Constant;
  3038. bool can_convert = check_cast_internal(c, x, type);
  3039. if (!can_convert) {
  3040. TEMPORARY_ALLOCATOR_GUARD();
  3041. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3042. gbString to_type = type_to_string(type, temporary_allocator());
  3043. gbString from_type = type_to_string(x->type, temporary_allocator());
  3044. x->mode = Addressing_Invalid;
  3045. ERROR_BLOCK();
  3046. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3047. if (is_const_expr) {
  3048. gbString val_str = exact_value_to_string(x->value);
  3049. if (is_type_float(x->type) && is_type_integer(type)) {
  3050. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3051. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3052. x->mode = Addressing_Constant;
  3053. x->type = type;
  3054. } else {
  3055. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3056. if (is_type_numeric(type)) {
  3057. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3058. x->mode = Addressing_Constant;
  3059. x->type = type;
  3060. }
  3061. }
  3062. gb_string_free(val_str);
  3063. }
  3064. check_cast_error_suggestion(c, x, type);
  3065. return;
  3066. }
  3067. if (is_type_untyped(x->type)) {
  3068. Type *final_type = type;
  3069. if (is_const_expr && !is_type_constant_type(type)) {
  3070. if (is_type_union(type)) {
  3071. convert_to_typed(c, x, type);
  3072. }
  3073. final_type = default_type(x->type);
  3074. }
  3075. update_untyped_expr_type(c, x->expr, final_type, true);
  3076. } else {
  3077. Type *src = core_type(x->type);
  3078. Type *dst = core_type(type);
  3079. if (src != dst) {
  3080. bool const REQUIRE = true;
  3081. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3082. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3083. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3084. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3085. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3086. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3087. } else if (src == t_f16 && is_type_float(dst)) {
  3088. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3089. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3090. } else if (is_type_float(dst) && dst == t_f16) {
  3091. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3092. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3093. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3094. }
  3095. }
  3096. // If we check polymorphic procedures, we risk erring on
  3097. // identical casts that cannot be foreseen or otherwise
  3098. // forbidden, so just skip them.
  3099. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3100. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3101. Type *src_exact = x->type;
  3102. Type *dst_exact = type;
  3103. if (src_exact != nullptr &&
  3104. dst_exact != nullptr &&
  3105. are_types_identical(src_exact, dst_exact)
  3106. ) {
  3107. gbString oper_str = expr_to_string(x->expr);
  3108. gbString to_type = type_to_string(dst_exact);
  3109. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3110. gb_string_free(oper_str);
  3111. gb_string_free(to_type);
  3112. }
  3113. }
  3114. }
  3115. x->type = type;
  3116. }
  3117. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3118. if (!is_operand_value(*o)) {
  3119. error(o->expr, "'transmute' can only be applied to values");
  3120. o->mode = Addressing_Invalid;
  3121. return false;
  3122. }
  3123. Operand src = *o;
  3124. Type *src_t = o->type;
  3125. Type *dst_t = t;
  3126. Type *src_bt = base_type(src_t);
  3127. Type *dst_bt = base_type(dst_t);
  3128. if (is_type_untyped(src_t)) {
  3129. gbString expr_str = expr_to_string(o->expr);
  3130. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3131. gb_string_free(expr_str);
  3132. o->mode = Addressing_Invalid;
  3133. o->expr = node;
  3134. return false;
  3135. }
  3136. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3137. GB_ASSERT(global_error_collector.count != 0);
  3138. o->mode = Addressing_Invalid;
  3139. o->expr = node;
  3140. return false;
  3141. }
  3142. if (src_bt == nullptr || src_bt == t_invalid) {
  3143. // NOTE(bill): this should be an error
  3144. GB_ASSERT(global_error_collector.count != 0);
  3145. o->mode = Addressing_Value;
  3146. o->expr = node;
  3147. o->type = dst_t;
  3148. return true;
  3149. }
  3150. i64 srcz = type_size_of(src_t);
  3151. i64 dstz = type_size_of(dst_t);
  3152. if (srcz != dstz) {
  3153. gbString expr_str = expr_to_string(o->expr);
  3154. gbString type_str = type_to_string(dst_t);
  3155. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3156. gb_string_free(type_str);
  3157. gb_string_free(expr_str);
  3158. o->mode = Addressing_Invalid;
  3159. o->expr = node;
  3160. return false;
  3161. }
  3162. o->expr = node;
  3163. o->type = dst_t;
  3164. if (o->mode == Addressing_Constant) {
  3165. if (are_types_identical(src_bt, dst_bt)) {
  3166. return true;
  3167. }
  3168. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3169. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3170. if (types_have_same_internal_endian(src_t, dst_t)) {
  3171. ExactValue src_v = exact_value_to_integer(o->value);
  3172. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3173. BigInt v = src_v.value_integer;
  3174. BigInt smax = {};
  3175. BigInt umax = {};
  3176. big_int_from_u64(&smax, 0);
  3177. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3178. big_int_from_u64(&umax, 1);
  3179. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3180. big_int_shl_eq(&umax, &sz_in_bits);
  3181. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3182. if (big_int_cmp(&v, &smax) >= 0) {
  3183. big_int_sub_eq(&v, &umax);
  3184. }
  3185. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3186. if (big_int_is_neg(&v)) {
  3187. big_int_add_eq(&v, &umax);
  3188. }
  3189. }
  3190. o->value.kind = ExactValue_Integer;
  3191. o->value.value_integer = v;
  3192. return true;
  3193. }
  3194. }
  3195. } else {
  3196. // If we check polymorphic procedures, we risk erring on
  3197. // identical casts that cannot be foreseen or otherwise
  3198. // forbidden, so just skip them.
  3199. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3200. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3201. check_is_castable_to(c, &src, dst_t)) {
  3202. if (are_types_identical(src_t, dst_t)) {
  3203. gbString oper_str = expr_to_string(o->expr);
  3204. gbString to_type = type_to_string(dst_t);
  3205. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3206. gb_string_free(oper_str);
  3207. gb_string_free(to_type);
  3208. } else if (is_type_internally_pointer_like(src_t) &&
  3209. is_type_internally_pointer_like(dst_t)) {
  3210. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3211. } else if (are_types_identical(src_bt, dst_bt)) {
  3212. gbString oper_str = expr_to_string(o->expr);
  3213. gbString to_type = type_to_string(dst_t);
  3214. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3215. gb_string_free(oper_str);
  3216. gb_string_free(to_type);
  3217. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3218. types_have_same_internal_endian(src_t, dst_t) &&
  3219. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3220. gbString oper_type = type_to_string(src_t);
  3221. gbString to_type = type_to_string(dst_t);
  3222. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since both are integers of the same endianness, from '%s' to '%s'", oper_type, to_type);
  3223. gb_string_free(to_type);
  3224. gb_string_free(oper_type);
  3225. }
  3226. }
  3227. }
  3228. o->mode = Addressing_Value;
  3229. o->value = {};
  3230. return true;
  3231. }
  3232. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3233. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3234. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3235. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3236. }
  3237. }
  3238. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3239. if (check_is_assignable_to(c, y, x->type)) {
  3240. if (check_binary_op(c, x, op)) {
  3241. return true;
  3242. }
  3243. }
  3244. }
  3245. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3246. if (check_is_assignable_to(c, y, x->type)) {
  3247. if (check_binary_op(c, x, op)) {
  3248. return true;
  3249. }
  3250. }
  3251. }
  3252. return false;
  3253. }
  3254. gb_internal bool is_ise_expr(Ast *node) {
  3255. node = unparen_expr(node);
  3256. return node->kind == Ast_ImplicitSelectorExpr;
  3257. }
  3258. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3259. if (use_lhs_as_type_hint) { // RHS in this case
  3260. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3261. }
  3262. return false;
  3263. }
  3264. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3265. Type *xt = base_type(matrix);
  3266. if (type_hint != nullptr) {
  3267. Type *th = base_type(type_hint);
  3268. if (are_types_identical(th, xt)) {
  3269. return type_hint;
  3270. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3271. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3272. // ignore
  3273. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3274. xt->Matrix.column_count == th->Matrix.column_count) {
  3275. return type_hint;
  3276. }
  3277. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3278. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3279. // ignore
  3280. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3281. return type_hint;
  3282. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3283. return type_hint;
  3284. }
  3285. }
  3286. }
  3287. return matrix;
  3288. }
  3289. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3290. if (!check_binary_op(c, x, op)) {
  3291. x->mode = Addressing_Invalid;
  3292. return;
  3293. }
  3294. Type *xt = base_type(x->type);
  3295. Type *yt = base_type(y->type);
  3296. if (is_type_matrix(x->type)) {
  3297. GB_ASSERT(xt->kind == Type_Matrix);
  3298. if (op.kind == Token_Mul) {
  3299. if (yt->kind == Type_Matrix) {
  3300. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3301. goto matrix_error;
  3302. }
  3303. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3304. goto matrix_error;
  3305. }
  3306. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3307. goto matrix_error;
  3308. }
  3309. x->mode = Addressing_Value;
  3310. if (are_types_identical(xt, yt)) {
  3311. if (are_types_identical(x->type, y->type)) {
  3312. return;
  3313. }
  3314. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3315. // prefer the named type
  3316. x->type = y->type;
  3317. }
  3318. } else {
  3319. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3320. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3321. }
  3322. goto matrix_success;
  3323. } else if (yt->kind == Type_Array) {
  3324. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3325. goto matrix_error;
  3326. }
  3327. if (xt->Matrix.column_count != yt->Array.count) {
  3328. goto matrix_error;
  3329. }
  3330. // Treat arrays as column vectors
  3331. x->mode = Addressing_Value;
  3332. if (xt->Matrix.row_count == yt->Array.count) {
  3333. x->type = y->type;
  3334. } else {
  3335. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3336. }
  3337. goto matrix_success;
  3338. }
  3339. }
  3340. if (!are_types_identical(xt, yt)) {
  3341. goto matrix_error;
  3342. }
  3343. x->mode = Addressing_Value;
  3344. x->type = xt;
  3345. goto matrix_success;
  3346. } else {
  3347. GB_ASSERT(!is_type_matrix(xt));
  3348. GB_ASSERT(is_type_matrix(yt));
  3349. if (op.kind == Token_Mul) {
  3350. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3351. if (xt->kind == Type_Array) {
  3352. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3353. goto matrix_error;
  3354. }
  3355. if (xt->Array.count != yt->Matrix.row_count) {
  3356. goto matrix_error;
  3357. }
  3358. // Treat arrays as row vectors
  3359. x->mode = Addressing_Value;
  3360. if (yt->Matrix.column_count == xt->Array.count) {
  3361. x->type = x->type;
  3362. } else {
  3363. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3364. }
  3365. goto matrix_success;
  3366. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3367. x->type = check_matrix_type_hint(y->type, type_hint);
  3368. return;
  3369. }
  3370. }
  3371. if (!are_types_identical(xt, yt)) {
  3372. goto matrix_error;
  3373. }
  3374. x->mode = Addressing_Value;
  3375. x->type = xt;
  3376. goto matrix_success;
  3377. }
  3378. matrix_success:
  3379. x->type = check_matrix_type_hint(x->type, type_hint);
  3380. return;
  3381. matrix_error:
  3382. gbString xts = type_to_string(x->type);
  3383. gbString yts = type_to_string(y->type);
  3384. gbString expr_str = expr_to_string(x->expr);
  3385. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3386. gb_string_free(expr_str);
  3387. gb_string_free(yts);
  3388. gb_string_free(xts);
  3389. x->type = t_invalid;
  3390. x->mode = Addressing_Invalid;
  3391. return;
  3392. }
  3393. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3394. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3395. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3396. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3397. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3398. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3399. }
  3400. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3401. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3402. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3403. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3404. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3405. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3406. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3407. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3408. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3409. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3410. }
  3411. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3412. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3413. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3414. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3415. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3416. case Basic_u128:
  3417. case Basic_i128:
  3418. if (is_arch_wasm()) {
  3419. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3420. }
  3421. break;
  3422. }
  3423. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3424. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3425. case Basic_u128:
  3426. case Basic_i128:
  3427. if (is_arch_wasm()) {
  3428. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3429. }
  3430. break;
  3431. }
  3432. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3433. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3434. case Basic_u128:
  3435. case Basic_i128:
  3436. if (is_arch_wasm()) {
  3437. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3438. }
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3444. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3445. Operand y_ = {}, *y = &y_;
  3446. ast_node(be, BinaryExpr, node);
  3447. defer({
  3448. node->viral_state_flags |= be->left->viral_state_flags;
  3449. node->viral_state_flags |= be->right->viral_state_flags;
  3450. });
  3451. Token op = be->op;
  3452. switch (op.kind) {
  3453. case Token_CmpEq:
  3454. case Token_NotEq: {
  3455. // NOTE(bill): Allow comparisons between types
  3456. if (is_ise_expr(be->left)) {
  3457. // Evalute the right before the left for an '.X' expression
  3458. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3459. check_expr_or_type(c, x, be->left, y->type);
  3460. } else {
  3461. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3462. check_expr_or_type(c, y, be->right, x->type);
  3463. }
  3464. bool xt = x->mode == Addressing_Type;
  3465. bool yt = y->mode == Addressing_Type;
  3466. // If only one is a type, this is an error
  3467. if (xt ^ yt) {
  3468. GB_ASSERT(xt != yt);
  3469. if (xt) {
  3470. if (!is_type_typeid(y->type)) {
  3471. error_operand_not_expression(x);
  3472. }
  3473. }
  3474. if (yt) {
  3475. if (!is_type_typeid(x->type)) {
  3476. error_operand_not_expression(y);
  3477. }
  3478. }
  3479. }
  3480. break;
  3481. }
  3482. case Token_in:
  3483. case Token_not_in:
  3484. {
  3485. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3486. check_expr(c, y, be->right);
  3487. Type *rhs_type = type_deref(y->type);
  3488. if (rhs_type == nullptr) {
  3489. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3490. x->mode = Addressing_Invalid;
  3491. x->expr = node;
  3492. return;
  3493. }
  3494. if (is_type_bit_set(rhs_type)) {
  3495. Type *elem = base_type(rhs_type)->BitSet.elem;
  3496. check_expr_with_type_hint(c, x, be->left, elem);
  3497. } else if (is_type_map(rhs_type)) {
  3498. Type *key = base_type(rhs_type)->Map.key;
  3499. check_expr_with_type_hint(c, x, be->left, key);
  3500. } else {
  3501. check_expr(c, x, be->left);
  3502. }
  3503. if (x->mode == Addressing_Invalid) {
  3504. return;
  3505. }
  3506. if (y->mode == Addressing_Invalid) {
  3507. x->mode = Addressing_Invalid;
  3508. x->expr = y->expr;
  3509. return;
  3510. }
  3511. if (is_type_map(rhs_type)) {
  3512. Type *yt = base_type(rhs_type);
  3513. if (op.kind == Token_in) {
  3514. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3515. } else {
  3516. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3517. }
  3518. add_map_get_dependencies(c);
  3519. } else if (is_type_bit_set(rhs_type)) {
  3520. Type *yt = base_type(rhs_type);
  3521. if (op.kind == Token_in) {
  3522. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3523. } else {
  3524. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3525. }
  3526. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3527. ExactValue k = exact_value_to_integer(x->value);
  3528. ExactValue v = exact_value_to_integer(y->value);
  3529. GB_ASSERT(k.kind == ExactValue_Integer);
  3530. GB_ASSERT(v.kind == ExactValue_Integer);
  3531. i64 key = big_int_to_i64(&k.value_integer);
  3532. i64 lower = yt->BitSet.lower;
  3533. i64 upper = yt->BitSet.upper;
  3534. if (lower <= key && key <= upper) {
  3535. i64 bit = 1ll<<key;
  3536. i64 bits = big_int_to_i64(&v.value_integer);
  3537. x->mode = Addressing_Constant;
  3538. x->type = t_untyped_bool;
  3539. if (op.kind == Token_in) {
  3540. x->value = exact_value_bool((bit & bits) != 0);
  3541. } else {
  3542. x->value = exact_value_bool((bit & bits) == 0);
  3543. }
  3544. x->expr = node;
  3545. return;
  3546. } else {
  3547. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3548. x->mode = Addressing_Invalid;
  3549. }
  3550. }
  3551. } else {
  3552. gbString t = type_to_string(y->type);
  3553. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3554. gb_string_free(t);
  3555. x->expr = node;
  3556. x->mode = Addressing_Invalid;
  3557. return;
  3558. }
  3559. if (x->mode != Addressing_Invalid) {
  3560. x->mode = Addressing_Value;
  3561. x->type = t_untyped_bool;
  3562. }
  3563. x->expr = node;
  3564. return;
  3565. }
  3566. default:
  3567. if (is_ise_expr(be->left)) {
  3568. // Evalute the right before the left for an '.X' expression
  3569. check_expr_or_type(c, y, be->right, type_hint);
  3570. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3571. check_expr_or_type(c, x, be->left, y->type);
  3572. } else {
  3573. check_expr_with_type_hint(c, x, be->left, type_hint);
  3574. }
  3575. } else {
  3576. check_expr_with_type_hint(c, x, be->left, type_hint);
  3577. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3578. check_expr_with_type_hint(c, y, be->right, x->type);
  3579. } else {
  3580. check_expr_with_type_hint(c, y, be->right, type_hint);
  3581. }
  3582. }
  3583. break;
  3584. }
  3585. if (x->mode == Addressing_Invalid) {
  3586. return;
  3587. }
  3588. if (y->mode == Addressing_Invalid) {
  3589. x->mode = Addressing_Invalid;
  3590. x->expr = y->expr;
  3591. return;
  3592. }
  3593. if (x->mode == Addressing_Builtin) {
  3594. x->mode = Addressing_Invalid;
  3595. error(x->expr, "built-in expression in binary expression");
  3596. return;
  3597. }
  3598. if (y->mode == Addressing_Builtin) {
  3599. x->mode = Addressing_Invalid;
  3600. error(y->expr, "built-in expression in binary expression");
  3601. return;
  3602. }
  3603. if (x->mode == Addressing_ProcGroup) {
  3604. x->mode = Addressing_Invalid;
  3605. if (x->proc_group != nullptr) {
  3606. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3607. } else {
  3608. error(x->expr, "procedure group used in binary expression");
  3609. }
  3610. return;
  3611. }
  3612. if (y->mode == Addressing_ProcGroup) {
  3613. x->mode = Addressing_Invalid;
  3614. if (x->proc_group != nullptr) {
  3615. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3616. } else {
  3617. error(y->expr, "procedure group used in binary expression");
  3618. }
  3619. return;
  3620. }
  3621. bool REQUIRE = true;
  3622. Type *btx = base_type(x->type);
  3623. Type *bty = base_type(y->type);
  3624. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3625. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3626. if (token_is_shift(op.kind)) {
  3627. check_shift(c, x, y, node, type_hint);
  3628. return;
  3629. }
  3630. switch (op.kind) {
  3631. case Token_Quo:
  3632. case Token_Mod:
  3633. case Token_ModMod:
  3634. case Token_QuoEq:
  3635. case Token_ModEq:
  3636. case Token_ModModEq:
  3637. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3638. is_type_float(x->type) && is_type_untyped(x->type)) {
  3639. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3640. gbString t = type_to_string(y->type);
  3641. if (x->value.kind != ExactValue_Invalid) {
  3642. gbString s = exact_value_to_string(x->value);
  3643. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3644. gb_string_free(s);
  3645. } else {
  3646. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3647. }
  3648. gb_string_free(t);
  3649. }
  3650. break;
  3651. }
  3652. convert_to_typed(c, x, y->type);
  3653. if (x->mode == Addressing_Invalid) {
  3654. return;
  3655. }
  3656. convert_to_typed(c, y, x->type);
  3657. if (y->mode == Addressing_Invalid) {
  3658. x->mode = Addressing_Invalid;
  3659. return;
  3660. }
  3661. if (token_is_comparison(op.kind)) {
  3662. check_comparison(c, node, x, y, op.kind);
  3663. return;
  3664. }
  3665. if (check_binary_array_expr(c, op, x, y)) {
  3666. x->mode = Addressing_Value;
  3667. x->type = x->type;
  3668. return;
  3669. }
  3670. if (check_binary_array_expr(c, op, y, x)) {
  3671. x->mode = Addressing_Value;
  3672. x->type = y->type;
  3673. return;
  3674. }
  3675. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3676. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3677. x->expr = node;
  3678. return;
  3679. }
  3680. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3681. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3682. // NOTE(bill, 2022-06-26)
  3683. // Allow any boolean types within `&&` and `||`
  3684. // This is an exception to all other binary expressions since the result
  3685. // of a comparison will always be an untyped boolean, and allowing
  3686. // any boolean between these two simplifies a lot of expressions
  3687. } else if (!are_types_identical(x->type, y->type)) {
  3688. if (x->type != t_invalid &&
  3689. y->type != t_invalid) {
  3690. gbString xt = type_to_string(x->type);
  3691. gbString yt = type_to_string(y->type);
  3692. gbString expr_str = expr_to_string(node);
  3693. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3694. gb_string_free(expr_str);
  3695. gb_string_free(yt);
  3696. gb_string_free(xt);
  3697. }
  3698. x->mode = Addressing_Invalid;
  3699. return;
  3700. }
  3701. if (!check_binary_op(c, x, op)) {
  3702. x->mode = Addressing_Invalid;
  3703. return;
  3704. }
  3705. switch (op.kind) {
  3706. case Token_Quo:
  3707. case Token_Mod:
  3708. case Token_ModMod:
  3709. case Token_QuoEq:
  3710. case Token_ModEq:
  3711. case Token_ModModEq:
  3712. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3713. y->mode == Addressing_Constant) {
  3714. bool fail = false;
  3715. switch (y->value.kind) {
  3716. case ExactValue_Integer:
  3717. if (big_int_is_zero(&y->value.value_integer)) {
  3718. fail = true;
  3719. }
  3720. break;
  3721. case ExactValue_Float:
  3722. if (y->value.value_float == 0.0) {
  3723. fail = true;
  3724. }
  3725. break;
  3726. }
  3727. if (fail) {
  3728. error(y->expr, "Division by zero not allowed");
  3729. x->mode = Addressing_Invalid;
  3730. return;
  3731. }
  3732. }
  3733. break;
  3734. case Token_CmpAnd:
  3735. case Token_CmpOr:
  3736. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3737. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3738. }
  3739. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3740. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3741. }
  3742. break;
  3743. }
  3744. if (x->mode == Addressing_Constant &&
  3745. y->mode == Addressing_Constant) {
  3746. ExactValue a = x->value;
  3747. ExactValue b = y->value;
  3748. if (!is_type_constant_type(x->type)) {
  3749. x->mode = Addressing_Value;
  3750. return;
  3751. }
  3752. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3753. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3754. }
  3755. if (is_type_bit_set(x->type)) {
  3756. switch (op.kind) {
  3757. case Token_Add: op.kind = Token_Or; break;
  3758. case Token_Sub: op.kind = Token_AndNot; break;
  3759. }
  3760. }
  3761. x->value = exact_binary_operator_value(op.kind, a, b);
  3762. if (is_type_typed(x->type)) {
  3763. if (node != nullptr) {
  3764. x->expr = node;
  3765. }
  3766. check_is_expressible(c, x, x->type);
  3767. }
  3768. return;
  3769. } else if (is_type_string(x->type)) {
  3770. error(node, "String concatenation is only allowed with constant strings");
  3771. x->mode = Addressing_Invalid;
  3772. return;
  3773. }
  3774. x->mode = Addressing_Value;
  3775. }
  3776. gb_internal Operand make_operand_from_node(Ast *node) {
  3777. GB_ASSERT(node != nullptr);
  3778. Operand x = {};
  3779. x.expr = node;
  3780. x.mode = node->tav.mode;
  3781. x.type = node->tav.type;
  3782. x.value = node->tav.value;
  3783. return x;
  3784. }
  3785. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3786. GB_ASSERT(e != nullptr);
  3787. ExprInfo *old = check_get_expr_info(c, e);
  3788. if (old == nullptr) {
  3789. if (type != nullptr && type != t_invalid) {
  3790. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3791. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3792. if (e->kind == Ast_TernaryIfExpr) {
  3793. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3794. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3795. }
  3796. }
  3797. }
  3798. return;
  3799. }
  3800. switch (e->kind) {
  3801. case_ast_node(ue, UnaryExpr, e);
  3802. if (old->value.kind != ExactValue_Invalid) {
  3803. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3804. // They don't need to be updated as they will be updated later and
  3805. // checked at the end of general checking stage.
  3806. break;
  3807. }
  3808. update_untyped_expr_type(c, ue->expr, type, final);
  3809. case_end;
  3810. case_ast_node(be, BinaryExpr, e);
  3811. if (old->value.kind != ExactValue_Invalid) {
  3812. // See above note in UnaryExpr case
  3813. break;
  3814. }
  3815. if (token_is_comparison(be->op.kind)) {
  3816. // NOTE(bill): Do nothing as the types are fine
  3817. } else if (token_is_shift(be->op.kind)) {
  3818. update_untyped_expr_type(c, be->left, type, final);
  3819. } else {
  3820. update_untyped_expr_type(c, be->left, type, final);
  3821. update_untyped_expr_type(c, be->right, type, final);
  3822. }
  3823. case_end;
  3824. case_ast_node(te, TernaryIfExpr, e);
  3825. if (old->value.kind != ExactValue_Invalid) {
  3826. // See above note in UnaryExpr case
  3827. break;
  3828. }
  3829. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3830. // having an untyped value
  3831. Operand x = make_operand_from_node(te->x);
  3832. Operand y = make_operand_from_node(te->y);
  3833. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3834. update_untyped_expr_type(c, te->x, type, final);
  3835. }
  3836. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3837. update_untyped_expr_type(c, te->y, type, final);
  3838. }
  3839. case_end;
  3840. case_ast_node(te, TernaryWhenExpr, e);
  3841. if (old->value.kind != ExactValue_Invalid) {
  3842. // See above note in UnaryExpr case
  3843. break;
  3844. }
  3845. update_untyped_expr_type(c, te->x, type, final);
  3846. update_untyped_expr_type(c, te->y, type, final);
  3847. case_end;
  3848. case_ast_node(ore, OrReturnExpr, e);
  3849. if (old->value.kind != ExactValue_Invalid) {
  3850. // See above note in UnaryExpr case
  3851. break;
  3852. }
  3853. update_untyped_expr_type(c, ore->expr, type, final);
  3854. case_end;
  3855. case_ast_node(obe, OrBranchExpr, e);
  3856. if (old->value.kind != ExactValue_Invalid) {
  3857. // See above note in UnaryExpr case
  3858. break;
  3859. }
  3860. update_untyped_expr_type(c, obe->expr, type, final);
  3861. case_end;
  3862. case_ast_node(oee, OrElseExpr, e);
  3863. if (old->value.kind != ExactValue_Invalid) {
  3864. // See above note in UnaryExpr case
  3865. break;
  3866. }
  3867. update_untyped_expr_type(c, oee->x, type, final);
  3868. update_untyped_expr_type(c, oee->y, type, final);
  3869. case_end;
  3870. case_ast_node(pe, ParenExpr, e);
  3871. update_untyped_expr_type(c, pe->expr, type, final);
  3872. case_end;
  3873. }
  3874. if (!final && is_type_untyped(type)) {
  3875. old->type = base_type(type);
  3876. return;
  3877. }
  3878. // We need to remove it and then give it a new one
  3879. check_remove_expr_info(c, e);
  3880. if (old->is_lhs && !is_type_integer(type)) {
  3881. gbString expr_str = expr_to_string(e);
  3882. gbString type_str = type_to_string(type);
  3883. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3884. gb_string_free(type_str);
  3885. gb_string_free(expr_str);
  3886. return;
  3887. }
  3888. add_type_and_value(c, e, old->mode, type, old->value);
  3889. }
  3890. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3891. GB_ASSERT(e != nullptr);
  3892. ExprInfo *found = check_get_expr_info(c, e);
  3893. if (found) {
  3894. found->value = value;
  3895. }
  3896. }
  3897. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3898. gbString expr_str = expr_to_string(operand->expr);
  3899. gbString type_str = type_to_string(target_type);
  3900. gbString from_type_str = type_to_string(operand->type);
  3901. char const *extra_text = "";
  3902. if (operand->mode == Addressing_Constant) {
  3903. if (big_int_is_zero(&operand->value.value_integer)) {
  3904. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3905. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3906. extra_text = " - Did you want 'nil'?";
  3907. }
  3908. }
  3909. }
  3910. if (!ignore_error_block) {
  3911. begin_error_block();
  3912. }
  3913. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3914. if (operand->value.kind == ExactValue_String) {
  3915. String key = operand->value.value_string;
  3916. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3917. Type *et = base_type(target_type);
  3918. check_did_you_mean_type(key, et->Enum.fields, ".");
  3919. }
  3920. }
  3921. gb_string_free(from_type_str);
  3922. gb_string_free(type_str);
  3923. gb_string_free(expr_str);
  3924. operand->mode = Addressing_Invalid;
  3925. if (!ignore_error_block) {
  3926. end_error_block();
  3927. }
  3928. }
  3929. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3930. Type *t = core_type(type);
  3931. if (is_type_boolean(t)) {
  3932. // v = exact_value_to_boolean(v);
  3933. } else if (is_type_float(t)) {
  3934. v = exact_value_to_float(v);
  3935. } else if (is_type_integer(t)) {
  3936. v = exact_value_to_integer(v);
  3937. } else if (is_type_pointer(t)) {
  3938. v = exact_value_to_integer(v);
  3939. } else if (is_type_complex(t)) {
  3940. v = exact_value_to_complex(v);
  3941. } else if (is_type_quaternion(t)) {
  3942. v = exact_value_to_quaternion(v);
  3943. }
  3944. return v;
  3945. }
  3946. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3947. // GB_ASSERT_NOT_NULL(target_type);
  3948. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  3949. operand->mode == Addressing_Type ||
  3950. is_type_typed(operand->type) ||
  3951. target_type == t_invalid) {
  3952. return;
  3953. }
  3954. if (is_type_untyped(target_type)) {
  3955. GB_ASSERT(operand->type->kind == Type_Basic);
  3956. GB_ASSERT(target_type->kind == Type_Basic);
  3957. BasicKind x_kind = operand->type->Basic.kind;
  3958. BasicKind y_kind = target_type->Basic.kind;
  3959. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3960. if (x_kind < y_kind) {
  3961. operand->type = target_type;
  3962. update_untyped_expr_type(c, operand->expr, target_type, false);
  3963. }
  3964. } else if (x_kind != y_kind) {
  3965. operand->mode = Addressing_Invalid;
  3966. convert_untyped_error(c, operand, target_type);
  3967. return;
  3968. }
  3969. return;
  3970. }
  3971. Type *t = base_type(target_type);
  3972. if (c->in_enum_type) {
  3973. t = core_type(target_type);
  3974. }
  3975. switch (t->kind) {
  3976. case Type_Basic:
  3977. if (operand->mode == Addressing_Constant) {
  3978. check_is_expressible(c, operand, t);
  3979. if (operand->mode == Addressing_Invalid) {
  3980. return;
  3981. }
  3982. update_untyped_expr_value(c, operand->expr, operand->value);
  3983. } else {
  3984. switch (operand->type->Basic.kind) {
  3985. case Basic_UntypedBool:
  3986. if (!is_type_boolean(target_type)) {
  3987. operand->mode = Addressing_Invalid;
  3988. convert_untyped_error(c, operand, target_type);
  3989. return;
  3990. }
  3991. break;
  3992. case Basic_UntypedInteger:
  3993. case Basic_UntypedFloat:
  3994. case Basic_UntypedComplex:
  3995. case Basic_UntypedQuaternion:
  3996. case Basic_UntypedRune:
  3997. if (!is_type_numeric(target_type)) {
  3998. operand->mode = Addressing_Invalid;
  3999. convert_untyped_error(c, operand, target_type);
  4000. return;
  4001. }
  4002. break;
  4003. case Basic_UntypedNil:
  4004. if (is_type_any(target_type)) {
  4005. // target_type = t_untyped_nil;
  4006. } else if (is_type_cstring(target_type)) {
  4007. // target_type = t_untyped_nil;
  4008. } else if (!type_has_nil(target_type)) {
  4009. operand->mode = Addressing_Invalid;
  4010. convert_untyped_error(c, operand, target_type);
  4011. return;
  4012. }
  4013. break;
  4014. }
  4015. }
  4016. break;
  4017. case Type_Array: {
  4018. Type *elem = base_array_type(t);
  4019. if (check_is_assignable_to(c, operand, elem)) {
  4020. operand->mode = Addressing_Value;
  4021. } else {
  4022. if (operand->value.kind == ExactValue_String) {
  4023. String s = operand->value.value_string;
  4024. if (is_type_u8_array(t)) {
  4025. if (s.len == t->Array.count) {
  4026. break;
  4027. }
  4028. } else if (is_type_rune_array(t)) {
  4029. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4030. if (rune_count == t->Array.count) {
  4031. break;
  4032. }
  4033. }
  4034. }
  4035. operand->mode = Addressing_Invalid;
  4036. convert_untyped_error(c, operand, target_type);
  4037. return;
  4038. }
  4039. break;
  4040. }
  4041. case Type_SimdVector: {
  4042. Type *elem = base_array_type(t);
  4043. if (check_is_assignable_to(c, operand, elem)) {
  4044. operand->mode = Addressing_Value;
  4045. } else {
  4046. operand->mode = Addressing_Invalid;
  4047. convert_untyped_error(c, operand, target_type);
  4048. return;
  4049. }
  4050. break;
  4051. }
  4052. case Type_Matrix: {
  4053. Type *elem = base_array_type(t);
  4054. if (check_is_assignable_to(c, operand, elem)) {
  4055. if (t->Matrix.row_count != t->Matrix.column_count) {
  4056. operand->mode = Addressing_Invalid;
  4057. ERROR_BLOCK();
  4058. convert_untyped_error(c, operand, target_type, true);
  4059. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4060. return;
  4061. } else {
  4062. operand->mode = Addressing_Value;
  4063. }
  4064. } else {
  4065. operand->mode = Addressing_Invalid;
  4066. convert_untyped_error(c, operand, target_type);
  4067. return;
  4068. }
  4069. break;
  4070. }
  4071. case Type_Union:
  4072. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4073. // as a kind of transition period
  4074. if (!build_context.strict_style &&
  4075. operand->mode == Addressing_Constant &&
  4076. target_type->kind == Type_Named &&
  4077. (c->pkg == nullptr || c->pkg->name != "os") &&
  4078. target_type->Named.name == "Error") {
  4079. Entity *e = target_type->Named.type_name;
  4080. if (e->pkg && e->pkg->name == "os") {
  4081. if (is_exact_value_zero(operand->value) &&
  4082. (operand->value.kind == ExactValue_Integer ||
  4083. operand->value.kind == ExactValue_Float)) {
  4084. operand->mode = Addressing_Value;
  4085. // target_type = t_untyped_nil;
  4086. operand->value = empty_exact_value;
  4087. update_untyped_expr_value(c, operand->expr, operand->value);
  4088. break;
  4089. }
  4090. }
  4091. }
  4092. // "fallthrough"
  4093. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4094. TEMPORARY_ALLOCATOR_GUARD();
  4095. isize count = t->Union.variants.count;
  4096. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4097. isize valid_count = 0;
  4098. isize first_success_index = -1;
  4099. for_array(i, t->Union.variants) {
  4100. Type *vt = t->Union.variants[i];
  4101. i64 score = 0;
  4102. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4103. valids[valid_count].index = i;
  4104. valids[valid_count].score = score;
  4105. valid_count += 1;
  4106. if (first_success_index < 0) {
  4107. first_success_index = i;
  4108. }
  4109. }
  4110. }
  4111. if (valid_count > 1) {
  4112. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4113. i64 best_score = valids[0].score;
  4114. for (isize i = 1; i < valid_count; i++) {
  4115. auto v = valids[i];
  4116. if (best_score > v.score) {
  4117. valid_count = i;
  4118. break;
  4119. }
  4120. best_score = v.score;
  4121. }
  4122. first_success_index = valids[0].index;
  4123. }
  4124. gbString type_str = type_to_string(target_type);
  4125. defer (gb_string_free(type_str));
  4126. if (valid_count == 1) {
  4127. Type *new_type = t->Union.variants[first_success_index];
  4128. target_type = new_type;
  4129. if (is_type_union(new_type)) {
  4130. convert_to_typed(c, operand, new_type);
  4131. break;
  4132. }
  4133. operand->type = new_type;
  4134. operand->mode = Addressing_Value;
  4135. break;
  4136. } else if (valid_count > 1) {
  4137. ERROR_BLOCK();
  4138. GB_ASSERT(first_success_index >= 0);
  4139. operand->mode = Addressing_Invalid;
  4140. convert_untyped_error(c, operand, target_type, true);
  4141. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4142. i32 j = 0;
  4143. for (i32 i = 0; i < valid_count; i++) {
  4144. ValidIndexAndScore valid = valids[i];
  4145. if (j > 0 && valid_count > 2) error_line(", ");
  4146. if (j == valid_count-1) {
  4147. if (valid_count == 2) error_line(" ");
  4148. error_line("or ");
  4149. }
  4150. gbString str = type_to_string(t->Union.variants[valid.index]);
  4151. error_line("'%s'", str);
  4152. gb_string_free(str);
  4153. j++;
  4154. }
  4155. error_line("\n\n");
  4156. return;
  4157. } else if (is_type_untyped_uninit(operand->type)) {
  4158. target_type = t_untyped_uninit;
  4159. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4160. ERROR_BLOCK();
  4161. operand->mode = Addressing_Invalid;
  4162. convert_untyped_error(c, operand, target_type, true);
  4163. if (count > 0) {
  4164. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4165. error_line("\t");
  4166. for (i32 i = 0; i < count; i++) {
  4167. Type *v = t->Union.variants[i];
  4168. if (i > 0 && count > 2) error_line(", ");
  4169. if (i == count-1) {
  4170. if (count == 2) error_line(" ");
  4171. if (count > 1) {
  4172. error_line("or ");
  4173. }
  4174. }
  4175. gbString str = type_to_string(v);
  4176. error_line("'%s'", str);
  4177. gb_string_free(str);
  4178. }
  4179. error_line("\n\n");
  4180. }
  4181. return;
  4182. }
  4183. }
  4184. /* fallthrough */
  4185. default:
  4186. if (is_type_untyped_uninit(operand->type)) {
  4187. target_type = t_untyped_uninit;
  4188. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4189. target_type = t_untyped_nil;
  4190. } else {
  4191. operand->mode = Addressing_Invalid;
  4192. convert_untyped_error(c, operand, target_type);
  4193. return;
  4194. }
  4195. break;
  4196. }
  4197. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4198. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4199. } else {
  4200. target_type = default_type(operand->type);
  4201. }
  4202. }
  4203. update_untyped_expr_type(c, operand->expr, target_type, true);
  4204. operand->type = target_type;
  4205. }
  4206. 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) {
  4207. Operand operand = {Addressing_Invalid};
  4208. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4209. if (operand.mode == Addressing_Invalid) {
  4210. if (value) *value = 0;
  4211. // NOTE(bill): return true here to propagate the errors better
  4212. return true;
  4213. }
  4214. Type *index_type = t_int;
  4215. if (type_hint != nullptr) {
  4216. index_type = type_hint;
  4217. }
  4218. convert_to_typed(c, &operand, index_type);
  4219. if (operand.mode == Addressing_Invalid) {
  4220. if (value) *value = 0;
  4221. return false;
  4222. }
  4223. if (type_hint != nullptr) {
  4224. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4225. gbString expr_str = expr_to_string(operand.expr);
  4226. gbString index_type_str = type_to_string(type_hint);
  4227. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4228. gb_string_free(index_type_str);
  4229. gb_string_free(expr_str);
  4230. if (value) *value = 0;
  4231. return false;
  4232. }
  4233. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4234. gbString expr_str = expr_to_string(operand.expr);
  4235. gbString type_str = type_to_string(operand.type);
  4236. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4237. gb_string_free(type_str);
  4238. gb_string_free(expr_str);
  4239. if (value) *value = 0;
  4240. return false;
  4241. }
  4242. if (operand.mode == Addressing_Constant &&
  4243. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4244. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4245. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4246. TEMPORARY_ALLOCATOR_GUARD();
  4247. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4248. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4249. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4250. if (value) *value = 0;
  4251. return false;
  4252. }
  4253. if (max_count >= 0) {
  4254. if (is_type_enum(index_type)) {
  4255. Type *bt = base_type(index_type);
  4256. GB_ASSERT(bt->kind == Type_Enum);
  4257. ExactValue const &lo = *bt->Enum.min_value;
  4258. ExactValue const &hi = *bt->Enum.max_value;
  4259. String lo_str = {};
  4260. String hi_str = {};
  4261. if (bt->Enum.fields.count > 0) {
  4262. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4263. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4264. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4265. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4266. }
  4267. bool out_of_bounds = false;
  4268. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4269. out_of_bounds = true;
  4270. }
  4271. if (out_of_bounds) {
  4272. gbString expr_str = expr_to_string(operand.expr);
  4273. if (lo_str.len > 0) {
  4274. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4275. } else {
  4276. gbString index_type_str = type_to_string(index_type);
  4277. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4278. gb_string_free(index_type_str);
  4279. }
  4280. gb_string_free(expr_str);
  4281. return false;
  4282. }
  4283. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4284. return true;
  4285. } else { // NOTE(bill): Do array bound checking
  4286. i64 v = -1;
  4287. if (i.used <= 1) {
  4288. v = big_int_to_i64(&i);
  4289. }
  4290. if (value) *value = v;
  4291. bool out_of_bounds = false;
  4292. if (v < 0) {
  4293. out_of_bounds = true;
  4294. } else if (open_range) {
  4295. out_of_bounds = v > max_count;
  4296. } else {
  4297. out_of_bounds = v >= max_count;
  4298. }
  4299. if (out_of_bounds) {
  4300. TEMPORARY_ALLOCATOR_GUARD();
  4301. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4302. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4303. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4304. return false;
  4305. }
  4306. return true;
  4307. }
  4308. } else {
  4309. if (value) *value = exact_value_to_i64(operand.value);
  4310. return true;
  4311. }
  4312. }
  4313. // NOTE(bill): It's alright :D
  4314. if (value) *value = -1;
  4315. return true;
  4316. }
  4317. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4318. if (value.kind == ExactValue_String) {
  4319. GB_ASSERT(0 <= index && index < value.value_string.len);
  4320. u8 val = value.value_string[index];
  4321. if (success_) *success_ = true;
  4322. if (finish_) *finish_ = true;
  4323. return exact_value_u64(val);
  4324. }
  4325. if (value.kind != ExactValue_Compound) {
  4326. if (success_) *success_ = true;
  4327. if (finish_) *finish_ = true;
  4328. return value;
  4329. }
  4330. Ast *node = value.value_compound;
  4331. switch (node->kind) {
  4332. case_ast_node(cl, CompoundLit, node);
  4333. if (cl->elems.count == 0) {
  4334. if (success_) *success_ = true;
  4335. if (finish_) *finish_ = true;
  4336. return empty_exact_value;
  4337. }
  4338. if (cl->elems[0]->kind == Ast_FieldValue) {
  4339. if (is_type_struct(node->tav.type)) {
  4340. bool found = false;
  4341. for (Ast *elem : cl->elems) {
  4342. if (elem->kind != Ast_FieldValue) {
  4343. continue;
  4344. }
  4345. ast_node(fv, FieldValue, elem);
  4346. String name = fv->field->Ident.token.string;
  4347. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4348. defer (array_free(&sub_sel.index));
  4349. if (sub_sel.index.count > 0 &&
  4350. sub_sel.index[0] == index) {
  4351. value = fv->value->tav.value;
  4352. found = true;
  4353. break;
  4354. }
  4355. }
  4356. if (!found) {
  4357. // Use the zero value if it is not found
  4358. value = {};
  4359. }
  4360. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4361. for (Ast *elem : cl->elems) {
  4362. if (elem->kind != Ast_FieldValue) {
  4363. continue;
  4364. }
  4365. ast_node(fv, FieldValue, elem);
  4366. if (is_ast_range(fv->field)) {
  4367. ast_node(ie, BinaryExpr, fv->field);
  4368. TypeAndValue lo_tav = ie->left->tav;
  4369. TypeAndValue hi_tav = ie->right->tav;
  4370. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4371. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4372. TokenKind op = ie->op.kind;
  4373. i64 lo = exact_value_to_i64(lo_tav.value);
  4374. i64 hi = exact_value_to_i64(hi_tav.value);
  4375. i64 corrected_index = index;
  4376. if (is_type_enumerated_array(node->tav.type)) {
  4377. Type *bt = base_type(node->tav.type);
  4378. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4379. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4380. }
  4381. if (op != Token_RangeHalf) {
  4382. if (lo <= corrected_index && corrected_index <= hi) {
  4383. TypeAndValue tav = fv->value->tav;
  4384. if (success_) *success_ = true;
  4385. if (finish_) *finish_ = false;
  4386. return tav.value;
  4387. }
  4388. } else {
  4389. if (lo <= corrected_index && corrected_index < hi) {
  4390. TypeAndValue tav = fv->value->tav;
  4391. if (success_) *success_ = true;
  4392. if (finish_) *finish_ = false;
  4393. return tav.value;
  4394. }
  4395. }
  4396. } else {
  4397. TypeAndValue index_tav = fv->field->tav;
  4398. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4399. ExactValue index_value = index_tav.value;
  4400. if (is_type_enumerated_array(node->tav.type)) {
  4401. Type *bt = base_type(node->tav.type);
  4402. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4403. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4404. }
  4405. i64 field_index = exact_value_to_i64(index_value);
  4406. if (index == field_index) {
  4407. TypeAndValue tav = fv->value->tav;
  4408. if (success_) *success_ = true;
  4409. if (finish_) *finish_ = false;
  4410. return tav.value;
  4411. }
  4412. }
  4413. }
  4414. }
  4415. } else {
  4416. i32 count = (i32)cl->elems.count;
  4417. if (count < index) {
  4418. if (success_) *success_ = false;
  4419. if (finish_) *finish_ = true;
  4420. return empty_exact_value;
  4421. }
  4422. if (cl->elems.count <= index) {
  4423. if (success_) *success_ = false;
  4424. if (finish_) *finish_ = false;
  4425. return value;
  4426. }
  4427. TypeAndValue tav = cl->elems[index]->tav;
  4428. if (tav.mode == Addressing_Constant) {
  4429. if (success_) *success_ = true;
  4430. if (finish_) *finish_ = false;
  4431. return tav.value;
  4432. } else if (is_type_proc(tav.type)) {
  4433. if (success_) *success_ = true;
  4434. if (finish_) *finish_ = false;
  4435. return tav.value;
  4436. } else {
  4437. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4438. if (success_) *success_ = true;
  4439. if (finish_) *finish_ = false;
  4440. return tav.value;
  4441. }
  4442. }
  4443. case_end;
  4444. default:
  4445. if (success_) *success_ = true;
  4446. if (finish_) *finish_ = true;
  4447. return empty_exact_value;
  4448. }
  4449. if (finish_) *finish_ = false;
  4450. return value;
  4451. }
  4452. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4453. if (operand->mode != Addressing_Constant) {
  4454. if (success_) *success_ = false;
  4455. return empty_exact_value;
  4456. }
  4457. if (sel.indirect) {
  4458. if (success_) *success_ = false;
  4459. return empty_exact_value;
  4460. }
  4461. if (sel.index.count == 0) {
  4462. if (success_) *success_ = false;
  4463. return empty_exact_value;
  4464. }
  4465. ExactValue value = operand->value;
  4466. if (value.kind == ExactValue_Compound) {
  4467. while (sel.index.count > 0) {
  4468. i32 index = sel.index[0];
  4469. sel = sub_selection(sel, 1);
  4470. bool finish = false;
  4471. value = get_constant_field_single(c, value, index, success_, &finish);
  4472. if (finish) {
  4473. return value;
  4474. }
  4475. }
  4476. if (success_) *success_ = true;
  4477. return value;
  4478. } else if (value.kind == ExactValue_Quaternion) {
  4479. // @QuaternionLayout
  4480. Quaternion256 q = *value.value_quaternion;
  4481. GB_ASSERT(sel.index.count == 1);
  4482. switch (sel.index[0]) {
  4483. case 3: // w
  4484. if (success_) *success_ = true;
  4485. return exact_value_float(q.real);
  4486. case 0: // x
  4487. if (success_) *success_ = true;
  4488. return exact_value_float(q.imag);
  4489. case 1: // y
  4490. if (success_) *success_ = true;
  4491. return exact_value_float(q.jmag);
  4492. case 2: // z
  4493. if (success_) *success_ = true;
  4494. return exact_value_float(q.kmag);
  4495. }
  4496. if (success_) *success_ = false;
  4497. return empty_exact_value;
  4498. } else if (value.kind == ExactValue_Complex) {
  4499. // @QuaternionLayout
  4500. Complex128 c = *value.value_complex;
  4501. GB_ASSERT(sel.index.count == 1);
  4502. switch (sel.index[0]) {
  4503. case 0: // real
  4504. if (success_) *success_ = true;
  4505. return exact_value_float(c.real);
  4506. case 1: // imag
  4507. if (success_) *success_ = true;
  4508. return exact_value_float(c.imag);
  4509. }
  4510. if (success_) *success_ = false;
  4511. return empty_exact_value;
  4512. }
  4513. if (success_) *success_ = true;
  4514. return empty_exact_value;
  4515. }
  4516. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4517. Type *array_type = base_type(type_deref(original_type));
  4518. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4519. if (array_type->kind == Type_SimdVector) {
  4520. Type *elem_type = array_type->SimdVector.elem;
  4521. return alloc_type_simd_vector(new_count, elem_type);
  4522. }
  4523. Type *elem_type = array_type->Array.elem;
  4524. Type *swizzle_array_type = nullptr;
  4525. Type *bth = base_type(type_deref(type_hint));
  4526. if (bth != nullptr && bth->kind == Type_Array &&
  4527. bth->Array.count == new_count &&
  4528. are_types_identical(bth->Array.elem, elem_type)) {
  4529. swizzle_array_type = type_hint;
  4530. } else {
  4531. i64 max_count = array_type->Array.count;
  4532. if (new_count == max_count) {
  4533. swizzle_array_type = original_type;
  4534. } else {
  4535. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4536. }
  4537. }
  4538. return swizzle_array_type;
  4539. }
  4540. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4541. bool is_declared = entity != nullptr;
  4542. if (is_declared) {
  4543. if (entity->kind == Entity_Builtin) {
  4544. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4545. // This means that we should just ignore the found result through it
  4546. *allow_builtin = entity->scope == import_scope ||
  4547. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4548. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4549. is_declared = false;
  4550. }
  4551. }
  4552. return is_declared;
  4553. }
  4554. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4555. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4556. if (node == nullptr) {
  4557. return nullptr;
  4558. }
  4559. /*if (node->kind == Ast_TernaryWhenExpr) {
  4560. ast_node(we, TernaryWhenExpr, node);
  4561. if (we->cond == nullptr) {
  4562. return nullptr;
  4563. }
  4564. if (we->cond->tav.mode != Addressing_Constant) {
  4565. return nullptr;
  4566. }
  4567. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4568. return nullptr;
  4569. }
  4570. if (we->cond->tav.value.value_bool) {
  4571. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4572. } else {
  4573. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4574. return e;
  4575. }
  4576. } else */if (node->kind == Ast_Ident) {
  4577. String name = node->Ident.token.string;
  4578. return scope_lookup(c->scope, name);
  4579. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4580. ast_node(se, SelectorExpr, node);
  4581. if (se->token.kind == Token_ArrowRight) {
  4582. return nullptr;
  4583. }
  4584. Ast *op_expr = se->expr;
  4585. Ast *selector = unparen_expr(se->selector);
  4586. if (selector == nullptr) {
  4587. return nullptr;
  4588. }
  4589. if (selector->kind != Ast_Ident) {
  4590. return nullptr;
  4591. }
  4592. Entity *entity = nullptr;
  4593. Entity *expr_entity = nullptr;
  4594. bool check_op_expr = true;
  4595. if (op_expr->kind == Ast_Ident) {
  4596. String op_name = op_expr->Ident.token.string;
  4597. Entity *e = scope_lookup(c->scope, op_name);
  4598. if (e == nullptr) {
  4599. return nullptr;
  4600. }
  4601. add_entity_use(c, op_expr, e);
  4602. expr_entity = e;
  4603. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4604. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4605. // It pretty much needs to be in this order and this way
  4606. // If you can clean this up, please do but be really careful
  4607. String import_name = op_name;
  4608. Scope *import_scope = e->ImportName.scope;
  4609. String entity_name = selector->Ident.token.string;
  4610. check_op_expr = false;
  4611. entity = scope_lookup_current(import_scope, entity_name);
  4612. bool allow_builtin = false;
  4613. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4614. return nullptr;
  4615. }
  4616. check_entity_decl(c, entity, nullptr, nullptr);
  4617. if (entity->kind == Entity_ProcGroup) {
  4618. return entity;
  4619. }
  4620. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4621. }
  4622. }
  4623. Operand operand = {};
  4624. if (check_op_expr) {
  4625. check_expr_base(c, &operand, op_expr, nullptr);
  4626. if (operand.mode == Addressing_Invalid) {
  4627. return nullptr;
  4628. }
  4629. }
  4630. if (entity == nullptr && selector->kind == Ast_Ident) {
  4631. String field_name = selector->Ident.token.string;
  4632. if (is_type_dynamic_array(type_deref(operand.type))) {
  4633. init_mem_allocator(c->checker);
  4634. }
  4635. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4636. entity = sel.entity;
  4637. }
  4638. if (entity != nullptr) {
  4639. return entity;
  4640. }
  4641. }
  4642. return nullptr;
  4643. }
  4644. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4645. ast_node(se, SelectorExpr, node);
  4646. bool check_op_expr = true;
  4647. Entity *expr_entity = nullptr;
  4648. Entity *entity = nullptr;
  4649. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4650. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4651. ERROR_BLOCK();
  4652. error(node, "Illegal use of -> selector shorthand outside of a call");
  4653. gbString x = expr_to_string(se->expr);
  4654. gbString y = expr_to_string(se->selector);
  4655. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4656. gb_string_free(y);
  4657. gb_string_free(x);
  4658. // TODO(bill): Should this terminate here or propagate onwards?
  4659. // operand->mode = Addressing_Invalid;
  4660. // operand->expr = node;
  4661. // return nullptr;
  4662. }
  4663. operand->expr = node;
  4664. Ast *op_expr = se->expr;
  4665. Ast *selector = unparen_expr(se->selector);
  4666. if (selector == nullptr) {
  4667. operand->mode = Addressing_Invalid;
  4668. operand->expr = node;
  4669. return nullptr;
  4670. }
  4671. if (selector->kind != Ast_Ident) {
  4672. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4673. operand->mode = Addressing_Invalid;
  4674. operand->expr = node;
  4675. return nullptr;
  4676. }
  4677. if (op_expr->kind == Ast_Ident) {
  4678. String op_name = op_expr->Ident.token.string;
  4679. Entity *e = scope_lookup(c->scope, op_name);
  4680. add_entity_use(c, op_expr, e);
  4681. expr_entity = e;
  4682. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4683. gbString sel_str = expr_to_string(selector);
  4684. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4685. gb_string_free(sel_str);
  4686. operand->mode = Addressing_Invalid;
  4687. operand->expr = node;
  4688. return nullptr;
  4689. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4690. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4691. // It pretty much needs to be in this order and this way
  4692. // If you can clean this up, please do but be really careful
  4693. String import_name = op_name;
  4694. Scope *import_scope = e->ImportName.scope;
  4695. String entity_name = selector->Ident.token.string;
  4696. if (import_scope == nullptr) {
  4697. ERROR_BLOCK();
  4698. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4699. operand->mode = Addressing_Invalid;
  4700. operand->expr = node;
  4701. return nullptr;
  4702. }
  4703. check_op_expr = false;
  4704. entity = scope_lookup_current(import_scope, entity_name);
  4705. bool allow_builtin = false;
  4706. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4707. ERROR_BLOCK();
  4708. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4709. operand->mode = Addressing_Invalid;
  4710. operand->expr = node;
  4711. check_did_you_mean_scope(entity_name, import_scope);
  4712. return nullptr;
  4713. }
  4714. if (!is_entity_exported(entity, allow_builtin)) {
  4715. gbString sel_str = expr_to_string(selector);
  4716. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4717. gb_string_free(sel_str);
  4718. // NOTE(bill): make the state valid still, even if it's "invalid"
  4719. // operand->mode = Addressing_Invalid;
  4720. // operand->expr = node;
  4721. // return nullptr;
  4722. }
  4723. check_entity_decl(c, entity, nullptr, nullptr);
  4724. if (entity->kind == Entity_ProcGroup) {
  4725. operand->mode = Addressing_ProcGroup;
  4726. operand->proc_group = entity;
  4727. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4728. return entity;
  4729. }
  4730. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4731. }
  4732. }
  4733. if (check_op_expr) {
  4734. check_expr_base(c, operand, op_expr, nullptr);
  4735. if (operand->mode == Addressing_Invalid) {
  4736. operand->mode = Addressing_Invalid;
  4737. operand->expr = node;
  4738. return nullptr;
  4739. }
  4740. }
  4741. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4742. complete_soa_type(c->checker, type_deref(operand->type), false);
  4743. }
  4744. if (entity == nullptr && selector->kind == Ast_Ident) {
  4745. String field_name = selector->Ident.token.string;
  4746. Type *t = type_deref(operand->type);
  4747. if (t == nullptr) {
  4748. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4749. } else {
  4750. if (is_type_dynamic_array(t)) {
  4751. init_mem_allocator(c->checker);
  4752. }
  4753. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4754. entity = sel.entity;
  4755. // NOTE(bill): Add type info needed for fields like 'names'
  4756. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4757. add_type_info_type(c, operand->type);
  4758. }
  4759. if (is_type_enum(operand->type)) {
  4760. add_type_info_type(c, operand->type);
  4761. }
  4762. }
  4763. }
  4764. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4765. String field_name = selector->Ident.token.string;
  4766. if (field_name.len == 1) {
  4767. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4768. } else {
  4769. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4770. }
  4771. return nullptr;
  4772. }
  4773. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4774. (is_type_array(type_deref(operand->type)))) {
  4775. String field_name = selector->Ident.token.string;
  4776. if (1 < field_name.len && field_name.len <= 4) {
  4777. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4778. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4779. bool found_xyzw = false;
  4780. bool found_rgba = false;
  4781. for (isize i = 0; i < field_name.len; i++) {
  4782. bool valid = false;
  4783. for (isize j = 0; j < 4; j++) {
  4784. if (field_name.text[i] == swizzles_xyzw[j]) {
  4785. found_xyzw = true;
  4786. valid = true;
  4787. break;
  4788. }
  4789. if (field_name.text[i] == swizzles_rgba[j]) {
  4790. found_rgba = true;
  4791. valid = true;
  4792. break;
  4793. }
  4794. }
  4795. if (!valid) {
  4796. goto end_of_array_selector_swizzle;
  4797. }
  4798. }
  4799. u8 *swizzles = nullptr;
  4800. u8 index_count = cast(u8)field_name.len;
  4801. if (found_xyzw && found_rgba) {
  4802. gbString op_str = expr_to_string(op_expr);
  4803. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4804. gb_string_free(op_str);
  4805. operand->mode = Addressing_Invalid;
  4806. operand->expr = node;
  4807. return nullptr;
  4808. }
  4809. u8 indices = 0;
  4810. if (found_xyzw) {
  4811. swizzles = swizzles_xyzw;
  4812. } else if (found_rgba) {
  4813. swizzles = swizzles_rgba;
  4814. }
  4815. for (isize i = 0; i < field_name.len; i++) {
  4816. for (isize j = 0; j < 4; j++) {
  4817. if (field_name.text[i] == swizzles[j]) {
  4818. indices |= cast(u8)(j)<<(i*2);
  4819. break;
  4820. }
  4821. }
  4822. }
  4823. Type *original_type = operand->type;
  4824. Type *array_type = base_type(type_deref(original_type));
  4825. GB_ASSERT(array_type->kind == Type_Array);
  4826. i64 array_count = get_array_type_count(array_type);
  4827. for (u8 i = 0; i < index_count; i++) {
  4828. u8 idx = indices>>(i*2) & 3;
  4829. if (idx >= array_count) {
  4830. char c = 0;
  4831. if (found_xyzw) {
  4832. c = swizzles_xyzw[idx];
  4833. } else if (found_rgba) {
  4834. c = swizzles_rgba[idx];
  4835. } else {
  4836. GB_PANIC("unknown swizzle kind");
  4837. }
  4838. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4839. break;
  4840. }
  4841. }
  4842. se->swizzle_count = index_count;
  4843. se->swizzle_indices = indices;
  4844. AddressingMode prev_mode = operand->mode;
  4845. operand->mode = Addressing_SwizzleValue;
  4846. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4847. operand->expr = node;
  4848. switch (prev_mode) {
  4849. case Addressing_Variable:
  4850. case Addressing_SoaVariable:
  4851. case Addressing_SwizzleVariable:
  4852. operand->mode = Addressing_SwizzleVariable;
  4853. break;
  4854. case Addressing_Value:
  4855. if (is_type_pointer(original_type)) {
  4856. operand->mode = Addressing_SwizzleVariable;
  4857. }
  4858. break;
  4859. }
  4860. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4861. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4862. return swizzle_entity;
  4863. }
  4864. end_of_array_selector_swizzle:;
  4865. }
  4866. if (entity == nullptr) {
  4867. gbString op_str = expr_to_string(op_expr);
  4868. gbString type_str = type_to_string_shorthand(operand->type);
  4869. gbString sel_str = expr_to_string(selector);
  4870. if (operand->mode == Addressing_Type) {
  4871. if (is_type_polymorphic(operand->type, true)) {
  4872. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4873. } else {
  4874. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4875. }
  4876. } else {
  4877. ERROR_BLOCK();
  4878. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4879. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4880. String const &name = selector->Ident.token.string;
  4881. Type *bt = base_type(operand->type);
  4882. if (operand->type->kind == Type_Named &&
  4883. operand->type->Named.type_name &&
  4884. operand->type->Named.type_name->kind == Entity_TypeName &&
  4885. operand->type->Named.type_name->TypeName.objc_metadata) {
  4886. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4887. } else if (bt->kind == Type_Struct) {
  4888. check_did_you_mean_type(name, bt->Struct.fields);
  4889. } else if (bt->kind == Type_Enum) {
  4890. check_did_you_mean_type(name, bt->Enum.fields);
  4891. }
  4892. }
  4893. }
  4894. gb_string_free(sel_str);
  4895. gb_string_free(type_str);
  4896. gb_string_free(op_str);
  4897. operand->mode = Addressing_Invalid;
  4898. operand->expr = node;
  4899. return nullptr;
  4900. }
  4901. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4902. bool success = false;
  4903. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4904. if (success) {
  4905. operand->mode = Addressing_Constant;
  4906. operand->expr = node;
  4907. operand->value = field_value;
  4908. operand->type = entity->type;
  4909. add_entity_use(c, selector, entity);
  4910. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4911. return entity;
  4912. }
  4913. gbString op_str = expr_to_string(op_expr);
  4914. gbString type_str = type_to_string_shorthand(operand->type);
  4915. gbString sel_str = expr_to_string(selector);
  4916. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4917. gb_string_free(sel_str);
  4918. gb_string_free(type_str);
  4919. gb_string_free(op_str);
  4920. operand->mode = Addressing_Invalid;
  4921. operand->expr = node;
  4922. return nullptr;
  4923. }
  4924. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4925. bool success = false;
  4926. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4927. if (success) {
  4928. operand->mode = Addressing_Constant;
  4929. operand->expr = node;
  4930. operand->value = field_value;
  4931. operand->type = entity->type;
  4932. add_entity_use(c, selector, entity);
  4933. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4934. return entity;
  4935. }
  4936. gbString op_str = expr_to_string(op_expr);
  4937. gbString type_str = type_to_string_shorthand(operand->type);
  4938. gbString sel_str = expr_to_string(selector);
  4939. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4940. gb_string_free(sel_str);
  4941. gb_string_free(type_str);
  4942. gb_string_free(op_str);
  4943. operand->mode = Addressing_Invalid;
  4944. operand->expr = node;
  4945. return nullptr;
  4946. }
  4947. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4948. gbString op_str = expr_to_string(op_expr);
  4949. gbString type_str = type_to_string_shorthand(operand->type);
  4950. gbString sel_str = expr_to_string(selector);
  4951. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4952. gb_string_free(sel_str);
  4953. gb_string_free(type_str);
  4954. gb_string_free(op_str);
  4955. operand->mode = Addressing_Invalid;
  4956. operand->expr = node;
  4957. return nullptr;
  4958. }
  4959. add_entity_use(c, selector, entity);
  4960. operand->type = entity->type;
  4961. operand->expr = node;
  4962. if (entity->flags & EntityFlag_BitFieldField) {
  4963. add_package_dependency(c, "runtime", "__write_bits");
  4964. add_package_dependency(c, "runtime", "__read_bits");
  4965. }
  4966. switch (entity->kind) {
  4967. case Entity_Constant:
  4968. operand->value = entity->Constant.value;
  4969. operand->mode = Addressing_Constant;
  4970. if (operand->value.kind == ExactValue_Procedure) {
  4971. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4972. if (proc != nullptr) {
  4973. operand->mode = Addressing_Value;
  4974. operand->type = proc->type;
  4975. }
  4976. }
  4977. break;
  4978. case Entity_Variable:
  4979. if (sel.is_bit_field) {
  4980. se->is_bit_field = true;
  4981. }
  4982. if (sel.indirect) {
  4983. operand->mode = Addressing_Variable;
  4984. } else if (operand->mode == Addressing_Context) {
  4985. // Do nothing
  4986. } else if (operand->mode == Addressing_MapIndex) {
  4987. operand->mode = Addressing_Value;
  4988. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4989. operand->mode = Addressing_SoaVariable;
  4990. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4991. operand->mode = Addressing_Value;
  4992. } else if (operand->mode == Addressing_SoaVariable) {
  4993. operand->mode = Addressing_Variable;
  4994. } else if (operand->mode != Addressing_Value) {
  4995. operand->mode = Addressing_Variable;
  4996. } else {
  4997. operand->mode = Addressing_Value;
  4998. }
  4999. break;
  5000. case Entity_TypeName:
  5001. operand->mode = Addressing_Type;
  5002. break;
  5003. case Entity_Procedure:
  5004. operand->mode = Addressing_Value;
  5005. operand->value = exact_value_procedure(node);
  5006. break;
  5007. case Entity_Builtin:
  5008. operand->mode = Addressing_Builtin;
  5009. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5010. break;
  5011. case Entity_ProcGroup:
  5012. operand->mode = Addressing_ProcGroup;
  5013. operand->proc_group = entity;
  5014. break;
  5015. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5016. case Entity_Nil:
  5017. operand->mode = Addressing_Value;
  5018. break;
  5019. }
  5020. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5021. return entity;
  5022. }
  5023. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5024. ptr = base_type(ptr);
  5025. if (is_type_pointer(ptr)) {
  5026. if (is_type_rawptr(ptr)) {
  5027. return false;
  5028. }
  5029. if (elem) *elem = ptr->Pointer.elem;
  5030. return true;
  5031. }
  5032. return false;
  5033. }
  5034. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5035. elem = core_type(elem);
  5036. if (is_type_internally_pointer_like(elem)) {
  5037. return true;
  5038. }
  5039. if (elem->kind == Type_BitSet) {
  5040. elem = bit_set_to_int(elem);
  5041. }
  5042. if (elem->kind != Type_Basic) {
  5043. return false;
  5044. }
  5045. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5046. }
  5047. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5048. switch (node->kind) {
  5049. case_ast_node(i, Ident, node);
  5050. String name = i->token.string;
  5051. if (nested) {
  5052. Entity *e = scope_lookup_current(s, name);
  5053. if (e != nullptr) {
  5054. if (out_scope) *out_scope = e->scope;
  5055. return true;
  5056. }
  5057. } else {
  5058. Entity *e = scope_lookup(s, name);
  5059. if (e != nullptr) {
  5060. if (out_scope) *out_scope = e->scope;
  5061. return true;
  5062. }
  5063. }
  5064. case_end;
  5065. case_ast_node(se, SelectorExpr, node);
  5066. Ast *lhs = se->expr;
  5067. Ast *rhs = se->selector;
  5068. Scope *lhs_scope = nullptr;
  5069. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5070. return check_identifier_exists(lhs_scope, rhs, true);
  5071. }
  5072. case_end;
  5073. }
  5074. return false;
  5075. }
  5076. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5077. bool optional_ok = false;
  5078. isize tuple_index = 0;
  5079. for (Ast *rhs_expr : rhs) {
  5080. CheckerContext c_ = *ctx;
  5081. CheckerContext *c = &c_;
  5082. Operand o = {};
  5083. Type *type_hint = nullptr;
  5084. if (tuple_index < lhs.count) {
  5085. type_hint = lhs[tuple_index].type;
  5086. }
  5087. check_expr_base(c, &o, rhs_expr, type_hint);
  5088. if (o.mode == Addressing_NoValue) {
  5089. error_operand_no_value(&o);
  5090. o.mode = Addressing_Invalid;
  5091. }
  5092. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5093. if (lhs.count == 2 && rhs.count == 1 &&
  5094. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5095. Ast *expr = unparen_expr(o.expr);
  5096. Operand val0 = o;
  5097. Operand val1 = o;
  5098. val0.mode = Addressing_Value;
  5099. val1.mode = Addressing_Value;
  5100. val1.type = t_untyped_bool;
  5101. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5102. if (expr->kind == Ast_TypeAssertion &&
  5103. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5104. // NOTE(bill): Used only for optimizations in the backend
  5105. if (is_blank_ident(lhs[0].expr)) {
  5106. expr->TypeAssertion.ignores[0] = true;
  5107. }
  5108. if (is_blank_ident(lhs[1].expr)) {
  5109. expr->TypeAssertion.ignores[1] = true;
  5110. }
  5111. }
  5112. array_add(operands, val0);
  5113. array_add(operands, val1);
  5114. optional_ok = true;
  5115. tuple_index += 2;
  5116. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5117. Type *tuple = o.type;
  5118. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5119. Ast *expr = unparen_expr(o.expr);
  5120. if (expr->kind == Ast_CallExpr) {
  5121. expr->CallExpr.optional_ok_one = true;
  5122. }
  5123. Operand val = o;
  5124. val.type = tuple->Tuple.variables[0]->type;
  5125. val.mode = Addressing_Value;
  5126. array_add(operands, val);
  5127. tuple_index += tuple->Tuple.variables.count;
  5128. } else {
  5129. array_add(operands, o);
  5130. tuple_index += 1;
  5131. }
  5132. } else {
  5133. TypeTuple *tuple = &o.type->Tuple;
  5134. for (Entity *e : tuple->variables) {
  5135. o.type = e->type;
  5136. array_add(operands, o);
  5137. }
  5138. tuple_index += tuple->variables.count;
  5139. }
  5140. }
  5141. return optional_ok;
  5142. }
  5143. typedef u32 UnpackFlags;
  5144. enum UnpackFlag : u32 {
  5145. UnpackFlag_None = 0,
  5146. UnpackFlag_AllowOk = 1<<0,
  5147. UnpackFlag_AllowUndef = 1<<1,
  5148. };
  5149. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5150. isize variadic_index = -1) {
  5151. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5152. if (lhs == nullptr || c->decl == nullptr) {
  5153. return tuple_count;
  5154. }
  5155. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5156. Entity *e = lhs[tuple_index + j];
  5157. if (e == nullptr) {
  5158. continue;
  5159. }
  5160. DeclInfo *decl = decl_info_of_entity(e);
  5161. if (decl == nullptr) {
  5162. continue;
  5163. }
  5164. rw_mutex_shared_lock(&decl->deps_mutex);
  5165. rw_mutex_lock(&c->decl->deps_mutex);
  5166. for (Entity *dep : decl->deps) {
  5167. ptr_set_add(&c->decl->deps, dep);
  5168. }
  5169. rw_mutex_unlock(&c->decl->deps_mutex);
  5170. rw_mutex_shared_unlock(&decl->deps_mutex);
  5171. }
  5172. return tuple_count;
  5173. };
  5174. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5175. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5176. bool is_variadic = variadic_index > -1;
  5177. if (!is_variadic) {
  5178. variadic_index = lhs_count;
  5179. }
  5180. bool optional_ok = false;
  5181. isize tuple_index = 0;
  5182. for (Ast *rhs : rhs_arguments) {
  5183. if (rhs->kind == Ast_FieldValue) {
  5184. error(rhs, "Invalid use of 'field = value'");
  5185. rhs = rhs->FieldValue.value;
  5186. }
  5187. CheckerContext c_ = *ctx;
  5188. CheckerContext *c = &c_;
  5189. Operand o = {};
  5190. Type *type_hint = nullptr;
  5191. if (lhs != nullptr) {
  5192. if (tuple_index < variadic_index) {
  5193. // NOTE(bill): override DeclInfo for dependency
  5194. Entity *e = lhs[tuple_index];
  5195. if (e != nullptr) {
  5196. type_hint = e->type;
  5197. }
  5198. } else if (is_variadic) {
  5199. Entity *e = lhs[variadic_index];
  5200. if (e != nullptr) {
  5201. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5202. GB_ASSERT(is_type_slice(e->type));
  5203. type_hint = e->type->Slice.elem;
  5204. }
  5205. }
  5206. }
  5207. Ast *rhs_expr = unparen_expr(rhs);
  5208. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5209. // NOTE(bill): Just handle this very specific logic here
  5210. o.type = t_untyped_uninit;
  5211. o.mode = Addressing_Value;
  5212. o.expr = rhs;
  5213. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5214. } else {
  5215. check_expr_base(c, &o, rhs, type_hint);
  5216. }
  5217. if (o.mode == Addressing_NoValue) {
  5218. error_operand_no_value(&o);
  5219. o.mode = Addressing_Invalid;
  5220. }
  5221. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5222. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5223. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5224. Ast *expr = unparen_expr(o.expr);
  5225. Operand val0 = o;
  5226. Operand val1 = o;
  5227. val0.mode = Addressing_Value;
  5228. val1.mode = Addressing_Value;
  5229. val1.type = t_untyped_bool;
  5230. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5231. if (expr->kind == Ast_TypeAssertion &&
  5232. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5233. // NOTE(bill): Used only for optimizations in the backend
  5234. if (is_blank_ident(lhs[0]->token)) {
  5235. expr->TypeAssertion.ignores[0] = true;
  5236. }
  5237. if (is_blank_ident(lhs[1]->token)) {
  5238. expr->TypeAssertion.ignores[1] = true;
  5239. }
  5240. }
  5241. array_add(operands, val0);
  5242. array_add(operands, val1);
  5243. optional_ok = true;
  5244. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5245. } else {
  5246. array_add(operands, o);
  5247. tuple_index += 1;
  5248. }
  5249. } else {
  5250. TypeTuple *tuple = &o.type->Tuple;
  5251. for (Entity *e : tuple->variables) {
  5252. o.type = e->type;
  5253. array_add(operands, o);
  5254. }
  5255. isize count = tuple->variables.count;
  5256. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5257. }
  5258. }
  5259. return optional_ok;
  5260. }
  5261. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5262. GB_ASSERT(pt != nullptr);
  5263. GB_ASSERT(pt->kind == Type_Proc);
  5264. isize param_count = 0;
  5265. isize param_count_excluding_defaults = 0;
  5266. bool variadic = pt->Proc.variadic;
  5267. TypeTuple *param_tuple = nullptr;
  5268. if (pt->Proc.params != nullptr) {
  5269. param_tuple = &pt->Proc.params->Tuple;
  5270. param_count = param_tuple->variables.count;
  5271. if (variadic) {
  5272. for (isize i = param_count-1; i >= 0; i--) {
  5273. Entity *e = param_tuple->variables[i];
  5274. if (e->kind == Entity_TypeName) {
  5275. break;
  5276. }
  5277. if (e->kind == Entity_Variable) {
  5278. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5279. param_count--;
  5280. continue;
  5281. }
  5282. }
  5283. break;
  5284. }
  5285. param_count--;
  5286. }
  5287. }
  5288. param_count_excluding_defaults = param_count;
  5289. if (param_tuple != nullptr) {
  5290. for (isize i = param_count-1; i >= 0; i--) {
  5291. Entity *e = param_tuple->variables[i];
  5292. if (e->kind == Entity_TypeName) {
  5293. break;
  5294. }
  5295. if (e->kind == Entity_Variable) {
  5296. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5297. param_count_excluding_defaults--;
  5298. continue;
  5299. }
  5300. }
  5301. break;
  5302. }
  5303. }
  5304. if (param_count_) *param_count_ = param_count;
  5305. return param_count_excluding_defaults;
  5306. }
  5307. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5308. isize param_count = pt->param_count;
  5309. for (isize i = 0; i < param_count; i++) {
  5310. Entity *e = pt->params->Tuple.variables[i];
  5311. String name = e->token.string;
  5312. if (is_blank_ident(name)) {
  5313. continue;
  5314. }
  5315. if (name == parameter_name) {
  5316. return i;
  5317. }
  5318. }
  5319. return -1;
  5320. }
  5321. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5322. type = base_type(type);
  5323. GB_ASSERT(type->kind == Type_Proc);
  5324. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5325. }
  5326. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5327. Entity *entity, Type *proc_type,
  5328. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5329. CallArgumentErrorMode show_error_mode,
  5330. CallArgumentData *data) {
  5331. TEMPORARY_ALLOCATOR_GUARD();
  5332. CallArgumentError err = CallArgumentError_None;
  5333. ast_node(ce, CallExpr, call);
  5334. GB_ASSERT(is_type_proc(proc_type));
  5335. proc_type = base_type(proc_type);
  5336. TypeProc *pt = &proc_type->Proc;
  5337. isize param_count = 0;
  5338. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5339. bool variadic = pt->variadic;
  5340. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5341. i64 score = 0;
  5342. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5343. Type *final_proc_type = proc_type;
  5344. Entity *gen_entity = nullptr;
  5345. if (vari_expand && !variadic) {
  5346. if (show_error) {
  5347. error(ce->ellipsis,
  5348. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5349. LIT(ce->proc->Ident.token.string));
  5350. }
  5351. err = CallArgumentError_NonVariadicExpand;
  5352. } else if (vari_expand && pt->c_vararg) {
  5353. if (show_error) {
  5354. error(ce->ellipsis,
  5355. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5356. LIT(ce->proc->Ident.token.string));
  5357. }
  5358. err = CallArgumentError_NonVariadicExpand;
  5359. }
  5360. GB_ASSERT(ce->split_args);
  5361. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5362. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5363. defer ({
  5364. for (Operand const &o : ordered_operands) {
  5365. if (o.expr != nullptr) {
  5366. call->viral_state_flags |= o.expr->viral_state_flags;
  5367. }
  5368. }
  5369. });
  5370. isize positional_operand_count = positional_operands.count;
  5371. if (variadic) {
  5372. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5373. } else if (positional_operand_count > pt->param_count) {
  5374. err = CallArgumentError_TooManyArguments;
  5375. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5376. if (show_error) {
  5377. gbString proc_str = expr_to_string(ce->proc);
  5378. defer (gb_string_free(proc_str));
  5379. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5380. }
  5381. return err;
  5382. }
  5383. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5384. for (isize i = 0; i < positional_operand_count; i++) {
  5385. ordered_operands[i] = positional_operands[i];
  5386. visited[i] = true;
  5387. }
  5388. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5389. bool named_variadic_param = false;
  5390. if (named_operands.count != 0) {
  5391. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5392. for_array(i, ce->split_args->named) {
  5393. Ast *arg = ce->split_args->named[i];
  5394. Operand operand = named_operands[i];
  5395. ast_node(fv, FieldValue, arg);
  5396. if (fv->field->kind != Ast_Ident) {
  5397. if (show_error) {
  5398. gbString expr_str = expr_to_string(fv->field);
  5399. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5400. gb_string_free(expr_str);
  5401. }
  5402. err = CallArgumentError_InvalidFieldValue;
  5403. continue;
  5404. }
  5405. String name = fv->field->Ident.token.string;
  5406. isize param_index = lookup_procedure_parameter(pt, name);
  5407. if (param_index < 0) {
  5408. if (show_error) {
  5409. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5410. }
  5411. err = CallArgumentError_ParameterNotFound;
  5412. continue;
  5413. }
  5414. if (pt->variadic && param_index == pt->variadic_index) {
  5415. named_variadic_param = true;
  5416. }
  5417. if (visited[param_index]) {
  5418. if (show_error) {
  5419. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5420. }
  5421. err = CallArgumentError_DuplicateParameter;
  5422. continue;
  5423. }
  5424. visited[param_index] = true;
  5425. ordered_operands[param_index] = operand;
  5426. }
  5427. }
  5428. isize dummy_argument_count = 0;
  5429. bool actually_variadic = false;
  5430. if (variadic) {
  5431. if (visited[pt->variadic_index] &&
  5432. positional_operand_count < positional_operands.count) {
  5433. if (show_error) {
  5434. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5435. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5436. }
  5437. err = CallArgumentError_DuplicateParameter;
  5438. } else if (!visited[pt->variadic_index]) {
  5439. visited[pt->variadic_index] = true;
  5440. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5441. if (vari_expand) {
  5442. if (variadic_operands.count == 0) {
  5443. error(call, "'..' in the wrong position");
  5444. } else {
  5445. GB_ASSERT(variadic_operands.count != 0);
  5446. *variadic_operand = variadic_operands[0];
  5447. variadic_operand->type = default_type(variadic_operand->type);
  5448. actually_variadic = true;
  5449. }
  5450. } else {
  5451. AstFile *f = call->file();
  5452. // HACK(bill): this is an awful hack
  5453. Operand o = {};
  5454. o.mode = Addressing_Value;
  5455. o.expr = ast_ident(f, make_token_ident("nil"));
  5456. o.expr->Ident.token.pos = ast_token(call).pos;
  5457. if (variadic_operands.count != 0) {
  5458. actually_variadic = true;
  5459. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5460. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5461. o.type = vt->type;
  5462. } else {
  5463. dummy_argument_count += 1;
  5464. o.type = t_untyped_nil;
  5465. }
  5466. *variadic_operand = o;
  5467. }
  5468. }
  5469. }
  5470. for (isize i = 0; i < pt->param_count; i++) {
  5471. if (!visited[i]) {
  5472. Entity *e = pt->params->Tuple.variables[i];
  5473. bool context_allocator_error = false;
  5474. if (e->kind == Entity_Variable) {
  5475. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5476. if (ast_file_vet_explicit_allocators(c->file)) {
  5477. // NOTE(lucas): check if we are trying to default to context.allocator or context.temp_allocator
  5478. if (e->Variable.param_value.original_ast_expr->kind == Ast_SelectorExpr) {
  5479. auto& expr = e->Variable.param_value.original_ast_expr->SelectorExpr.expr;
  5480. auto& selector = e->Variable.param_value.original_ast_expr->SelectorExpr.selector;
  5481. if (expr->kind == Ast_Implicit &&
  5482. expr->Implicit.string == STR_LIT("context") &&
  5483. selector->kind == Ast_Ident &&
  5484. (selector->Ident.token.string == STR_LIT("allocator") ||
  5485. selector->Ident.token.string == STR_LIT("temp_allocator"))) {
  5486. context_allocator_error = true;
  5487. }
  5488. }
  5489. }
  5490. if (!context_allocator_error) {
  5491. ordered_operands[i].mode = Addressing_Value;
  5492. ordered_operands[i].type = e->type;
  5493. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5494. dummy_argument_count += 1;
  5495. score += assign_score_function(1);
  5496. continue;
  5497. }
  5498. }
  5499. }
  5500. if (show_error) {
  5501. if (context_allocator_error) {
  5502. gbString str = type_to_string(e->type);
  5503. error(call, "Parameter '%.*s' of type '%s' must be explicitly provided in procedure call",
  5504. LIT(e->token.string), str);
  5505. gb_string_free(str);
  5506. } else if (e->kind == Entity_TypeName) {
  5507. error(call, "Type parameter '%.*s' is missing in procedure call",
  5508. LIT(e->token.string));
  5509. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5510. // Ignore
  5511. } else {
  5512. gbString str = type_to_string(e->type);
  5513. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5514. LIT(e->token.string), str);
  5515. gb_string_free(str);
  5516. }
  5517. }
  5518. err = CallArgumentError_ParameterMissing;
  5519. }
  5520. }
  5521. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5522. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5523. i64 s = 0;
  5524. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5525. bool ok = false;
  5526. if (e && (e->flags & EntityFlag_AnyInt)) {
  5527. if (is_type_integer(param_type)) {
  5528. ok = check_is_castable_to(c, o, param_type);
  5529. }
  5530. }
  5531. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5532. if (show_error) {
  5533. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5534. }
  5535. }
  5536. if (ok) {
  5537. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5538. } else {
  5539. if (show_error) {
  5540. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5541. }
  5542. err = CallArgumentError_WrongTypes;
  5543. }
  5544. } else if (show_error) {
  5545. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5546. }
  5547. if (e && e->flags & EntityFlag_ConstInput) {
  5548. if (o->mode != Addressing_Constant) {
  5549. if (show_error) {
  5550. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5551. }
  5552. err = CallArgumentError_NoneConstantParameter;
  5553. }
  5554. }
  5555. if (!err && is_type_any(param_type)) {
  5556. add_type_info_type(c, o->type);
  5557. }
  5558. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5559. add_type_info_type(c, o->type);
  5560. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5561. } else if (show_error && is_type_untyped(o->type)) {
  5562. update_untyped_expr_type(c, o->expr, param_type, true);
  5563. }
  5564. return s;
  5565. };
  5566. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5567. err = CallArgumentError_None;
  5568. if (variadic) {
  5569. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5570. Type *t = pt->params->Tuple.variables[0]->type;
  5571. if (is_type_polymorphic(t)) {
  5572. if (show_error) {
  5573. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5574. }
  5575. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5576. }
  5577. }
  5578. } else {
  5579. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5580. PolyProcData poly_proc_data = {};
  5581. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5582. gen_entity = poly_proc_data.gen_entity;
  5583. Type *gept = base_type(gen_entity->type);
  5584. GB_ASSERT(is_type_proc(gept));
  5585. final_proc_type = gen_entity->type;
  5586. pt = &gept->Proc;
  5587. } else {
  5588. err = CallArgumentError_WrongTypes;
  5589. }
  5590. }
  5591. for (isize i = 0; i < pt->param_count; i++) {
  5592. Operand *o = &ordered_operands[i];
  5593. if (o->mode == Addressing_Invalid) {
  5594. continue;
  5595. }
  5596. Entity *e = pt->params->Tuple.variables[i];
  5597. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5598. if (e->kind == Entity_TypeName) {
  5599. GB_ASSERT(pt->is_polymorphic);
  5600. if (o->mode != Addressing_Type) {
  5601. if (show_error) {
  5602. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5603. }
  5604. err = CallArgumentError_WrongTypes;
  5605. }
  5606. if (are_types_identical(e->type, o->type)) {
  5607. score += assign_score_function(1);
  5608. } else {
  5609. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5610. }
  5611. continue;
  5612. }
  5613. if (param_is_variadic) {
  5614. if (!named_variadic_param) {
  5615. continue;
  5616. }
  5617. }
  5618. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5619. }
  5620. }
  5621. if (variadic) {
  5622. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5623. Type *slice = var_entity->type;
  5624. GB_ASSERT(is_type_slice(slice));
  5625. Type *elem = base_type(slice)->Slice.elem;
  5626. Type *t = elem;
  5627. if (is_type_polymorphic(t)) {
  5628. if (show_error) {
  5629. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5630. }
  5631. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5632. }
  5633. for_array(operand_index, variadic_operands) {
  5634. Operand *o = &variadic_operands[operand_index];
  5635. if (vari_expand) {
  5636. t = slice;
  5637. if (operand_index > 0) {
  5638. if (show_error) {
  5639. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5640. }
  5641. if (data) {
  5642. data->score = score;
  5643. data->result_type = final_proc_type->Proc.results;
  5644. data->gen_entity = gen_entity;
  5645. }
  5646. return CallArgumentError_MultipleVariadicExpand;
  5647. }
  5648. }
  5649. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5650. }
  5651. if (!vari_expand && variadic_operands.count != 0) {
  5652. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5653. if (c->decl) {
  5654. bool found = false;
  5655. for (auto &vr : c->decl->variadic_reuses) {
  5656. if (are_types_identical(slice, vr.slice_type)) {
  5657. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5658. found = true;
  5659. break;
  5660. }
  5661. }
  5662. if (!found) {
  5663. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5664. }
  5665. }
  5666. }
  5667. }
  5668. if (data) {
  5669. data->score = score;
  5670. data->result_type = final_proc_type->Proc.results;
  5671. data->gen_entity = gen_entity;
  5672. Ast *proc_lit = nullptr;
  5673. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5674. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5675. if (vp && vp->kind == Ast_ProcLit) {
  5676. proc_lit = vp;
  5677. }
  5678. }
  5679. if (proc_lit == nullptr) {
  5680. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5681. }
  5682. }
  5683. return err;
  5684. }
  5685. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5686. GB_ASSERT(ce != nullptr);
  5687. if (ce->args.count == 0) {
  5688. return false;
  5689. }
  5690. return ce->args[0]->kind == Ast_FieldValue;
  5691. }
  5692. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5693. Entity **lhs = nullptr;
  5694. isize lhs_count = -1;
  5695. if (proc_type == nullptr || proc_type == t_invalid) {
  5696. return nullptr;
  5697. }
  5698. GB_ASSERT(is_type_proc(proc_type));
  5699. TypeProc *pt = &base_type(proc_type)->Proc;
  5700. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5701. if (pt->params != nullptr) {
  5702. lhs = pt->params->Tuple.variables.data;
  5703. lhs_count = pt->params->Tuple.variables.count;
  5704. }
  5705. } else {
  5706. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5707. if (pt->params == nullptr) {
  5708. lhs_count = 0;
  5709. } else {
  5710. lhs_count = pt->params->Tuple.variables.count;
  5711. }
  5712. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5713. for (isize i = 0; i < lhs_count; i++) {
  5714. Entity *e = pt->params->Tuple.variables[i];
  5715. if (!is_type_polymorphic(e->type)) {
  5716. lhs[i] = e;
  5717. }
  5718. }
  5719. }
  5720. if (lhs_count_) *lhs_count_ = lhs_count;
  5721. return lhs;
  5722. }
  5723. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5724. if (clauses != nullptr) {
  5725. for (Ast *clause : *clauses) {
  5726. Operand o = {};
  5727. check_expr(ctx, &o, clause);
  5728. if (o.mode != Addressing_Constant) {
  5729. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5730. if (print_err && call_expr) error(call_expr, "at caller location");
  5731. return false;
  5732. } else if (o.value.kind != ExactValue_Bool) {
  5733. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5734. if (print_err && call_expr) error(call_expr, "at caller location");
  5735. return false;
  5736. } else if (!o.value.value_bool) {
  5737. if (print_err) {
  5738. ERROR_BLOCK();
  5739. gbString str = expr_to_string(clause);
  5740. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5741. gb_string_free(str);
  5742. if (scope != nullptr) {
  5743. isize print_count = 0;
  5744. for (auto const &entry : scope->elements) {
  5745. Entity *e = entry.value;
  5746. switch (e->kind) {
  5747. case Entity_TypeName: {
  5748. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5749. gbString str = type_to_string(e->type);
  5750. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5751. gb_string_free(str);
  5752. print_count += 1;
  5753. break;
  5754. }
  5755. case Entity_Constant: {
  5756. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5757. gbString str = exact_value_to_string(e->Constant.value);
  5758. if (is_type_untyped(e->type)) {
  5759. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5760. } else {
  5761. gbString t = type_to_string(e->type);
  5762. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5763. gb_string_free(t);
  5764. }
  5765. gb_string_free(str);
  5766. print_count += 1;
  5767. break;
  5768. }
  5769. }
  5770. }
  5771. }
  5772. if (call_expr) {
  5773. TokenPos pos = ast_token(call_expr).pos;
  5774. error_line("%s at caller location\n", token_pos_to_string(pos));
  5775. }
  5776. }
  5777. return false;
  5778. }
  5779. if (ast_file_vet_style(ctx->file)) {
  5780. Ast *c = unparen_expr(clause);
  5781. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5782. ERROR_BLOCK();
  5783. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5784. gbString x = expr_to_string(c->BinaryExpr.left);
  5785. gbString y = expr_to_string(c->BinaryExpr.right);
  5786. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5787. gb_string_free(y);
  5788. gb_string_free(x);
  5789. }
  5790. }
  5791. }
  5792. }
  5793. return true;
  5794. }
  5795. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5796. bool success = true;
  5797. type = base_type(type);
  5798. if (named_args.count > 0) {
  5799. TypeProc *pt = nullptr;
  5800. if (is_type_proc(type)) {
  5801. pt = &type->Proc;
  5802. }
  5803. for_array(i, named_args) {
  5804. Ast *arg = named_args[i];
  5805. if (arg->kind != Ast_FieldValue) {
  5806. if (show_error) {
  5807. error(arg, "Expected a 'field = value'");
  5808. }
  5809. return false;
  5810. }
  5811. ast_node(fv, FieldValue, arg);
  5812. if (fv->field->kind != Ast_Ident) {
  5813. if (show_error) {
  5814. gbString expr_str = expr_to_string(fv->field);
  5815. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5816. gb_string_free(expr_str);
  5817. }
  5818. success = false;
  5819. continue;
  5820. }
  5821. String key = fv->field->Ident.token.string;
  5822. Ast *value = fv->value;
  5823. Type *type_hint = nullptr;
  5824. if (pt) {
  5825. isize param_index = lookup_procedure_parameter(pt, key);
  5826. if (param_index < 0) {
  5827. if (show_error) {
  5828. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5829. }
  5830. success = false;
  5831. continue;
  5832. }
  5833. Entity *e = pt->params->Tuple.variables[param_index];
  5834. if (!is_type_polymorphic(e->type)) {
  5835. type_hint = e->type;
  5836. }
  5837. }
  5838. Operand o = {};
  5839. check_expr_with_type_hint(c, &o, value, type_hint);
  5840. if (o.mode == Addressing_Invalid) {
  5841. success = false;
  5842. }
  5843. array_add(named_operands, o);
  5844. }
  5845. }
  5846. return success;
  5847. }
  5848. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5849. Entity *e, Type *proc_type,
  5850. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5851. CallArgumentErrorMode show_error_mode,
  5852. CallArgumentData *data) {
  5853. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5854. Ast *ident = operand->expr;
  5855. while (ident->kind == Ast_SelectorExpr) {
  5856. Ast *s = ident->SelectorExpr.selector;
  5857. ident = s;
  5858. }
  5859. if (e == nullptr) {
  5860. e = entity_of_node(ident);
  5861. if (e != nullptr) {
  5862. proc_type = e->type;
  5863. }
  5864. }
  5865. GB_ASSERT(proc_type != nullptr);
  5866. proc_type = base_type(proc_type);
  5867. if (proc_type == t_invalid) {
  5868. return false;
  5869. }
  5870. GB_ASSERT(proc_type->kind == Type_Proc);
  5871. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5872. if (return_on_failure && err != CallArgumentError_None) {
  5873. return false;
  5874. }
  5875. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5876. if (!return_on_failure && entity_to_use != nullptr) {
  5877. add_entity_use(c, ident, entity_to_use);
  5878. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5879. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5880. }
  5881. if (data->gen_entity != nullptr) {
  5882. Entity *e = data->gen_entity;
  5883. DeclInfo *decl = data->gen_entity->decl_info;
  5884. CheckerContext ctx = *c;
  5885. ctx.scope = decl->scope;
  5886. ctx.decl = decl;
  5887. ctx.proc_name = e->token.string;
  5888. ctx.curr_proc_decl = decl;
  5889. ctx.curr_proc_sig = e->type;
  5890. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5891. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5892. if (return_on_failure) {
  5893. if (!ok) {
  5894. return false;
  5895. }
  5896. } else {
  5897. decl->where_clauses_evaluated = true;
  5898. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5899. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5900. }
  5901. if (is_type_proc(data->gen_entity->type)) {
  5902. Type *t = base_type(entity_to_use->type);
  5903. data->result_type = t->Proc.results;
  5904. }
  5905. }
  5906. }
  5907. return true;
  5908. }
  5909. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5910. ast_node(ce, CallExpr, call);
  5911. GB_ASSERT(ce->split_args != nullptr);
  5912. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5913. Slice<Ast *> const &named_args = ce->split_args->named;
  5914. CallArgumentData data = {};
  5915. data.result_type = t_invalid;
  5916. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5917. auto procs = proc_group_entities_cloned(c, *operand);
  5918. if (procs.count > 1) {
  5919. isize max_arg_count = positional_args.count + named_args.count;
  5920. for (Ast *arg : positional_args) {
  5921. // NOTE(bill): The only thing that may have multiple values
  5922. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5923. arg = strip_or_return_expr(arg);
  5924. if (arg && arg->kind == Ast_CallExpr) {
  5925. max_arg_count = ISIZE_MAX;
  5926. break;
  5927. }
  5928. }
  5929. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5930. // NOTE(bill): The only thing that may have multiple values
  5931. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5932. if (arg->kind == Ast_FieldValue) {
  5933. arg = strip_or_return_expr(arg->FieldValue.value);
  5934. if (arg && arg->kind == Ast_CallExpr) {
  5935. max_arg_count = ISIZE_MAX;
  5936. break;
  5937. }
  5938. }
  5939. }
  5940. // ignore named arguments first
  5941. for (Ast *arg : named_args) {
  5942. if (arg->kind != Ast_FieldValue) {
  5943. continue;
  5944. }
  5945. ast_node(fv, FieldValue, arg);
  5946. if (fv->field->kind != Ast_Ident) {
  5947. continue;
  5948. }
  5949. String key = fv->field->Ident.token.string;
  5950. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5951. Type *t = procs[proc_index]->type;
  5952. if (is_type_proc(t)) {
  5953. isize param_index = lookup_procedure_parameter(t, key);
  5954. if (param_index < 0) {
  5955. array_unordered_remove(&procs, proc_index);
  5956. }
  5957. }
  5958. }
  5959. }
  5960. if (procs.count == 0) {
  5961. // if any of the named arguments are wrong, the `procs` will be empty
  5962. // just start from scratch
  5963. array_free(&procs);
  5964. procs = proc_group_entities_cloned(c, *operand);
  5965. }
  5966. // filter by positional argument length
  5967. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5968. Entity *proc = procs[proc_index];
  5969. Type *pt = base_type(proc->type);
  5970. if (!(pt != nullptr && is_type_proc(pt))) {
  5971. proc_index++;
  5972. continue;
  5973. }
  5974. isize param_count = 0;
  5975. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5976. if (param_count_excluding_defaults > max_arg_count) {
  5977. array_unordered_remove(&procs, proc_index);
  5978. continue;
  5979. }
  5980. proc_index++;
  5981. }
  5982. }
  5983. Entity **lhs = nullptr;
  5984. isize lhs_count = -1;
  5985. i32 variadic_index = -1;
  5986. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5987. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5988. defer (array_free(&positional_operands));
  5989. defer (array_free(&named_operands));
  5990. if (procs.count == 1) {
  5991. Entity *e = procs[0];
  5992. Type *pt = base_type(e->type);
  5993. if (pt != nullptr && is_type_proc(pt)) {
  5994. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  5995. if (pt->Proc.variadic) {
  5996. variadic_index = pt->Proc.variadic_index;
  5997. }
  5998. }
  5999. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6000. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  6001. check_call_arguments_single(c, call, operand,
  6002. e, e->type,
  6003. positional_operands, named_operands,
  6004. CallArgumentErrorMode::ShowErrors,
  6005. &data);
  6006. }
  6007. return data;
  6008. }
  6009. {
  6010. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6011. // where the same positional parameter has the same type value (and ellipsis)
  6012. isize proc_arg_count = -1;
  6013. for (Entity *p : procs) {
  6014. Type *pt = base_type(p->type);
  6015. if (pt != nullptr && is_type_proc(pt)) {
  6016. if (proc_arg_count < 0) {
  6017. proc_arg_count = pt->Proc.param_count;
  6018. } else {
  6019. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6020. }
  6021. }
  6022. }
  6023. if (proc_arg_count >= 0) {
  6024. lhs_count = proc_arg_count;
  6025. if (lhs_count > 0) {
  6026. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6027. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6028. Entity *e = nullptr;
  6029. for (Entity *p : procs) {
  6030. Type *pt = base_type(p->type);
  6031. if (!(pt != nullptr && is_type_proc(pt))) {
  6032. continue;
  6033. }
  6034. if (e == nullptr) {
  6035. e = pt->Proc.params->Tuple.variables[param_index];
  6036. } else {
  6037. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6038. if (e == f) {
  6039. continue;
  6040. }
  6041. if (are_types_identical(e->type, f->type)) {
  6042. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6043. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6044. if (ee == fe) {
  6045. continue;
  6046. }
  6047. }
  6048. // NOTE(bill): Entities are not close enough to be used
  6049. e = nullptr;
  6050. break;
  6051. }
  6052. }
  6053. lhs[param_index] = e;
  6054. }
  6055. for (Entity *p : procs) {
  6056. Type *pt = base_type(p->type);
  6057. if (!(pt != nullptr && is_type_proc(pt))) {
  6058. continue;
  6059. }
  6060. if (pt->Proc.is_polymorphic) {
  6061. if (variadic_index == -1) {
  6062. variadic_index = pt->Proc.variadic_index;
  6063. } else if (variadic_index != pt->Proc.variadic_index) {
  6064. variadic_index = -1;
  6065. break;
  6066. }
  6067. } else {
  6068. variadic_index = -1;
  6069. break;
  6070. }
  6071. }
  6072. }
  6073. }
  6074. }
  6075. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6076. for_array(i, named_args) {
  6077. Ast *arg = named_args[i];
  6078. if (arg->kind != Ast_FieldValue) {
  6079. error(arg, "Expected a 'field = value'");
  6080. return data;
  6081. }
  6082. ast_node(fv, FieldValue, arg);
  6083. if (fv->field->kind != Ast_Ident) {
  6084. gbString expr_str = expr_to_string(fv->field);
  6085. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6086. gb_string_free(expr_str);
  6087. return data;
  6088. }
  6089. String key = fv->field->Ident.token.string;
  6090. Ast *value = fv->value;
  6091. Type *type_hint = nullptr;
  6092. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6093. Entity *e = lhs[lhs_idx];
  6094. if (e != nullptr && e->token.string == key &&
  6095. !is_type_polymorphic(e->type)) {
  6096. type_hint = e->type;
  6097. break;
  6098. }
  6099. }
  6100. Operand o = {};
  6101. check_expr_with_type_hint(c, &o, value, type_hint);
  6102. array_add(&named_operands, o);
  6103. }
  6104. gb_free(heap_allocator(), lhs);
  6105. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6106. defer (array_free(&valids));
  6107. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6108. defer (array_free(&proc_entities));
  6109. for (Entity *proc : procs) {
  6110. array_add(&proc_entities, proc);
  6111. }
  6112. int max_matched_features = 0;
  6113. gbString expr_name = expr_to_string(operand->expr);
  6114. defer (gb_string_free(expr_name));
  6115. for_array(i, procs) {
  6116. Entity *p = procs[i];
  6117. if (p->flags & EntityFlag_Disabled) {
  6118. continue;
  6119. }
  6120. Type *pt = base_type(p->type);
  6121. if (pt != nullptr && is_type_proc(pt)) {
  6122. CallArgumentData data = {};
  6123. CheckerContext ctx = *c;
  6124. ctx.no_polymorphic_errors = true;
  6125. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6126. ctx.hide_polymorphic_errors = true;
  6127. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6128. p, pt,
  6129. positional_operands, named_operands,
  6130. CallArgumentErrorMode::NoErrors,
  6131. &data);
  6132. if (!is_a_candidate) {
  6133. continue;
  6134. }
  6135. isize index = i;
  6136. ValidIndexAndScore item = {};
  6137. item.score = data.score;
  6138. if (data.gen_entity != nullptr) {
  6139. array_add(&proc_entities, data.gen_entity);
  6140. index = proc_entities.count-1;
  6141. // prefer non-polymorphic procedures over polymorphic
  6142. item.score += assign_score_function(1);
  6143. }
  6144. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6145. item.index = index;
  6146. array_add(&valids, item);
  6147. }
  6148. }
  6149. if (max_matched_features > 0) {
  6150. for_array(i, valids) {
  6151. Entity *p = procs[valids[i].index];
  6152. Type *t = base_type(p->type);
  6153. GB_ASSERT(t->kind == Type_Proc);
  6154. int matched = matched_target_features(&t->Proc);
  6155. valids[i].score += assign_score_function(max_matched_features-matched);
  6156. }
  6157. }
  6158. if (valids.count > 1) {
  6159. array_sort(valids, valid_index_and_score_cmp);
  6160. i64 best_score = valids[0].score;
  6161. Entity *best_entity = proc_entities[valids[0].index];
  6162. GB_ASSERT(best_entity != nullptr);
  6163. for (isize i = 1; i < valids.count; i++) {
  6164. if (best_score > valids[i].score) {
  6165. valids.count = i;
  6166. break;
  6167. }
  6168. if (best_entity == proc_entities[valids[i].index]) {
  6169. valids.count = i;
  6170. break;
  6171. }
  6172. }
  6173. }
  6174. auto print_argument_types = [&]() {
  6175. error_line("\tGiven argument types: (");
  6176. isize i = 0;
  6177. for (Operand const &o : positional_operands) {
  6178. if (i++ > 0) error_line(", ");
  6179. gbString type = type_to_string(o.type);
  6180. defer (gb_string_free(type));
  6181. error_line("%s", type);
  6182. }
  6183. for (Operand const &o : named_operands) {
  6184. if (i++ > 0) error_line(", ");
  6185. gbString type = type_to_string(o.type);
  6186. defer (gb_string_free(type));
  6187. if (i < ce->split_args->named.count) {
  6188. Ast *named_field = ce->split_args->named[i];
  6189. ast_node(fv, FieldValue, named_field);
  6190. gbString field = expr_to_string(fv->field);
  6191. defer (gb_string_free(field));
  6192. error_line("%s = %s", field, type);
  6193. } else {
  6194. error_line("%s", type);
  6195. }
  6196. }
  6197. error_line(")\n");
  6198. };
  6199. if (valids.count == 0) {
  6200. ERROR_BLOCK();
  6201. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6202. if (positional_operands.count == 0 && named_operands.count == 0) {
  6203. error_line("\tNo given arguments\n");
  6204. } else {
  6205. print_argument_types();
  6206. }
  6207. if (procs.count == 0) {
  6208. procs = proc_group_entities_cloned(c, *operand);
  6209. }
  6210. if (procs.count > 0) {
  6211. error_line("Did you mean to use one of the following:\n");
  6212. }
  6213. // Try to reduce the list further for `$T: typeid` like parameters
  6214. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6215. isize possibly_ignore_set = 0;
  6216. if (true) {
  6217. // NOTE(bill): This currently only checks for #soa types
  6218. for_array(i, procs) {
  6219. Entity *proc = procs[i];
  6220. Type *t = base_type(proc->type);
  6221. if (t == nullptr || t->kind != Type_Proc) {
  6222. continue;
  6223. }
  6224. TypeProc *pt = &t->Proc;
  6225. if (pt->param_count == 0) {
  6226. continue;
  6227. }
  6228. for_array(j, pt->params->Tuple.variables) {
  6229. Entity *v = pt->params->Tuple.variables[j];
  6230. if (v->kind != Entity_TypeName) {
  6231. continue;
  6232. }
  6233. Type *dst_t = base_type(v->type);
  6234. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6235. dst_t = dst_t->Generic.specialized;
  6236. }
  6237. if (j >= positional_operands.count) {
  6238. continue;
  6239. }
  6240. Operand const &o = positional_operands[j];
  6241. if (o.mode != Addressing_Type) {
  6242. continue;
  6243. }
  6244. Type *t = base_type(o.type);
  6245. if (t->kind == dst_t->kind) {
  6246. continue;
  6247. }
  6248. Type *st = base_type(type_deref(o.type));
  6249. Type *dt = base_type(type_deref(dst_t));
  6250. if (st->kind == dt->kind) {
  6251. continue;
  6252. }
  6253. if (is_type_soa_struct(st)) {
  6254. possibly_ignore[i] = true;
  6255. possibly_ignore_set += 1;
  6256. continue;
  6257. }
  6258. }
  6259. }
  6260. }
  6261. if (possibly_ignore_set == procs.count) {
  6262. possibly_ignore_set = 0;
  6263. }
  6264. isize max_name_length = 0;
  6265. isize max_type_length = 0;
  6266. for_array(i, procs) {
  6267. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6268. continue;
  6269. }
  6270. Entity *proc = procs[i];
  6271. Type *t = base_type(proc->type);
  6272. if (t == t_invalid) continue;
  6273. String prefix = {};
  6274. String prefix_sep = {};
  6275. if (proc->pkg) {
  6276. prefix = proc->pkg->name;
  6277. prefix_sep = str_lit(".");
  6278. }
  6279. String name = proc->token.string;
  6280. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6281. gbString pt;
  6282. if (t->Proc.node != nullptr) {
  6283. pt = expr_to_string(t->Proc.node);
  6284. } else {
  6285. pt = type_to_string(t);
  6286. }
  6287. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6288. gb_string_free(pt);
  6289. }
  6290. isize max_spaces = gb_max(max_name_length, max_type_length);
  6291. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6292. for (isize i = 0; i < max_spaces; i++) {
  6293. spaces[i] = ' ';
  6294. }
  6295. spaces[max_spaces] = 0;
  6296. for_array(i, procs) {
  6297. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6298. continue;
  6299. }
  6300. Entity *proc = procs[i];
  6301. TokenPos pos = proc->token.pos;
  6302. Type *t = base_type(proc->type);
  6303. if (t == t_invalid) continue;
  6304. GB_ASSERT(t->kind == Type_Proc);
  6305. gbString pt;
  6306. defer (gb_string_free(pt));
  6307. if (t->Proc.node != nullptr) {
  6308. pt = expr_to_string(t->Proc.node);
  6309. } else {
  6310. pt = type_to_string(t);
  6311. }
  6312. String prefix = {};
  6313. String prefix_sep = {};
  6314. if (proc->pkg) {
  6315. prefix = proc->pkg->name;
  6316. prefix_sep = str_lit(".");
  6317. }
  6318. String name = proc->token.string;
  6319. isize len = prefix.len + prefix_sep.len + name.len;
  6320. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6321. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6322. char const *sep = "::";
  6323. if (proc->kind == Entity_Variable) {
  6324. sep = ":=";
  6325. }
  6326. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6327. LIT(prefix), LIT(prefix_sep), LIT(name),
  6328. name_padding, spaces,
  6329. sep,
  6330. pt,
  6331. type_padding, spaces,
  6332. token_pos_to_string(pos)
  6333. );
  6334. }
  6335. if (procs.count > 0) {
  6336. error_line("\n");
  6337. }
  6338. data.result_type = t_invalid;
  6339. } else if (valids.count > 1) {
  6340. ERROR_BLOCK();
  6341. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6342. if (positional_operands.count == 0 && named_operands.count == 0) {
  6343. error_line("\tNo given arguments\n");
  6344. } else {
  6345. print_argument_types();
  6346. }
  6347. for (auto const &valid : valids) {
  6348. Entity *proc = proc_entities[valid.index];
  6349. GB_ASSERT(proc != nullptr);
  6350. TokenPos pos = proc->token.pos;
  6351. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6352. gbString pt = nullptr;
  6353. defer (gb_string_free(pt));
  6354. if (t->Proc.node != nullptr) {
  6355. pt = expr_to_string(t->Proc.node);
  6356. } else {
  6357. pt = type_to_string(t);
  6358. }
  6359. String name = proc->token.string;
  6360. char const *sep = "::";
  6361. if (proc->kind == Entity_Variable) {
  6362. sep = ":=";
  6363. }
  6364. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6365. if (proc->decl_info->proc_lit != nullptr) {
  6366. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6367. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6368. if (pl->where_token.kind != Token_Invalid) {
  6369. error_line("\n\t\twhere ");
  6370. for_array(j, pl->where_clauses) {
  6371. Ast *clause = pl->where_clauses[j];
  6372. if (j != 0) {
  6373. error_line("\t\t ");
  6374. }
  6375. gbString str = expr_to_string(clause);
  6376. error_line("%s", str);
  6377. gb_string_free(str);
  6378. if (j != pl->where_clauses.count-1) {
  6379. error_line(",");
  6380. }
  6381. }
  6382. error_line("\n\t");
  6383. }
  6384. }
  6385. error_line("at %s\n", token_pos_to_string(pos));
  6386. }
  6387. data.result_type = t_invalid;
  6388. } else {
  6389. GB_ASSERT(valids.count == 1);
  6390. Ast *ident = operand->expr;
  6391. while (ident->kind == Ast_SelectorExpr) {
  6392. Ast *s = ident->SelectorExpr.selector;
  6393. ident = s;
  6394. }
  6395. Entity *e = proc_entities[valids[0].index];
  6396. GB_ASSERT(e != nullptr);
  6397. Array<Operand> named_operands = {};
  6398. check_call_arguments_single(c, call, operand,
  6399. e, e->type,
  6400. positional_operands, named_operands,
  6401. CallArgumentErrorMode::ShowErrors,
  6402. &data);
  6403. return data;
  6404. }
  6405. return data;
  6406. }
  6407. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6408. Type *proc_type = nullptr;
  6409. CallArgumentData data = {};
  6410. data.result_type = t_invalid;
  6411. proc_type = base_type(operand->type);
  6412. TypeProc *pt = nullptr;
  6413. if (proc_type) {
  6414. pt = &proc_type->Proc;
  6415. }
  6416. TEMPORARY_ALLOCATOR_GUARD();
  6417. ast_node(ce, CallExpr, call);
  6418. bool any_failure = false;
  6419. // Split positional and named args into separate arrays/slices
  6420. Slice<Ast *> positional_args = {};
  6421. Slice<Ast *> named_args = {};
  6422. if (ce->split_args == nullptr) {
  6423. positional_args = ce->args;
  6424. for (isize i = 0; i < ce->args.count; i++) {
  6425. Ast *arg = ce->args.data[i];
  6426. if (arg->kind == Ast_FieldValue) {
  6427. positional_args.count = i;
  6428. break;
  6429. }
  6430. }
  6431. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6432. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6433. split_args->positional = positional_args;
  6434. split_args->named = named_args;
  6435. ce->split_args = split_args;
  6436. } else {
  6437. positional_args = ce->split_args->positional;
  6438. named_args = ce->split_args->named;
  6439. }
  6440. if (operand->mode == Addressing_ProcGroup) {
  6441. return check_call_arguments_proc_group(c, operand, call);
  6442. }
  6443. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6444. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6445. defer (array_free(&positional_operands));
  6446. defer (array_free(&named_operands));
  6447. if (positional_args.count > 0) {
  6448. Entity **lhs = nullptr;
  6449. isize lhs_count = -1;
  6450. i32 variadic_index = -1;
  6451. if (pt != nullptr) {
  6452. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6453. if (pt->variadic) {
  6454. variadic_index = pt->variadic_index;
  6455. }
  6456. }
  6457. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6458. }
  6459. if (named_args.count > 0) {
  6460. for_array(i, named_args) {
  6461. Ast *arg = named_args[i];
  6462. if (arg->kind != Ast_FieldValue) {
  6463. error(arg, "Expected a 'field = value'");
  6464. return data;
  6465. }
  6466. ast_node(fv, FieldValue, arg);
  6467. if (fv->field->kind != Ast_Ident) {
  6468. gbString expr_str = expr_to_string(fv->field);
  6469. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6470. any_failure = true;
  6471. gb_string_free(expr_str);
  6472. continue;
  6473. }
  6474. String key = fv->field->Ident.token.string;
  6475. Ast *value = fv->value;
  6476. isize param_index = lookup_procedure_parameter(pt, key);
  6477. Type *type_hint = nullptr;
  6478. if (param_index >= 0) {
  6479. Entity *e = pt->params->Tuple.variables[param_index];
  6480. type_hint = e->type;
  6481. }
  6482. Operand o = {};
  6483. check_expr_with_type_hint(c, &o, value, type_hint);
  6484. if (o.mode == Addressing_Invalid) {
  6485. any_failure = true;
  6486. }
  6487. array_add(&named_operands, o);
  6488. }
  6489. }
  6490. if (!any_failure) {
  6491. check_call_arguments_single(c, call, operand,
  6492. nullptr, proc_type,
  6493. positional_operands, named_operands,
  6494. CallArgumentErrorMode::ShowErrors,
  6495. &data);
  6496. } else if (pt) {
  6497. data.result_type = pt->results;
  6498. }
  6499. return data;
  6500. }
  6501. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6502. if (!is_type_polymorphic_record(t)) {
  6503. return -1;
  6504. }
  6505. TypeTuple *params = get_record_polymorphic_params(t);
  6506. if (params == nullptr) {
  6507. return -1;
  6508. }
  6509. for_array(i, params->variables) {
  6510. Entity *e = params->variables[i];
  6511. String name = e->token.string;
  6512. if (is_blank_ident(name)) {
  6513. continue;
  6514. }
  6515. if (name == parameter_name) {
  6516. return i;
  6517. }
  6518. }
  6519. return -1;
  6520. }
  6521. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6522. ast_node(ce, CallExpr, call);
  6523. Type *original_type = operand->type;
  6524. GB_ASSERT(is_type_polymorphic_record(original_type));
  6525. bool show_error = true;
  6526. Array<Operand> operands = {};
  6527. defer (array_free(&operands));
  6528. CallArgumentError err = CallArgumentError_None;
  6529. bool named_fields = false;
  6530. {
  6531. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6532. auto prev_type_path = c->type_path;
  6533. c->type_path = new_checker_type_path();
  6534. defer ({
  6535. destroy_checker_type_path(c->type_path);
  6536. c->type_path = prev_type_path;
  6537. });
  6538. if (is_call_expr_field_value(ce)) {
  6539. named_fields = true;
  6540. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6541. for_array(i, ce->args) {
  6542. Ast *arg = ce->args[i];
  6543. ast_node(fv, FieldValue, arg);
  6544. if (fv->value == nullptr) {
  6545. error(fv->eq, "Expected a value");
  6546. err = CallArgumentError_InvalidFieldValue;
  6547. continue;
  6548. }
  6549. if (fv->field->kind == Ast_Ident) {
  6550. String name = fv->field->Ident.token.string;
  6551. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6552. if (index >= 0) {
  6553. TypeTuple *params = get_record_polymorphic_params(original_type);
  6554. Entity *e = params->variables[index];
  6555. if (e->kind == Entity_Constant) {
  6556. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6557. continue;
  6558. }
  6559. }
  6560. }
  6561. check_expr_or_type(c, &operands[i], fv->value);
  6562. }
  6563. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6564. if (vari_expand) {
  6565. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6566. }
  6567. } else {
  6568. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6569. Entity **lhs = nullptr;
  6570. isize lhs_count = -1;
  6571. TypeTuple *params = get_record_polymorphic_params(original_type);
  6572. if (params != nullptr) {
  6573. lhs = params->variables.data;
  6574. lhs_count = params->variables.count;
  6575. }
  6576. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6577. }
  6578. }
  6579. if (err != 0) {
  6580. operand->mode = Addressing_Invalid;
  6581. return err;
  6582. }
  6583. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6584. isize param_count = tuple->variables.count;
  6585. isize minimum_param_count = param_count;
  6586. for (; minimum_param_count > 0; minimum_param_count--) {
  6587. Entity *e = tuple->variables[minimum_param_count-1];
  6588. if (e->kind != Entity_Constant) {
  6589. break;
  6590. }
  6591. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6592. break;
  6593. }
  6594. }
  6595. Array<Operand> ordered_operands = operands;
  6596. if (!named_fields) {
  6597. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6598. array_copy(&ordered_operands, operands, 0);
  6599. } else {
  6600. TEMPORARY_ALLOCATOR_GUARD();
  6601. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6602. // LEAK(bill)
  6603. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6604. for_array(i, ce->args) {
  6605. Ast *arg = ce->args[i];
  6606. ast_node(fv, FieldValue, arg);
  6607. if (fv->field->kind != Ast_Ident) {
  6608. if (show_error) {
  6609. gbString expr_str = expr_to_string(fv->field);
  6610. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6611. gb_string_free(expr_str);
  6612. }
  6613. err = CallArgumentError_InvalidFieldValue;
  6614. continue;
  6615. }
  6616. String name = fv->field->Ident.token.string;
  6617. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6618. if (index < 0) {
  6619. if (show_error) {
  6620. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6621. }
  6622. err = CallArgumentError_ParameterNotFound;
  6623. continue;
  6624. }
  6625. if (visited[index]) {
  6626. if (show_error) {
  6627. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6628. }
  6629. err = CallArgumentError_DuplicateParameter;
  6630. continue;
  6631. }
  6632. visited[index] = true;
  6633. ordered_operands[index] = operands[i];
  6634. }
  6635. for (isize i = 0; i < param_count; i++) {
  6636. if (!visited[i]) {
  6637. Entity *e = tuple->variables[i];
  6638. if (is_blank_ident(e->token)) {
  6639. continue;
  6640. }
  6641. if (show_error) {
  6642. if (e->kind == Entity_TypeName) {
  6643. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6644. LIT(e->token.string));
  6645. } else {
  6646. gbString str = type_to_string(e->type);
  6647. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6648. LIT(e->token.string), str);
  6649. gb_string_free(str);
  6650. }
  6651. }
  6652. err = CallArgumentError_ParameterMissing;
  6653. }
  6654. }
  6655. }
  6656. if (err != 0) {
  6657. operand->mode = Addressing_Invalid;
  6658. return err;
  6659. }
  6660. while (ordered_operands.count > 0) {
  6661. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6662. break;
  6663. }
  6664. array_pop(&ordered_operands);
  6665. }
  6666. if (minimum_param_count != param_count) {
  6667. if (param_count < ordered_operands.count) {
  6668. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6669. err = CallArgumentError_TooManyArguments;
  6670. } else if (minimum_param_count > ordered_operands.count) {
  6671. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6672. err = CallArgumentError_TooFewArguments;
  6673. }
  6674. } else {
  6675. if (param_count < ordered_operands.count) {
  6676. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6677. err = CallArgumentError_TooManyArguments;
  6678. } else if (param_count > ordered_operands.count) {
  6679. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6680. err = CallArgumentError_TooFewArguments;
  6681. }
  6682. }
  6683. if (err != 0) {
  6684. return err;
  6685. }
  6686. if (minimum_param_count != param_count) {
  6687. array_resize(&ordered_operands, param_count);
  6688. isize missing_count = 0;
  6689. // NOTE(bill): Replace missing operands with the default values (if possible)
  6690. for_array(i, ordered_operands) {
  6691. Operand *o = &ordered_operands[i];
  6692. if (o->expr == nullptr) {
  6693. Entity *e = tuple->variables[i];
  6694. if (e->kind == Entity_Constant) {
  6695. missing_count += 1;
  6696. o->mode = Addressing_Constant;
  6697. o->type = default_type(e->type);
  6698. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6699. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6700. o->value = e->Constant.param_value.value;
  6701. }
  6702. } else if (e->kind == Entity_TypeName) {
  6703. missing_count += 1;
  6704. o->mode = Addressing_Type;
  6705. o->type = e->type;
  6706. o->expr = e->identifier;
  6707. }
  6708. }
  6709. }
  6710. }
  6711. isize oo_count = gb_min(param_count, ordered_operands.count);
  6712. i64 score = 0;
  6713. for (isize i = 0; i < oo_count; i++) {
  6714. Entity *e = tuple->variables[i];
  6715. Operand *o = &ordered_operands[i];
  6716. if (o->mode == Addressing_Invalid) {
  6717. continue;
  6718. }
  6719. if (e->kind == Entity_TypeName) {
  6720. if (o->mode != Addressing_Type) {
  6721. if (show_error) {
  6722. gbString expr = expr_to_string(o->expr);
  6723. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6724. gb_string_free(expr);
  6725. }
  6726. err = CallArgumentError_WrongTypes;
  6727. }
  6728. if (are_types_identical(e->type, o->type)) {
  6729. score += assign_score_function(1);
  6730. } else {
  6731. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6732. }
  6733. } else {
  6734. i64 s = 0;
  6735. if (o->type->kind == Type_Generic) {
  6736. // Polymorphic name!
  6737. score += assign_score_function(1);
  6738. continue;
  6739. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6740. if (show_error) {
  6741. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6742. }
  6743. err = CallArgumentError_WrongTypes;
  6744. }
  6745. o->type = e->type;
  6746. if (o->mode != Addressing_Constant) {
  6747. bool valid = false;
  6748. if (is_type_proc(o->type)) {
  6749. Entity *proc_entity = entity_from_expr(o->expr);
  6750. valid = proc_entity != nullptr;
  6751. }
  6752. if (!valid) {
  6753. if (show_error) {
  6754. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6755. }
  6756. err = CallArgumentError_NoneConstantParameter;
  6757. }
  6758. }
  6759. score += s;
  6760. }
  6761. // NOTE(bill): Add type info the parameters
  6762. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6763. // add_type_info_type(c, o->type);
  6764. }
  6765. if (show_error && err) {
  6766. return err;
  6767. }
  6768. {
  6769. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6770. mutex_lock(&found_gen_types->mutex);
  6771. defer (mutex_unlock(&found_gen_types->mutex));
  6772. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6773. if (found_entity) {
  6774. operand->mode = Addressing_Type;
  6775. operand->type = found_entity->type;
  6776. return err;
  6777. }
  6778. CheckerContext ctx = *c;
  6779. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6780. ctx.scope = polymorphic_record_parent_scope(original_type);
  6781. GB_ASSERT(ctx.scope != nullptr);
  6782. Type *bt = base_type(original_type);
  6783. String generated_name = make_string_c(expr_to_string(call));
  6784. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6785. if (bt->kind == Type_Struct) {
  6786. Ast *node = clone_ast(bt->Struct.node);
  6787. Type *struct_type = alloc_type_struct();
  6788. struct_type->Struct.node = node;
  6789. struct_type->Struct.polymorphic_parent = original_type;
  6790. set_base_type(named_type, struct_type);
  6791. check_open_scope(&ctx, node);
  6792. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6793. check_close_scope(&ctx);
  6794. } else if (bt->kind == Type_Union) {
  6795. Ast *node = clone_ast(bt->Union.node);
  6796. Type *union_type = alloc_type_union();
  6797. union_type->Union.node = node;
  6798. union_type->Union.polymorphic_parent = original_type;
  6799. set_base_type(named_type, union_type);
  6800. check_open_scope(&ctx, node);
  6801. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6802. check_close_scope(&ctx);
  6803. } else {
  6804. GB_PANIC("Unsupported parametric polymorphic record type");
  6805. }
  6806. bt = base_type(named_type);
  6807. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6808. GB_ASSERT(original_type->kind == Type_Named);
  6809. Entity *e = original_type->Named.type_name;
  6810. GB_ASSERT(e->kind == Entity_TypeName);
  6811. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6812. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6813. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6814. if (tuple != nullptr) for_array(i, tuple->variables) {
  6815. Entity *v = tuple->variables[i];
  6816. String name = v->token.string;
  6817. if (i > 0) {
  6818. s = gb_string_append_fmt(s, ", ");
  6819. }
  6820. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6821. if (v->kind == Entity_TypeName) {
  6822. if (v->type->kind != Type_Generic) {
  6823. s = gb_string_append_fmt(s, "=");
  6824. s = write_type_to_string(s, v->type, false);
  6825. }
  6826. } else if (v->kind == Entity_Constant) {
  6827. if (v->Constant.value.kind != ExactValue_Invalid) {
  6828. s = gb_string_append_fmt(s, "=");
  6829. s = write_exact_value_to_string(s, v->Constant.value);
  6830. }
  6831. }
  6832. }
  6833. s = gb_string_append_fmt(s, ")");
  6834. String new_name = make_string_c(s);
  6835. named_type->Named.name = new_name;
  6836. if (named_type->Named.type_name) {
  6837. named_type->Named.type_name->token.string = new_name;
  6838. }
  6839. }
  6840. operand->mode = Addressing_Type;
  6841. operand->type = named_type;
  6842. }
  6843. return err;
  6844. }
  6845. // returns true on success
  6846. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6847. bool success = true;
  6848. if (args.count > 0) {
  6849. if (allow_mixed) {
  6850. bool was_named = false;
  6851. for (Ast *arg : args) {
  6852. if (was_named && arg->kind != Ast_FieldValue) {
  6853. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6854. success = false;
  6855. break;
  6856. }
  6857. was_named = was_named || arg->kind == Ast_FieldValue;
  6858. }
  6859. } else {
  6860. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6861. for (Ast *arg : args) {
  6862. bool mix = false;
  6863. if (first_is_field_value) {
  6864. mix = arg->kind != Ast_FieldValue;
  6865. } else {
  6866. mix = arg->kind == Ast_FieldValue;
  6867. }
  6868. if (mix) {
  6869. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6870. success = false;
  6871. }
  6872. }
  6873. }
  6874. }
  6875. return success;
  6876. }
  6877. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6878. operand->mode = Addressing_Invalid; \
  6879. operand->expr = call; \
  6880. return Expr_Stmt; \
  6881. }
  6882. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6883. if (proc != nullptr &&
  6884. proc->kind == Ast_BasicDirective) {
  6885. ast_node(bd, BasicDirective, proc);
  6886. String name = bd->name.string;
  6887. if (
  6888. name == "location" ||
  6889. name == "exists" ||
  6890. name == "assert" ||
  6891. name == "panic" ||
  6892. name == "defined" ||
  6893. name == "config" ||
  6894. name == "load" ||
  6895. name == "load_directory" ||
  6896. name == "load_hash" ||
  6897. name == "hash" ||
  6898. name == "caller_expression"
  6899. ) {
  6900. operand->mode = Addressing_Builtin;
  6901. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6902. operand->expr = proc;
  6903. operand->type = t_invalid;
  6904. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6905. } else {
  6906. error(proc, "Unknown directive: #%.*s", LIT(name));
  6907. operand->expr = proc;
  6908. operand->type = t_invalid;
  6909. operand->mode = Addressing_Invalid;
  6910. return Expr_Expr;
  6911. }
  6912. if (inlining != ProcInlining_none) {
  6913. error(call, "Inlining operators are not allowed on built-in procedures");
  6914. }
  6915. } else {
  6916. if (proc != nullptr) {
  6917. check_expr_or_type(c, operand, proc);
  6918. } else {
  6919. GB_ASSERT(operand->expr != nullptr);
  6920. }
  6921. }
  6922. if (operand->mode == Addressing_Invalid) {
  6923. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6924. for (Ast *arg : args) {
  6925. if (arg->kind == Ast_FieldValue) {
  6926. arg = arg->FieldValue.value;
  6927. }
  6928. check_expr_base(c, operand, arg, nullptr);
  6929. }
  6930. operand->mode = Addressing_Invalid;
  6931. operand->expr = call;
  6932. return Expr_Stmt;
  6933. }
  6934. if (operand->mode == Addressing_Type) {
  6935. Type *t = operand->type;
  6936. if (is_type_polymorphic_record(t)) {
  6937. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6938. if (!is_type_named(t)) {
  6939. gbString s = expr_to_string(operand->expr);
  6940. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6941. gb_string_free(s);
  6942. operand->mode = Addressing_Invalid;
  6943. operand->type = t_invalid;;
  6944. return Expr_Expr;
  6945. }
  6946. auto err = check_polymorphic_record_type(c, operand, call);
  6947. if (err == 0) {
  6948. Ast *ident = operand->expr;
  6949. while (ident->kind == Ast_SelectorExpr) {
  6950. Ast *s = ident->SelectorExpr.selector;
  6951. ident = s;
  6952. }
  6953. Type *ot = operand->type;
  6954. GB_ASSERT(ot->kind == Type_Named);
  6955. Entity *e = ot->Named.type_name;
  6956. add_entity_use(c, ident, e);
  6957. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6958. } else {
  6959. operand->mode = Addressing_Invalid;
  6960. operand->type = t_invalid;
  6961. }
  6962. } else {
  6963. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6964. operand->mode = Addressing_Invalid;
  6965. isize arg_count = args.count;
  6966. switch (arg_count) {
  6967. case 0:
  6968. {
  6969. gbString str = type_to_string(t);
  6970. error(call, "Missing argument in conversion to '%s'", str);
  6971. gb_string_free(str);
  6972. } break;
  6973. default:
  6974. {
  6975. gbString str = type_to_string(t);
  6976. if (t->kind == Type_Basic) {
  6977. ERROR_BLOCK();
  6978. switch (t->Basic.kind) {
  6979. case Basic_complex32:
  6980. case Basic_complex64:
  6981. case Basic_complex128:
  6982. error(call, "Too many arguments in conversion to '%s'", str);
  6983. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  6984. break;
  6985. case Basic_quaternion64:
  6986. case Basic_quaternion128:
  6987. case Basic_quaternion256:
  6988. error(call, "Too many arguments in conversion to '%s'", str);
  6989. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  6990. break;
  6991. default:
  6992. error(call, "Too many arguments in conversion to '%s'", str);
  6993. }
  6994. } else {
  6995. error(call, "Too many arguments in conversion to '%s'", str);
  6996. }
  6997. gb_string_free(str);
  6998. } break;
  6999. case 1: {
  7000. Ast *arg = args[0];
  7001. if (arg->kind == Ast_FieldValue) {
  7002. error(call, "'field = value' cannot be used in a type conversion");
  7003. arg = arg->FieldValue.value;
  7004. // NOTE(bill): Carry on the cast regardless
  7005. }
  7006. check_expr_with_type_hint(c, operand, arg, t);
  7007. if (operand->mode != Addressing_Invalid) {
  7008. if (is_type_polymorphic(t)) {
  7009. error(call, "A polymorphic type cannot be used in a type conversion");
  7010. } else {
  7011. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7012. // as it assumes it is determining the type
  7013. check_cast(c, operand, t);
  7014. }
  7015. }
  7016. operand->type = t;
  7017. operand->expr = call;
  7018. if (operand->mode != Addressing_Invalid) {
  7019. update_untyped_expr_type(c, arg, t, false);
  7020. }
  7021. break;
  7022. }
  7023. }
  7024. }
  7025. return Expr_Expr;
  7026. }
  7027. if (operand->mode == Addressing_Builtin) {
  7028. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7029. i32 id = operand->builtin_id;
  7030. Entity *e = entity_of_node(operand->expr);
  7031. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7032. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7033. }
  7034. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7035. operand->mode = Addressing_Invalid;
  7036. operand->type = t_invalid;
  7037. }
  7038. operand->expr = call;
  7039. return builtin_procs[id].kind;
  7040. }
  7041. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7042. Entity *initial_entity = entity_of_node(operand->expr);
  7043. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7044. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7045. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7046. if (c->decl) {
  7047. c->decl->defer_used += 1;
  7048. }
  7049. }
  7050. add_entity_use(c, operand->expr, initial_entity);
  7051. if (initial_entity->Procedure.entry_point_only) {
  7052. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7053. // Okay
  7054. } else {
  7055. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7056. }
  7057. }
  7058. }
  7059. if (operand->mode != Addressing_ProcGroup) {
  7060. Type *proc_type = base_type(operand->type);
  7061. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7062. bool valid_mode = is_operand_value(*operand);
  7063. if (!valid_type || !valid_mode) {
  7064. Ast *e = operand->expr;
  7065. gbString str = expr_to_string(e);
  7066. gbString type_str = type_to_string(operand->type);
  7067. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7068. gb_string_free(type_str);
  7069. gb_string_free(str);
  7070. operand->mode = Addressing_Invalid;
  7071. operand->expr = call;
  7072. return Expr_Stmt;
  7073. }
  7074. }
  7075. CallArgumentData data = check_call_arguments(c, operand, call);
  7076. Type *result_type = data.result_type;
  7077. gb_zero_item(operand);
  7078. operand->expr = call;
  7079. if (result_type == t_invalid) {
  7080. operand->mode = Addressing_Invalid;
  7081. operand->type = t_invalid;
  7082. return Expr_Stmt;
  7083. }
  7084. Type *pt = base_type(operand->type);
  7085. if (pt == nullptr) {
  7086. pt = t_invalid;
  7087. }
  7088. if (pt == t_invalid) {
  7089. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7090. pt = type_of_expr(operand->expr->CallExpr.proc);
  7091. }
  7092. if (pt == t_invalid && data.gen_entity) {
  7093. pt = data.gen_entity->type;
  7094. }
  7095. }
  7096. pt = base_type(pt);
  7097. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7098. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7099. ERROR_BLOCK();
  7100. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7101. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7102. }
  7103. }
  7104. if (result_type == nullptr) {
  7105. operand->mode = Addressing_NoValue;
  7106. } else {
  7107. GB_ASSERT(is_type_tuple(result_type));
  7108. isize count = result_type->Tuple.variables.count;
  7109. switch (count) {
  7110. case 0:
  7111. operand->mode = Addressing_NoValue;
  7112. break;
  7113. case 1:
  7114. operand->mode = Addressing_Value;
  7115. operand->type = result_type->Tuple.variables[0]->type;
  7116. break;
  7117. default:
  7118. operand->mode = Addressing_Value;
  7119. operand->type = result_type;
  7120. break;
  7121. }
  7122. }
  7123. bool is_call_inlined = false;
  7124. switch (inlining) {
  7125. case ProcInlining_inline:
  7126. is_call_inlined = true;
  7127. if (proc != nullptr) {
  7128. Entity *e = entity_from_expr(proc);
  7129. if (e != nullptr && e->kind == Entity_Procedure) {
  7130. DeclInfo *decl = e->decl_info;
  7131. if (decl->proc_lit) {
  7132. ast_node(pl, ProcLit, decl->proc_lit);
  7133. if (pl->inlining == ProcInlining_no_inline) {
  7134. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7135. }
  7136. }
  7137. }
  7138. }
  7139. break;
  7140. case ProcInlining_no_inline:
  7141. break;
  7142. case ProcInlining_none:
  7143. if (proc != nullptr) {
  7144. Entity *e = entity_from_expr(proc);
  7145. if (e != nullptr && e->kind == Entity_Procedure) {
  7146. DeclInfo *decl = e->decl_info;
  7147. if (decl->proc_lit) {
  7148. ast_node(pl, ProcLit, decl->proc_lit);
  7149. if (pl->inlining == ProcInlining_inline) {
  7150. is_call_inlined = true;
  7151. }
  7152. }
  7153. }
  7154. }
  7155. }
  7156. {
  7157. String invalid;
  7158. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7159. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7160. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7161. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7162. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7163. }
  7164. }
  7165. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7166. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7167. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7168. }
  7169. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7170. if (is_call_inlined) {
  7171. if (c->curr_proc_decl == nullptr) {
  7172. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7173. } else {
  7174. GB_ASSERT(c->curr_proc_decl->entity);
  7175. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7176. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7177. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7178. ERROR_BLOCK();
  7179. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7180. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7181. }
  7182. }
  7183. }
  7184. }
  7185. }
  7186. operand->expr = call;
  7187. {
  7188. Type *type = nullptr;
  7189. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7190. type = type_of_expr(operand->expr->CallExpr.proc);
  7191. }
  7192. if (type == nullptr) {
  7193. type = pt;
  7194. }
  7195. type = base_type(type);
  7196. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7197. operand->mode = Addressing_OptionalOk;
  7198. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7199. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7200. operand->expr->CallExpr.optional_ok_one = true;
  7201. }
  7202. }
  7203. }
  7204. return Expr_Expr;
  7205. }
  7206. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7207. check_expr_base(c, o, e, t);
  7208. check_not_tuple(c, o);
  7209. char const *err_str = nullptr;
  7210. switch (o->mode) {
  7211. case Addressing_NoValue:
  7212. err_str = "used as a value";
  7213. break;
  7214. case Addressing_Type:
  7215. if (t == nullptr || !is_type_typeid(t)) {
  7216. err_str = "is not an expression but a type, in this context it is ambiguous";
  7217. }
  7218. break;
  7219. case Addressing_Builtin:
  7220. err_str = "must be called";
  7221. break;
  7222. }
  7223. if (err_str != nullptr) {
  7224. gbString str = expr_to_string(e);
  7225. error(e, "'%s' %s", str, err_str);
  7226. gb_string_free(str);
  7227. o->mode = Addressing_Invalid;
  7228. }
  7229. }
  7230. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7231. switch (t->kind) {
  7232. case Type_Basic:
  7233. if (t->Basic.kind == Basic_string) {
  7234. if (o->mode == Addressing_Constant) {
  7235. *max_count = o->value.value_string.len;
  7236. }
  7237. if (o->mode != Addressing_Constant) {
  7238. o->mode = Addressing_Value;
  7239. }
  7240. o->type = t_u8;
  7241. return true;
  7242. } else if (t->Basic.kind == Basic_UntypedString) {
  7243. if (o->mode == Addressing_Constant) {
  7244. *max_count = o->value.value_string.len;
  7245. o->type = t_u8;
  7246. return true;
  7247. }
  7248. return false;
  7249. }
  7250. break;
  7251. case Type_MultiPointer:
  7252. o->type = t->MultiPointer.elem;
  7253. if (o->mode != Addressing_Constant) {
  7254. o->mode = Addressing_Variable;
  7255. }
  7256. return true;
  7257. case Type_Array:
  7258. *max_count = t->Array.count;
  7259. if (indirection) {
  7260. o->mode = Addressing_Variable;
  7261. } else if (o->mode != Addressing_Variable &&
  7262. o->mode != Addressing_Constant) {
  7263. o->mode = Addressing_Value;
  7264. }
  7265. o->type = t->Array.elem;
  7266. return true;
  7267. case Type_EnumeratedArray:
  7268. *max_count = t->EnumeratedArray.count;
  7269. if (indirection) {
  7270. o->mode = Addressing_Variable;
  7271. } else if (o->mode != Addressing_Variable &&
  7272. o->mode != Addressing_Constant) {
  7273. o->mode = Addressing_Value;
  7274. }
  7275. o->type = t->EnumeratedArray.elem;
  7276. return true;
  7277. case Type_Matrix:
  7278. if (indirection) {
  7279. o->mode = Addressing_Variable;
  7280. } else if (o->mode != Addressing_Variable) {
  7281. o->mode = Addressing_Value;
  7282. }
  7283. if (t->Matrix.is_row_major) {
  7284. *max_count = t->Matrix.row_count;
  7285. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7286. } else {
  7287. *max_count = t->Matrix.column_count;
  7288. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7289. }
  7290. return true;
  7291. case Type_Slice:
  7292. o->type = t->Slice.elem;
  7293. if (o->mode != Addressing_Constant) {
  7294. o->mode = Addressing_Variable;
  7295. }
  7296. return true;
  7297. case Type_DynamicArray:
  7298. o->type = t->DynamicArray.elem;
  7299. if (o->mode != Addressing_Constant) {
  7300. o->mode = Addressing_Variable;
  7301. }
  7302. return true;
  7303. case Type_Struct:
  7304. if (t->Struct.soa_kind != StructSoa_None) {
  7305. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7306. *max_count = t->Struct.soa_count;
  7307. }
  7308. o->type = t->Struct.soa_elem;
  7309. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7310. o->mode = Addressing_SoaVariable;
  7311. } else {
  7312. o->mode = Addressing_Value;
  7313. }
  7314. return true;
  7315. }
  7316. return false;
  7317. }
  7318. if (is_type_pointer(original_type) && indirection) {
  7319. Type *ptr = base_type(original_type);
  7320. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7321. o->type = ptr->MultiPointer.elem;
  7322. o->mode = Addressing_Value;
  7323. return true;
  7324. }
  7325. }
  7326. return false;
  7327. }
  7328. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7329. if (is_type_untyped_uninit(x)) {
  7330. return true;
  7331. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7332. return true;
  7333. } else if (is_type_untyped_uninit(y)) {
  7334. return true;
  7335. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7336. return true;
  7337. }
  7338. return are_types_identical(x, y);
  7339. }
  7340. 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) {
  7341. if (!is_ast_range(node)) {
  7342. return false;
  7343. }
  7344. ast_node(ie, BinaryExpr, node);
  7345. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7346. if (x->mode == Addressing_Invalid) {
  7347. return false;
  7348. }
  7349. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7350. if (y->mode == Addressing_Invalid) {
  7351. return false;
  7352. }
  7353. convert_to_typed(c, x, y->type);
  7354. if (x->mode == Addressing_Invalid) {
  7355. return false;
  7356. }
  7357. convert_to_typed(c, y, x->type);
  7358. if (y->mode == Addressing_Invalid) {
  7359. return false;
  7360. }
  7361. convert_to_typed(c, x, default_type(y->type));
  7362. if (x->mode == Addressing_Invalid) {
  7363. return false;
  7364. }
  7365. convert_to_typed(c, y, default_type(x->type));
  7366. if (y->mode == Addressing_Invalid) {
  7367. return false;
  7368. }
  7369. if (!are_types_identical(x->type, y->type)) {
  7370. if (x->type != t_invalid &&
  7371. y->type != t_invalid) {
  7372. gbString xt = type_to_string(x->type);
  7373. gbString yt = type_to_string(y->type);
  7374. gbString expr_str = expr_to_string(x->expr);
  7375. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7376. gb_string_free(expr_str);
  7377. gb_string_free(yt);
  7378. gb_string_free(xt);
  7379. }
  7380. return false;
  7381. }
  7382. Type *type = x->type;
  7383. if (is_for_loop) {
  7384. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7385. error(ie->op, "Only numerical types are allowed within interval expressions");
  7386. return false;
  7387. }
  7388. } else {
  7389. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7390. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7391. return false;
  7392. }
  7393. }
  7394. if (x->mode == Addressing_Constant &&
  7395. y->mode == Addressing_Constant) {
  7396. ExactValue a = x->value;
  7397. ExactValue b = y->value;
  7398. GB_ASSERT(are_types_identical(x->type, y->type));
  7399. TokenKind op = Token_Lt;
  7400. switch (ie->op.kind) {
  7401. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7402. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7403. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7404. default: error(ie->op, "Invalid range operator"); break;
  7405. }
  7406. bool ok = compare_exact_values(op, a, b);
  7407. if (!ok) {
  7408. // TODO(bill): Better error message
  7409. error(ie->op, "Invalid interval range");
  7410. return false;
  7411. }
  7412. ExactValue inline_for_depth = exact_value_sub(b, a);
  7413. if (ie->op.kind != Token_RangeHalf) {
  7414. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7415. }
  7416. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7417. } else if (inline_for_depth_ != nullptr) {
  7418. error(ie->op, "Interval expressions must be constant");
  7419. return false;
  7420. }
  7421. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7422. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7423. return true;
  7424. }
  7425. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7426. if (is_operand_nil(*o)) {
  7427. return true;
  7428. }
  7429. Ast *expr = unparen_expr(o->expr);
  7430. if (expr != nullptr) {
  7431. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7432. if (e != nullptr && e->kind == Entity_Procedure) {
  7433. return true;
  7434. }
  7435. if (expr->kind == Ast_ProcLit) {
  7436. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7437. return true;
  7438. }
  7439. }
  7440. return o->mode == Addressing_Constant;
  7441. }
  7442. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7443. if (is_type_enum(th)) {
  7444. Type *enum_type = base_type(th);
  7445. GB_ASSERT(enum_type->kind == Type_Enum);
  7446. String name = ise->selector->Ident.token.string;
  7447. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7448. if (e == nullptr) {
  7449. return false;
  7450. }
  7451. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7452. GB_ASSERT(e->kind == Entity_Constant);
  7453. o->value = e->Constant.value;
  7454. o->mode = Addressing_Constant;
  7455. o->type = e->type;
  7456. return true;
  7457. }
  7458. if (is_type_union(th)) {
  7459. TEMPORARY_ALLOCATOR_GUARD();
  7460. Type *union_type = base_type(th);
  7461. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7462. for (Type *vt : union_type->Union.variants) {
  7463. Operand x = {};
  7464. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7465. array_add(&operands, x);
  7466. }
  7467. }
  7468. if (operands.count == 1) {
  7469. *o = operands[0];
  7470. return true;
  7471. }
  7472. }
  7473. return false;
  7474. }
  7475. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7476. ast_node(ise, ImplicitSelectorExpr, node);
  7477. o->type = t_invalid;
  7478. o->expr = node;
  7479. o->mode = Addressing_Invalid;
  7480. Type *th = type_hint;
  7481. if (th == nullptr) {
  7482. gbString str = expr_to_string(node);
  7483. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7484. gb_string_free(str);
  7485. return Expr_Expr;
  7486. }
  7487. o->type = th;
  7488. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7489. if (!ok) {
  7490. String name = ise->selector->Ident.token.string;
  7491. if (is_type_enum(th)) {
  7492. ERROR_BLOCK();
  7493. Type *bt = base_type(th);
  7494. GB_ASSERT(bt->kind == Type_Enum);
  7495. gbString typ = type_to_string(th);
  7496. defer (gb_string_free(typ));
  7497. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7498. check_did_you_mean_type(name, bt->Enum.fields);
  7499. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7500. ERROR_BLOCK();
  7501. gbString typ = type_to_string(th);
  7502. gbString str = expr_to_string(node);
  7503. error(node, "Cannot convert enum value to '%s'", typ);
  7504. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7505. gb_string_free(typ);
  7506. gb_string_free(str);
  7507. } else {
  7508. gbString typ = type_to_string(th);
  7509. gbString str = expr_to_string(node);
  7510. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7511. gb_string_free(str);
  7512. gb_string_free(typ);
  7513. }
  7514. }
  7515. o->expr = node;
  7516. return Expr_Expr;
  7517. }
  7518. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7519. switch (x->mode) {
  7520. case Addressing_MapIndex:
  7521. case Addressing_OptionalOk:
  7522. case Addressing_OptionalOkPtr:
  7523. if (val_type_) *val_type_ = x->type;
  7524. break;
  7525. default:
  7526. if (ok_type_) *ok_type_ = x->type;
  7527. return;
  7528. }
  7529. Ast *expr = unparen_expr(x->expr);
  7530. if (expr->kind == Ast_CallExpr) {
  7531. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7532. if (is_type_proc(pt)) {
  7533. Type *tuple = pt->Proc.results;
  7534. if (pt->Proc.result_count >= 2) {
  7535. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7536. }
  7537. if (change_operand) {
  7538. expr->CallExpr.optional_ok_one = false;
  7539. x->type = tuple;
  7540. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7541. }
  7542. return;
  7543. }
  7544. }
  7545. Type *tuple = make_optional_ok_type(x->type);
  7546. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7547. if (change_operand) {
  7548. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7549. x->type = tuple;
  7550. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7551. }
  7552. }
  7553. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7554. ast_node(ie, MatrixIndexExpr, node);
  7555. check_expr(c, o, ie->expr);
  7556. node->viral_state_flags |= ie->expr->viral_state_flags;
  7557. if (o->mode == Addressing_Invalid) {
  7558. o->expr = node;
  7559. return;
  7560. }
  7561. Type *t = base_type(type_deref(o->type));
  7562. bool is_ptr = is_type_pointer(o->type);
  7563. bool is_const = o->mode == Addressing_Constant;
  7564. if (t->kind != Type_Matrix) {
  7565. gbString str = expr_to_string(o->expr);
  7566. gbString type_str = type_to_string(o->type);
  7567. defer (gb_string_free(str));
  7568. defer (gb_string_free(type_str));
  7569. if (is_const) {
  7570. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7571. } else {
  7572. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7573. }
  7574. o->mode = Addressing_Invalid;
  7575. o->expr = node;
  7576. return;
  7577. }
  7578. o->type = t->Matrix.elem;
  7579. if (is_ptr) {
  7580. o->mode = Addressing_Variable;
  7581. } else if (o->mode != Addressing_Variable) {
  7582. o->mode = Addressing_Value;
  7583. }
  7584. if (ie->row_index == nullptr) {
  7585. gbString str = expr_to_string(o->expr);
  7586. error(o->expr, "Missing row index for '%s'", str);
  7587. gb_string_free(str);
  7588. o->mode = Addressing_Invalid;
  7589. o->expr = node;
  7590. return;
  7591. }
  7592. if (ie->column_index == nullptr) {
  7593. gbString str = expr_to_string(o->expr);
  7594. error(o->expr, "Missing column index for '%s'", str);
  7595. gb_string_free(str);
  7596. o->mode = Addressing_Invalid;
  7597. o->expr = node;
  7598. return;
  7599. }
  7600. i64 row_count = t->Matrix.row_count;
  7601. i64 column_count = t->Matrix.column_count;
  7602. i64 row_index = 0;
  7603. i64 column_index = 0;
  7604. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7605. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7606. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7607. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7608. }
  7609. gb_unused(row_ok);
  7610. gb_unused(column_ok);
  7611. }
  7612. struct TypeAndToken {
  7613. Type *type;
  7614. Token token;
  7615. };
  7616. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7617. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7618. if (operand.mode != Addressing_Constant) {
  7619. return;
  7620. }
  7621. if (operand.value.kind == ExactValue_Invalid) {
  7622. return;
  7623. }
  7624. uintptr key = hash_exact_value(operand.value);
  7625. GB_ASSERT(key != 0);
  7626. isize count = multi_map_count(seen, key);
  7627. if (count) {
  7628. TEMPORARY_ALLOCATOR_GUARD();
  7629. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7630. multi_map_get_all(seen, key, taps);
  7631. for (isize i = 0; i < count; i++) {
  7632. TypeAndToken tap = taps[i];
  7633. Operand to = {};
  7634. to.mode = Addressing_Value;
  7635. to.type = tap.type;
  7636. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7637. continue;
  7638. }
  7639. TokenPos pos = tap.token.pos;
  7640. if (use_expr) {
  7641. gbString expr_str = expr_to_string(operand.expr);
  7642. error(operand.expr,
  7643. "Duplicate case '%s'\n"
  7644. "\tprevious case at %s",
  7645. expr_str,
  7646. token_pos_to_string(pos));
  7647. gb_string_free(expr_str);
  7648. } else {
  7649. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7650. }
  7651. return;
  7652. }
  7653. }
  7654. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7655. multi_map_insert(seen, key, tap);
  7656. }
  7657. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7658. if (is_type_enum(x.type)) {
  7659. // TODO(bill): Fix this logic so it's fast!!!
  7660. i64 v0 = exact_value_to_i64(lhs.value);
  7661. i64 v1 = exact_value_to_i64(rhs.value);
  7662. Operand v = {};
  7663. v.mode = Addressing_Constant;
  7664. v.type = x.type;
  7665. v.expr = x.expr;
  7666. Type *bt = base_type(x.type);
  7667. GB_ASSERT(bt->kind == Type_Enum);
  7668. for (i64 vi = v0; vi <= v1; vi++) {
  7669. if (upper_op != Token_LtEq && vi == v1) {
  7670. break;
  7671. }
  7672. v.value = exact_value_i64(vi);
  7673. add_constant_switch_case(ctx, seen, v);
  7674. }
  7675. } else {
  7676. add_constant_switch_case(ctx, seen, lhs);
  7677. if (upper_op == Token_LtEq) {
  7678. add_constant_switch_case(ctx, seen, rhs);
  7679. }
  7680. }
  7681. }
  7682. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7683. add_constant_switch_case(ctx, seen, x);
  7684. }
  7685. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7686. ast_node(bd, BasicDirective, node);
  7687. ExprKind kind = Expr_Expr;
  7688. o->mode = Addressing_Constant;
  7689. String name = bd->name.string;
  7690. if (name == "file") {
  7691. String file = get_file_path_string(bd->token.pos.file_id);
  7692. switch (build_context.source_code_location_info) {
  7693. case SourceCodeLocationInfo_Normal:
  7694. break;
  7695. case SourceCodeLocationInfo_Obfuscated:
  7696. file = obfuscate_string(file, "F");
  7697. break;
  7698. case SourceCodeLocationInfo_Filename:
  7699. file = last_path_element(file);
  7700. break;
  7701. case SourceCodeLocationInfo_None:
  7702. file = str_lit("");
  7703. break;
  7704. }
  7705. o->type = t_untyped_string;
  7706. o->value = exact_value_string(file);
  7707. } else if (name == "directory") {
  7708. String file = get_file_path_string(bd->token.pos.file_id);
  7709. String path = dir_from_path(file);
  7710. switch (build_context.source_code_location_info) {
  7711. case SourceCodeLocationInfo_Normal:
  7712. break;
  7713. case SourceCodeLocationInfo_Obfuscated:
  7714. path = obfuscate_string(path, "D");
  7715. break;
  7716. case SourceCodeLocationInfo_Filename:
  7717. path = last_path_element(path);
  7718. break;
  7719. case SourceCodeLocationInfo_None:
  7720. path = str_lit("");
  7721. break;
  7722. }
  7723. o->type = t_untyped_string;
  7724. o->value = exact_value_string(path);
  7725. } else if (name == "line") {
  7726. i32 line = bd->token.pos.line;
  7727. switch (build_context.source_code_location_info) {
  7728. case SourceCodeLocationInfo_Normal:
  7729. break;
  7730. case SourceCodeLocationInfo_Obfuscated:
  7731. line = obfuscate_i32(line);
  7732. break;
  7733. case SourceCodeLocationInfo_Filename:
  7734. break;
  7735. case SourceCodeLocationInfo_None:
  7736. line = 0;
  7737. break;
  7738. }
  7739. o->type = t_untyped_integer;
  7740. o->value = exact_value_i64(line);
  7741. } else if (name == "procedure") {
  7742. if (c->curr_proc_decl == nullptr) {
  7743. error(node, "#procedure may only be used within procedures");
  7744. o->type = t_untyped_string;
  7745. o->value = exact_value_string(str_lit(""));
  7746. } else {
  7747. String p = c->proc_name;
  7748. switch (build_context.source_code_location_info) {
  7749. case SourceCodeLocationInfo_Normal:
  7750. break;
  7751. case SourceCodeLocationInfo_Obfuscated:
  7752. p = obfuscate_string(p, "P");
  7753. break;
  7754. case SourceCodeLocationInfo_Filename:
  7755. break;
  7756. case SourceCodeLocationInfo_None:
  7757. p = str_lit("");
  7758. break;
  7759. }
  7760. o->type = t_untyped_string;
  7761. o->value = exact_value_string(p);
  7762. }
  7763. } else if (name == "caller_location") {
  7764. init_core_source_code_location(c->checker);
  7765. error(node, "#caller_location may only be used as a default argument parameter");
  7766. o->type = t_source_code_location;
  7767. o->mode = Addressing_Value;
  7768. } else if (name == "caller_expression") {
  7769. error(node, "#caller_expression may only be used as a default argument parameter");
  7770. o->type = t_string;
  7771. o->mode = Addressing_Value;
  7772. } else if (name == "branch_location") {
  7773. if (!c->in_defer) {
  7774. error(node, "#branch_location may only be used within a 'defer' statement");
  7775. } else if (c->curr_proc_decl) {
  7776. Entity *e = c->curr_proc_decl->entity;
  7777. if (e != nullptr) {
  7778. GB_ASSERT(e->kind == Entity_Procedure);
  7779. e->Procedure.uses_branch_location = true;
  7780. }
  7781. }
  7782. o->type = t_source_code_location;
  7783. o->mode = Addressing_Value;
  7784. } else {
  7785. if (name == "location") {
  7786. init_core_source_code_location(c->checker);
  7787. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7788. o->type = t_source_code_location;
  7789. o->mode = Addressing_Value;
  7790. } else if (
  7791. name == "assert" ||
  7792. name == "defined" ||
  7793. name == "config" ||
  7794. name == "exists" ||
  7795. name == "load" ||
  7796. name == "load_hash" ||
  7797. name == "load_directory" ||
  7798. name == "load_or"
  7799. ) {
  7800. error(node, "'#%.*s' must be used as a call", LIT(name));
  7801. o->type = t_invalid;
  7802. o->mode = Addressing_Invalid;
  7803. } else {
  7804. error(node, "Unknown directive: #%.*s", LIT(name));
  7805. o->type = t_invalid;
  7806. o->mode = Addressing_Invalid;
  7807. }
  7808. }
  7809. return kind;
  7810. }
  7811. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7812. ExprKind kind = Expr_Expr;
  7813. Operand cond = {Addressing_Invalid};
  7814. ast_node(te, TernaryIfExpr, node);
  7815. check_expr(c, &cond, te->cond);
  7816. node->viral_state_flags |= te->cond->viral_state_flags;
  7817. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7818. error(te->cond, "Non-boolean condition in ternary if expression");
  7819. }
  7820. Operand x = {Addressing_Invalid};
  7821. Operand y = {Addressing_Invalid};
  7822. check_expr_or_type(c, &x, te->x, type_hint);
  7823. node->viral_state_flags |= te->x->viral_state_flags;
  7824. if (te->y != nullptr) {
  7825. Type *th = type_hint;
  7826. if (type_hint == nullptr && is_type_typed(x.type)) {
  7827. th = x.type;
  7828. }
  7829. check_expr_or_type(c, &y, te->y, th);
  7830. node->viral_state_flags |= te->y->viral_state_flags;
  7831. } else {
  7832. error(node, "A ternary expression must have an else clause");
  7833. return kind;
  7834. }
  7835. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7836. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7837. gbString type_string = expr_to_string(type_expr);
  7838. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7839. gb_string_free(type_string);
  7840. return kind;
  7841. }
  7842. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7843. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7844. if (x.mode == Addressing_Invalid) {
  7845. return kind;
  7846. }
  7847. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7848. if (y.mode == Addressing_Invalid) {
  7849. x.mode = Addressing_Invalid;
  7850. return kind;
  7851. }
  7852. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7853. // x: union{f32} = f32(123) if cond else nil
  7854. if (type_hint && !is_type_any(type_hint)) {
  7855. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7856. check_cast(c, &x, type_hint);
  7857. check_cast(c, &y, type_hint);
  7858. }
  7859. }
  7860. if (!ternary_compare_types(x.type, y.type)) {
  7861. gbString its = type_to_string(x.type);
  7862. gbString ets = type_to_string(y.type);
  7863. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7864. gb_string_free(ets);
  7865. gb_string_free(its);
  7866. return kind;
  7867. }
  7868. o->type = x.type;
  7869. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7870. o->type = y.type;
  7871. }
  7872. o->mode = Addressing_Value;
  7873. o->expr = node;
  7874. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7875. if (check_cast_internal(c, &x, type_hint) &&
  7876. check_cast_internal(c, &y, type_hint)) {
  7877. convert_to_typed(c, o, type_hint);
  7878. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7879. o->type = type_hint;
  7880. }
  7881. }
  7882. return kind;
  7883. }
  7884. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7885. ExprKind kind = Expr_Expr;
  7886. Operand cond = {};
  7887. ast_node(te, TernaryWhenExpr, node);
  7888. check_expr(c, &cond, te->cond);
  7889. node->viral_state_flags |= te->cond->viral_state_flags;
  7890. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7891. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7892. return kind;
  7893. }
  7894. if (cond.value.value_bool) {
  7895. check_expr_or_type(c, o, te->x, type_hint);
  7896. node->viral_state_flags |= te->x->viral_state_flags;
  7897. } else {
  7898. if (te->y != nullptr) {
  7899. check_expr_or_type(c, o, te->y, type_hint);
  7900. node->viral_state_flags |= te->y->viral_state_flags;
  7901. } else {
  7902. error(node, "A ternary when expression must have an else clause");
  7903. return kind;
  7904. }
  7905. }
  7906. return kind;
  7907. }
  7908. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7909. ast_node(oe, OrElseExpr, node);
  7910. String name = oe->token.string;
  7911. Ast *arg = oe->x;
  7912. Ast *default_value = oe->y;
  7913. Operand x = {};
  7914. Operand y = {};
  7915. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7916. if (is_load_directive_call(arg)) {
  7917. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7918. // Allow for chaining of '#load(path) or_else #load(path)'
  7919. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7920. bool y_is_diverging = false;
  7921. check_expr_base(c, &y, default_value, x.type);
  7922. switch (y.mode) {
  7923. case Addressing_NoValue:
  7924. if (is_diverging_expr(y.expr)) {
  7925. // Allow
  7926. y.mode = Addressing_Value;
  7927. y_is_diverging = true;
  7928. } else {
  7929. error_operand_no_value(&y);
  7930. y.mode = Addressing_Invalid;
  7931. }
  7932. break;
  7933. case Addressing_Type:
  7934. error_operand_not_expression(&y);
  7935. y.mode = Addressing_Invalid;
  7936. break;
  7937. }
  7938. if (y.mode == Addressing_Invalid) {
  7939. o->mode = Addressing_Value;
  7940. o->type = t_invalid;
  7941. o->expr = node;
  7942. return Expr_Expr;
  7943. }
  7944. if (!y_is_diverging) {
  7945. check_assignment(c, &y, x.type, name);
  7946. if (y.mode != Addressing_Constant) {
  7947. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7948. }
  7949. }
  7950. }
  7951. if (res == LoadDirective_Success) {
  7952. *o = x;
  7953. } else {
  7954. *o = y;
  7955. }
  7956. o->expr = node;
  7957. return Expr_Expr;
  7958. }
  7959. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7960. if (x.mode == Addressing_Invalid) {
  7961. o->mode = Addressing_Value;
  7962. o->type = t_invalid;
  7963. o->expr = node;
  7964. return Expr_Expr;
  7965. }
  7966. Type *left_type = nullptr;
  7967. Type *right_type = nullptr;
  7968. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7969. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7970. bool y_is_diverging = false;
  7971. check_expr_base(c, &y, default_value, left_type);
  7972. switch (y.mode) {
  7973. case Addressing_NoValue:
  7974. if (is_diverging_expr(y.expr)) {
  7975. // Allow
  7976. y.mode = Addressing_Value;
  7977. y_is_diverging = true;
  7978. } else {
  7979. error_operand_no_value(&y);
  7980. y.mode = Addressing_Invalid;
  7981. }
  7982. break;
  7983. case Addressing_Type:
  7984. error_operand_not_expression(&y);
  7985. y.mode = Addressing_Invalid;
  7986. break;
  7987. }
  7988. if (y.mode == Addressing_Invalid) {
  7989. o->mode = Addressing_Value;
  7990. o->type = t_invalid;
  7991. o->expr = node;
  7992. return Expr_Expr;
  7993. }
  7994. if (left_type != nullptr) {
  7995. if (!y_is_diverging) {
  7996. if (is_type_tuple(left_type)) {
  7997. if (!is_type_tuple(y.type)) {
  7998. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  7999. } else if (!are_types_identical(left_type, y.type)) {
  8000. gbString xt = type_to_string(left_type);
  8001. gbString yt = type_to_string(y.type);
  8002. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  8003. gb_string_free(yt);
  8004. gb_string_free(xt);
  8005. }
  8006. } else {
  8007. check_assignment(c, &y, left_type, name);
  8008. }
  8009. }
  8010. } else {
  8011. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8012. }
  8013. if (left_type == nullptr) {
  8014. left_type = t_invalid;
  8015. }
  8016. o->mode = Addressing_Value;
  8017. o->type = left_type;
  8018. o->expr = node;
  8019. return Expr_Expr;
  8020. }
  8021. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8022. ast_node(re, OrReturnExpr, node);
  8023. String name = re->token.string;
  8024. Operand x = {};
  8025. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  8026. if (x.mode == Addressing_Invalid) {
  8027. o->mode = Addressing_Value;
  8028. o->type = t_invalid;
  8029. o->expr = node;
  8030. return Expr_Expr;
  8031. }
  8032. Type *left_type = nullptr;
  8033. Type *right_type = nullptr;
  8034. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8035. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  8036. if (right_type == nullptr) {
  8037. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8038. } else {
  8039. Type *proc_type = base_type(c->curr_proc_sig);
  8040. GB_ASSERT(proc_type->kind == Type_Proc);
  8041. Type *result_type = proc_type->Proc.results;
  8042. if (result_type == nullptr) {
  8043. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8044. } else {
  8045. GB_ASSERT(result_type->kind == Type_Tuple);
  8046. auto const &vars = result_type->Tuple.variables;
  8047. Type *end_type = vars[vars.count-1]->type;
  8048. if (vars.count > 1) {
  8049. if (!proc_type->Proc.has_named_results) {
  8050. 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));
  8051. }
  8052. }
  8053. Operand rhs = {};
  8054. rhs.type = right_type;
  8055. rhs.mode = Addressing_Value;
  8056. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8057. // NOTE(bill): allow implicit conversion between boolean types
  8058. // within 'or_return' to improve the experience using third-party code
  8059. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8060. ERROR_BLOCK();
  8061. // TODO(bill): better error message
  8062. gbString a = type_to_string(right_type);
  8063. gbString b = type_to_string(end_type);
  8064. gbString ret_type = type_to_string(result_type);
  8065. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8066. if (vars.count == 1) {
  8067. error_line("\tProcedure return value type: %s\n", ret_type);
  8068. } else {
  8069. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8070. }
  8071. gb_string_free(ret_type);
  8072. gb_string_free(b);
  8073. gb_string_free(a);
  8074. }
  8075. }
  8076. }
  8077. o->expr = node;
  8078. o->type = left_type;
  8079. if (left_type != nullptr) {
  8080. o->mode = Addressing_Value;
  8081. } else {
  8082. o->mode = Addressing_NoValue;
  8083. }
  8084. if (c->curr_proc_sig == nullptr) {
  8085. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8086. }
  8087. if (c->in_defer) {
  8088. error(node, "'or_return' cannot be used within a defer statement");
  8089. }
  8090. return Expr_Expr;
  8091. }
  8092. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8093. ast_node(be, OrBranchExpr, node);
  8094. String name = be->token.string;
  8095. Operand x = {};
  8096. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8097. if (x.mode == Addressing_Invalid) {
  8098. o->mode = Addressing_Value;
  8099. o->type = t_invalid;
  8100. o->expr = node;
  8101. return Expr_Expr;
  8102. }
  8103. Type *left_type = nullptr;
  8104. Type *right_type = nullptr;
  8105. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8106. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8107. if (right_type == nullptr) {
  8108. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8109. } else {
  8110. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8111. // okay
  8112. } else {
  8113. gbString s = type_to_string(right_type);
  8114. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8115. gb_string_free(s);
  8116. }
  8117. }
  8118. o->expr = node;
  8119. o->type = left_type;
  8120. if (left_type != nullptr) {
  8121. o->mode = Addressing_Value;
  8122. } else {
  8123. o->mode = Addressing_NoValue;
  8124. }
  8125. if (c->curr_proc_sig == nullptr) {
  8126. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8127. }
  8128. Ast *label = be->label;
  8129. switch (be->token.kind) {
  8130. case Token_or_break:
  8131. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8132. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8133. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8134. }
  8135. break;
  8136. case Token_or_continue:
  8137. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8138. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8139. }
  8140. break;
  8141. }
  8142. if (label != nullptr) {
  8143. if (c->in_defer) {
  8144. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8145. return Expr_Expr;
  8146. }
  8147. if (label->kind != Ast_Ident) {
  8148. error(label, "A branch statement's label name must be an identifier");
  8149. return Expr_Expr;
  8150. }
  8151. Ast *ident = label;
  8152. String name = ident->Ident.token.string;
  8153. Operand o = {};
  8154. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8155. if (e == nullptr) {
  8156. error(ident, "Undeclared label name: %.*s", LIT(name));
  8157. return Expr_Expr;
  8158. }
  8159. add_entity_use(c, ident, e);
  8160. if (e->kind != Entity_Label) {
  8161. error(ident, "'%.*s' is not a label", LIT(name));
  8162. return Expr_Expr;
  8163. }
  8164. Ast *parent = e->Label.parent;
  8165. GB_ASSERT(parent != nullptr);
  8166. switch (parent->kind) {
  8167. case Ast_BlockStmt:
  8168. case Ast_IfStmt:
  8169. case Ast_SwitchStmt:
  8170. if (be->token.kind != Token_or_break) {
  8171. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8172. }
  8173. break;
  8174. case Ast_RangeStmt:
  8175. case Ast_ForStmt:
  8176. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8177. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8178. }
  8179. break;
  8180. }
  8181. }
  8182. return Expr_Expr;
  8183. }
  8184. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8185. Type *bt = base_type(type);
  8186. StringSet fields_visited = {};
  8187. defer (string_set_destroy(&fields_visited));
  8188. StringMap<String> fields_visited_through_raw_union = {};
  8189. defer (string_map_destroy(&fields_visited_through_raw_union));
  8190. String assignment_str = str_lit("structure literal");
  8191. if (bt->kind == Type_BitField) {
  8192. assignment_str = str_lit("bit_field literal");
  8193. }
  8194. for (Ast *elem : elems) {
  8195. if (elem->kind != Ast_FieldValue) {
  8196. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8197. continue;
  8198. }
  8199. ast_node(fv, FieldValue, elem);
  8200. Ast *ident = fv->field;
  8201. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8202. gbString expr_str = expr_to_string(ident);
  8203. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8204. gb_string_free(expr_str);
  8205. ident = ident->ImplicitSelectorExpr.selector;
  8206. }
  8207. if (ident->kind != Ast_Ident) {
  8208. gbString expr_str = expr_to_string(ident);
  8209. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8210. gb_string_free(expr_str);
  8211. continue;
  8212. }
  8213. String name = ident->Ident.token.string;
  8214. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8215. bool is_unknown = sel.entity == nullptr;
  8216. if (is_unknown) {
  8217. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8218. continue;
  8219. }
  8220. Entity *field = nullptr;
  8221. if (bt->kind == Type_Struct) {
  8222. field = bt->Struct.fields[sel.index[0]];
  8223. } else if (bt->kind == Type_BitField) {
  8224. field = bt->BitField.fields[sel.index[0]];
  8225. } else {
  8226. GB_PANIC("Unknown type");
  8227. }
  8228. add_entity_use(c, ident, field);
  8229. if (string_set_update(&fields_visited, name)) {
  8230. if (sel.index.count > 1) {
  8231. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8232. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8233. } else {
  8234. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8235. }
  8236. } else {
  8237. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8238. }
  8239. continue;
  8240. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8241. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8242. continue;
  8243. }
  8244. if (sel.indirect) {
  8245. error(ident, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a %.*s", cast(int)sel.index.count-1, LIT(name), LIT(assignment_str));
  8246. continue;
  8247. }
  8248. if (sel.index.count > 1) {
  8249. GB_ASSERT(bt->kind == Type_Struct);
  8250. if (is_constant) {
  8251. Type *ft = type;
  8252. for (i32 index : sel.index) {
  8253. Type *bt = base_type(ft);
  8254. switch (bt->kind) {
  8255. case Type_Struct:
  8256. if (bt->Struct.is_raw_union) {
  8257. is_constant = false;
  8258. break;
  8259. }
  8260. ft = bt->Struct.fields[index]->type;
  8261. break;
  8262. case Type_Array:
  8263. ft = bt->Array.elem;
  8264. break;
  8265. case Type_BitField:
  8266. is_constant = false;
  8267. ft = bt->BitField.fields[index]->type;
  8268. break;
  8269. default:
  8270. GB_PANIC("invalid type: %s", type_to_string(ft));
  8271. break;
  8272. }
  8273. }
  8274. if (is_constant &&
  8275. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8276. is_constant = false;
  8277. }
  8278. }
  8279. Type *nested_ft = bt;
  8280. for (i32 index : sel.index) {
  8281. Type *bt = base_type(nested_ft);
  8282. switch (bt->kind) {
  8283. case Type_Struct:
  8284. if (bt->Struct.is_raw_union) {
  8285. for (Entity *re : bt->Struct.fields) {
  8286. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8287. }
  8288. }
  8289. nested_ft = bt->Struct.fields[index]->type;
  8290. break;
  8291. case Type_Array:
  8292. nested_ft = bt->Array.elem;
  8293. break;
  8294. case Type_BitField:
  8295. nested_ft = bt->BitField.fields[index]->type;
  8296. break;
  8297. default:
  8298. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8299. break;
  8300. }
  8301. }
  8302. field = sel.entity;
  8303. }
  8304. Operand o = {};
  8305. check_expr_or_type(c, &o, fv->value, field->type);
  8306. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8307. is_constant = false;
  8308. }
  8309. if (is_constant) {
  8310. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8311. }
  8312. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8313. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8314. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8315. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8316. }
  8317. check_assignment(c, &o, field->type, assignment_str);
  8318. c->bit_field_bit_size = prev_bit_field_bit_size;
  8319. }
  8320. }
  8321. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8322. type_expr = unparen_expr(type_expr);
  8323. if (type_expr == nullptr) {
  8324. return false;
  8325. }
  8326. // [?]Type
  8327. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8328. Ast *count = type_expr->ArrayType.count;
  8329. if (count->kind == Ast_UnaryExpr &&
  8330. count->UnaryExpr.op.kind == Token_Question) {
  8331. return true;
  8332. }
  8333. }
  8334. return false;
  8335. }
  8336. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8337. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8338. ERROR_BLOCK();
  8339. error(node, "Compound literals of dynamic types are disabled by default");
  8340. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8341. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8342. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8343. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8344. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8345. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8346. }
  8347. return false;
  8348. }
  8349. return cl->elems.count > 0;
  8350. }
  8351. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8352. ExprKind kind = Expr_Expr;
  8353. ast_node(cl, CompoundLit, node);
  8354. Type *type = type_hint;
  8355. if (type != nullptr && is_type_untyped(type)) {
  8356. type = nullptr;
  8357. }
  8358. bool is_to_be_determined_array_count = false;
  8359. bool is_constant = true;
  8360. bool is_soa = false;
  8361. Ast *type_expr = cl->type;
  8362. bool used_type_hint_expr = false;
  8363. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8364. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8365. type_expr = clone_ast(c->type_hint_expr);
  8366. used_type_hint_expr = true;
  8367. }
  8368. }
  8369. if (type_expr != nullptr) {
  8370. type = nullptr;
  8371. // [?]Type
  8372. if (type_expr->kind == Ast_ArrayType) {
  8373. Ast *count = type_expr->ArrayType.count;
  8374. if (count != nullptr) {
  8375. if (count->kind == Ast_UnaryExpr &&
  8376. count->UnaryExpr.op.kind == Token_Question) {
  8377. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8378. is_to_be_determined_array_count = true;
  8379. }
  8380. } else {
  8381. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8382. }
  8383. if (cl->elems.count > 0) {
  8384. if (type_expr->ArrayType.tag != nullptr) {
  8385. Ast *tag = type_expr->ArrayType.tag;
  8386. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8387. String name = tag->BasicDirective.name.string;
  8388. if (name == "soa") {
  8389. is_soa = true;
  8390. if (count == nullptr) {
  8391. error(node, "#soa slices are not supported for compound literals");
  8392. return kind;
  8393. } else if (count->kind == Ast_UnaryExpr &&
  8394. count->UnaryExpr.op.kind == Token_Question) {
  8395. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8396. }
  8397. }
  8398. }
  8399. }
  8400. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8401. if (cl->elems.count > 0) {
  8402. Ast *tag = type_expr->DynamicArrayType.tag;
  8403. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8404. String name = tag->BasicDirective.name.string;
  8405. if (name == "soa") {
  8406. is_soa = true;
  8407. error(node, "#soa dynamic arrays are not supported for compound literals");
  8408. return kind;
  8409. }
  8410. }
  8411. }
  8412. if (type == nullptr) {
  8413. type = check_type(c, type_expr);
  8414. }
  8415. }
  8416. if (type == nullptr) {
  8417. error(node, "Missing type in compound literal");
  8418. return kind;
  8419. }
  8420. Type *t = base_type(type);
  8421. if (is_type_polymorphic(t)) {
  8422. gbString str = type_to_string(type);
  8423. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8424. o->expr = node;
  8425. o->type = type;
  8426. gb_string_free(str);
  8427. return kind;
  8428. }
  8429. switch (t->kind) {
  8430. case Type_Struct:
  8431. if (cl->elems.count == 0) {
  8432. break; // NOTE(bill): No need to init
  8433. }
  8434. if (t->Struct.soa_kind == StructSoa_None) {
  8435. if (t->Struct.is_raw_union) {
  8436. if (cl->elems.count > 0) {
  8437. // NOTE: unions cannot be constant
  8438. is_constant = false;
  8439. if (cl->elems[0]->kind != Ast_FieldValue) {
  8440. gbString type_str = type_to_string(type);
  8441. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8442. gb_string_free(type_str);
  8443. } else {
  8444. if (cl->elems.count != 1) {
  8445. gbString type_str = type_to_string(type);
  8446. 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);
  8447. gb_string_free(type_str);
  8448. } else {
  8449. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8450. }
  8451. }
  8452. }
  8453. break;
  8454. }
  8455. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8456. isize field_count = t->Struct.fields.count;
  8457. isize min_field_count = t->Struct.fields.count;
  8458. for (isize i = min_field_count-1; i >= 0; i--) {
  8459. Entity *e = t->Struct.fields[i];
  8460. GB_ASSERT(e->kind == Entity_Variable);
  8461. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8462. min_field_count--;
  8463. } else {
  8464. break;
  8465. }
  8466. }
  8467. if (cl->elems[0]->kind == Ast_FieldValue) {
  8468. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8469. } else {
  8470. bool seen_field_value = false;
  8471. for_array(index, cl->elems) {
  8472. Entity *field = nullptr;
  8473. Ast *elem = cl->elems[index];
  8474. if (elem->kind == Ast_FieldValue) {
  8475. seen_field_value = true;
  8476. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8477. continue;
  8478. } else if (seen_field_value) {
  8479. error(elem, "Value elements cannot be used after a 'field = value'");
  8480. continue;
  8481. }
  8482. if (index >= field_count) {
  8483. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8484. break;
  8485. }
  8486. if (field == nullptr) {
  8487. field = t->Struct.fields[index];
  8488. }
  8489. Operand o = {};
  8490. check_expr_or_type(c, &o, elem, field->type);
  8491. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8492. is_constant = false;
  8493. }
  8494. if (is_constant) {
  8495. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8496. }
  8497. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8498. }
  8499. if (cl->elems.count < field_count) {
  8500. if (min_field_count < field_count) {
  8501. if (cl->elems.count < min_field_count) {
  8502. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8503. }
  8504. } else {
  8505. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8506. }
  8507. }
  8508. }
  8509. break;
  8510. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8511. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8512. break;
  8513. }
  8514. /*fallthrough*/
  8515. case Type_Slice:
  8516. case Type_Array:
  8517. case Type_DynamicArray:
  8518. case Type_SimdVector:
  8519. case Type_Matrix:
  8520. {
  8521. Type *elem_type = nullptr;
  8522. String context_name = {};
  8523. i64 max_type_count = -1;
  8524. if (t->kind == Type_Struct) {
  8525. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8526. elem_type = t->Struct.soa_elem;
  8527. context_name = str_lit("#soa array literal");
  8528. if (!is_to_be_determined_array_count) {
  8529. max_type_count = t->Struct.soa_count;
  8530. }
  8531. } else if (t->kind == Type_Slice) {
  8532. elem_type = t->Slice.elem;
  8533. context_name = str_lit("slice literal");
  8534. } else if (t->kind == Type_Array) {
  8535. elem_type = t->Array.elem;
  8536. context_name = str_lit("array literal");
  8537. if (!is_to_be_determined_array_count) {
  8538. max_type_count = t->Array.count;
  8539. }
  8540. } else if (t->kind == Type_Array) {
  8541. elem_type = t->Array.elem;
  8542. context_name = str_lit("array literal");
  8543. if (!is_to_be_determined_array_count) {
  8544. max_type_count = t->Array.count;
  8545. }
  8546. } else if (t->kind == Type_DynamicArray) {
  8547. elem_type = t->DynamicArray.elem;
  8548. context_name = str_lit("dynamic array literal");
  8549. is_constant = false;
  8550. } else if (t->kind == Type_SimdVector) {
  8551. elem_type = t->SimdVector.elem;
  8552. context_name = str_lit("simd vector literal");
  8553. max_type_count = t->SimdVector.count;
  8554. } else if (t->kind == Type_Matrix) {
  8555. elem_type = t->Matrix.elem;
  8556. context_name = str_lit("matrix literal");
  8557. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8558. } else {
  8559. GB_PANIC("unreachable");
  8560. }
  8561. i64 max = 0;
  8562. Type *bet = base_type(elem_type);
  8563. if (!elem_type_can_be_constant(bet)) {
  8564. is_constant = false;
  8565. }
  8566. if (bet == t_invalid) {
  8567. break;
  8568. }
  8569. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8570. RangeCache rc = range_cache_make(heap_allocator());
  8571. defer (range_cache_destroy(&rc));
  8572. for (Ast *elem : cl->elems) {
  8573. if (elem->kind != Ast_FieldValue) {
  8574. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8575. continue;
  8576. }
  8577. ast_node(fv, FieldValue, elem);
  8578. if (is_ast_range(fv->field)) {
  8579. Token op = fv->field->BinaryExpr.op;
  8580. Operand x = {};
  8581. Operand y = {};
  8582. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8583. if (!ok) {
  8584. continue;
  8585. }
  8586. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8587. error(x.expr, "Expected a constant integer as an array field");
  8588. continue;
  8589. }
  8590. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8591. error(y.expr, "Expected a constant integer as an array field");
  8592. continue;
  8593. }
  8594. i64 lo = exact_value_to_i64(x.value);
  8595. i64 hi = exact_value_to_i64(y.value);
  8596. i64 max_index = hi;
  8597. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8598. hi -= 1;
  8599. } else { // .. (inclusive)
  8600. max_index += 1;
  8601. }
  8602. bool new_range = range_cache_add_range(&rc, lo, hi);
  8603. if (!new_range) {
  8604. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8605. continue;
  8606. }
  8607. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8608. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8609. continue;
  8610. }
  8611. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8612. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8613. continue;
  8614. }
  8615. if (max < hi) {
  8616. max = max_index;
  8617. }
  8618. Operand operand = {};
  8619. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8620. check_assignment(c, &operand, elem_type, context_name);
  8621. is_constant = is_constant && operand.mode == Addressing_Constant;
  8622. } else {
  8623. Operand op_index = {};
  8624. check_expr(c, &op_index, fv->field);
  8625. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8626. error(elem, "Expected a constant integer as an array field");
  8627. continue;
  8628. }
  8629. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8630. i64 index = exact_value_to_i64(op_index.value);
  8631. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8632. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8633. continue;
  8634. }
  8635. bool new_index = range_cache_add_index(&rc, index);
  8636. if (!new_index) {
  8637. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8638. continue;
  8639. }
  8640. if (max < index+1) {
  8641. max = index+1;
  8642. }
  8643. Operand operand = {};
  8644. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8645. check_assignment(c, &operand, elem_type, context_name);
  8646. is_constant = is_constant && operand.mode == Addressing_Constant;
  8647. }
  8648. }
  8649. cl->max_count = max;
  8650. } else {
  8651. isize index = 0;
  8652. for (; index < cl->elems.count; index++) {
  8653. Ast *e = cl->elems[index];
  8654. if (e == nullptr) {
  8655. error(node, "Invalid literal element");
  8656. continue;
  8657. }
  8658. if (e->kind == Ast_FieldValue) {
  8659. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8660. continue;
  8661. }
  8662. if (0 <= max_type_count && max_type_count <= index) {
  8663. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8664. }
  8665. Operand operand = {};
  8666. check_expr_with_type_hint(c, &operand, e, elem_type);
  8667. check_assignment(c, &operand, elem_type, context_name);
  8668. is_constant = is_constant && operand.mode == Addressing_Constant;
  8669. }
  8670. if (max < index) {
  8671. max = index;
  8672. }
  8673. }
  8674. if (t->kind == Type_Array) {
  8675. if (is_to_be_determined_array_count) {
  8676. t->Array.count = max;
  8677. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8678. if (0 < max && max < t->Array.count) {
  8679. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8680. }
  8681. }
  8682. } else if (t->kind == Type_Struct) {
  8683. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8684. if (is_to_be_determined_array_count) {
  8685. t->Struct.soa_count = cast(i32)max;
  8686. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8687. if (0 < max && max < t->Struct.soa_count) {
  8688. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8689. }
  8690. }
  8691. }
  8692. if (t->kind == Type_SimdVector) {
  8693. if (!is_constant) {
  8694. // error(node, "Expected all constant elements for a simd vector");
  8695. }
  8696. }
  8697. if (t->kind == Type_DynamicArray) {
  8698. if (check_for_dynamic_literals(c, node, cl)) {
  8699. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8700. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8701. }
  8702. }
  8703. if (t->kind == Type_Matrix) {
  8704. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8705. if (0 < max && max < max_type_count) {
  8706. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8707. }
  8708. }
  8709. }
  8710. break;
  8711. }
  8712. case Type_EnumeratedArray:
  8713. {
  8714. Type *elem_type = t->EnumeratedArray.elem;
  8715. Type *index_type = t->EnumeratedArray.index;
  8716. String context_name = str_lit("enumerated array literal");
  8717. i64 max_type_count = t->EnumeratedArray.count;
  8718. gbString index_type_str = type_to_string(index_type);
  8719. defer (gb_string_free(index_type_str));
  8720. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8721. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8722. String total_lo_string = {};
  8723. String total_hi_string = {};
  8724. GB_ASSERT(is_type_enum(index_type));
  8725. {
  8726. Type *bt = base_type(index_type);
  8727. GB_ASSERT(bt->kind == Type_Enum);
  8728. for (Entity *f : bt->Enum.fields) {
  8729. if (f->kind != Entity_Constant) {
  8730. continue;
  8731. }
  8732. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8733. total_lo_string = f->token.string;
  8734. }
  8735. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8736. total_hi_string = f->token.string;
  8737. }
  8738. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8739. break;
  8740. }
  8741. }
  8742. }
  8743. i64 max = 0;
  8744. Type *bet = base_type(elem_type);
  8745. if (!elem_type_can_be_constant(bet)) {
  8746. is_constant = false;
  8747. }
  8748. if (bet == t_invalid) {
  8749. break;
  8750. }
  8751. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8752. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8753. defer (map_destroy(&seen));
  8754. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8755. RangeCache rc = range_cache_make(heap_allocator());
  8756. defer (range_cache_destroy(&rc));
  8757. for (Ast *elem : cl->elems) {
  8758. if (elem->kind != Ast_FieldValue) {
  8759. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8760. continue;
  8761. }
  8762. ast_node(fv, FieldValue, elem);
  8763. if (is_ast_range(fv->field)) {
  8764. Token op = fv->field->BinaryExpr.op;
  8765. Operand x = {};
  8766. Operand y = {};
  8767. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8768. if (!ok) {
  8769. continue;
  8770. }
  8771. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8772. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8773. continue;
  8774. }
  8775. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8776. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8777. continue;
  8778. }
  8779. i64 lo = exact_value_to_i64(x.value);
  8780. i64 hi = exact_value_to_i64(y.value);
  8781. i64 max_index = hi;
  8782. if (op.kind == Token_RangeHalf) {
  8783. hi -= 1;
  8784. }
  8785. bool new_range = range_cache_add_range(&rc, lo, hi);
  8786. if (!new_range) {
  8787. gbString lo_str = expr_to_string(x.expr);
  8788. gbString hi_str = expr_to_string(y.expr);
  8789. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8790. gb_string_free(hi_str);
  8791. gb_string_free(lo_str);
  8792. continue;
  8793. }
  8794. // NOTE(bill): These are sanity checks for invalid enum values
  8795. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8796. gbString lo_str = expr_to_string(x.expr);
  8797. 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));
  8798. gb_string_free(lo_str);
  8799. continue;
  8800. }
  8801. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8802. gbString hi_str = expr_to_string(y.expr);
  8803. 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));
  8804. gb_string_free(hi_str);
  8805. continue;
  8806. }
  8807. if (max < hi) {
  8808. max = max_index;
  8809. }
  8810. Operand operand = {};
  8811. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8812. check_assignment(c, &operand, elem_type, context_name);
  8813. is_constant = is_constant && operand.mode == Addressing_Constant;
  8814. TokenKind upper_op = Token_LtEq;
  8815. if (op.kind == Token_RangeHalf) {
  8816. upper_op = Token_Lt;
  8817. }
  8818. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8819. } else {
  8820. Operand op_index = {};
  8821. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8822. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8823. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8824. continue;
  8825. }
  8826. i64 index = exact_value_to_i64(op_index.value);
  8827. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8828. gbString idx_str = expr_to_string(op_index.expr);
  8829. 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));
  8830. gb_string_free(idx_str);
  8831. continue;
  8832. }
  8833. bool new_index = range_cache_add_index(&rc, index);
  8834. if (!new_index) {
  8835. gbString idx_str = expr_to_string(op_index.expr);
  8836. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8837. gb_string_free(idx_str);
  8838. continue;
  8839. }
  8840. if (max < index+1) {
  8841. max = index+1;
  8842. }
  8843. Operand operand = {};
  8844. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8845. check_assignment(c, &operand, elem_type, context_name);
  8846. is_constant = is_constant && operand.mode == Addressing_Constant;
  8847. add_to_seen_map(c, &seen, op_index);
  8848. }
  8849. }
  8850. cl->max_count = max;
  8851. } else {
  8852. isize index = 0;
  8853. for (; index < cl->elems.count; index++) {
  8854. Ast *e = cl->elems[index];
  8855. if (e == nullptr) {
  8856. error(node, "Invalid literal element");
  8857. continue;
  8858. }
  8859. if (e->kind == Ast_FieldValue) {
  8860. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8861. continue;
  8862. }
  8863. if (0 <= max_type_count && max_type_count <= index) {
  8864. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8865. }
  8866. Operand operand = {};
  8867. check_expr_with_type_hint(c, &operand, e, elem_type);
  8868. check_assignment(c, &operand, elem_type, context_name);
  8869. is_constant = is_constant && operand.mode == Addressing_Constant;
  8870. }
  8871. if (max < index) {
  8872. max = index;
  8873. }
  8874. }
  8875. bool was_error = false;
  8876. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8877. if (0 < max && max < t->EnumeratedArray.count) {
  8878. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8879. was_error = true;
  8880. } else {
  8881. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8882. was_error = true;
  8883. }
  8884. }
  8885. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8886. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8887. TEMPORARY_ALLOCATOR_GUARD();
  8888. Type *et = base_type(index_type);
  8889. GB_ASSERT(et->kind == Type_Enum);
  8890. auto fields = et->Enum.fields;
  8891. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8892. for (Entity *f : fields) {
  8893. if (f->kind != Entity_Constant) {
  8894. continue;
  8895. }
  8896. ExactValue v = f->Constant.value;
  8897. uintptr hash = hash_exact_value(v);
  8898. auto found = map_get(&seen, hash);
  8899. if (!found) {
  8900. array_add(&unhandled, f);
  8901. }
  8902. }
  8903. if (unhandled.count > 0) {
  8904. ERROR_BLOCK();
  8905. if (unhandled.count == 1) {
  8906. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8907. } else {
  8908. error(node, "Unhandled enumerated array cases:");
  8909. for_array(i, unhandled) {
  8910. Entity *f = unhandled[i];
  8911. error_line("\t%.*s\n", LIT(f->token.string));
  8912. }
  8913. }
  8914. if (!build_context.terse_errors) {
  8915. error_line("\n");
  8916. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8917. }
  8918. }
  8919. }
  8920. break;
  8921. }
  8922. case Type_Basic: {
  8923. if (!is_type_any(t)) {
  8924. if (cl->elems.count != 0) {
  8925. gbString s = type_to_string(t);
  8926. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8927. gb_string_free(s);
  8928. is_constant = false;
  8929. }
  8930. break;
  8931. }
  8932. if (cl->elems.count == 0) {
  8933. break; // NOTE(bill): No need to init
  8934. }
  8935. { // Checker values
  8936. Type *field_types[2] = {t_rawptr, t_typeid};
  8937. isize field_count = 2;
  8938. if (cl->elems[0]->kind == Ast_FieldValue) {
  8939. bool fields_visited[2] = {};
  8940. for_array(i, cl->elems) {
  8941. Ast *elem = cl->elems[i];
  8942. if (elem->kind != Ast_FieldValue) {
  8943. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8944. continue;
  8945. }
  8946. ast_node(fv, FieldValue, elem);
  8947. if (fv->field->kind != Ast_Ident) {
  8948. gbString expr_str = expr_to_string(fv->field);
  8949. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8950. gb_string_free(expr_str);
  8951. continue;
  8952. }
  8953. String name = fv->field->Ident.token.string;
  8954. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8955. if (sel.entity == nullptr) {
  8956. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8957. continue;
  8958. }
  8959. isize index = sel.index[0];
  8960. if (fields_visited[index]) {
  8961. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8962. continue;
  8963. }
  8964. fields_visited[index] = true;
  8965. check_expr(c, o, fv->value);
  8966. // NOTE(bill): 'any' literals can never be constant
  8967. is_constant = false;
  8968. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8969. }
  8970. } else {
  8971. for_array(index, cl->elems) {
  8972. Ast *elem = cl->elems[index];
  8973. if (elem->kind == Ast_FieldValue) {
  8974. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8975. continue;
  8976. }
  8977. check_expr(c, o, elem);
  8978. if (index >= field_count) {
  8979. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8980. break;
  8981. }
  8982. // NOTE(bill): 'any' literals can never be constant
  8983. is_constant = false;
  8984. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8985. }
  8986. if (cl->elems.count < field_count) {
  8987. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8988. }
  8989. }
  8990. }
  8991. break;
  8992. }
  8993. case Type_Map: {
  8994. if (cl->elems.count == 0) {
  8995. break;
  8996. }
  8997. is_constant = false;
  8998. { // Checker values
  8999. bool key_is_typeid = is_type_typeid(t->Map.key);
  9000. bool value_is_typeid = is_type_typeid(t->Map.value);
  9001. for (Ast *elem : cl->elems) {
  9002. if (elem->kind != Ast_FieldValue) {
  9003. error(elem, "Only 'field = value' elements are allowed in a map literal");
  9004. continue;
  9005. }
  9006. ast_node(fv, FieldValue, elem);
  9007. if (key_is_typeid) {
  9008. check_expr_or_type(c, o, fv->field, t->Map.key);
  9009. } else {
  9010. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  9011. }
  9012. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  9013. if (o->mode == Addressing_Invalid) {
  9014. continue;
  9015. }
  9016. if (value_is_typeid) {
  9017. check_expr_or_type(c, o, fv->value, t->Map.value);
  9018. } else {
  9019. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  9020. }
  9021. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  9022. }
  9023. }
  9024. if (check_for_dynamic_literals(c, node, cl)) {
  9025. add_map_reserve_dependencies(c);
  9026. add_map_set_dependencies(c);
  9027. }
  9028. break;
  9029. }
  9030. case Type_BitSet: {
  9031. if (cl->elems.count == 0) {
  9032. break; // NOTE(bill): No need to init
  9033. }
  9034. Type *et = base_type(t->BitSet.elem);
  9035. isize field_count = 0;
  9036. if (et != nullptr && et->kind == Type_Enum) {
  9037. field_count = et->Enum.fields.count;
  9038. }
  9039. if (is_type_array(bit_set_to_int(t))) {
  9040. is_constant = false;
  9041. }
  9042. for (Ast *elem : cl->elems) {
  9043. if (elem->kind == Ast_FieldValue) {
  9044. error(elem, "'field = value' in a bit_set literal is not allowed");
  9045. is_constant = false;
  9046. continue;
  9047. }
  9048. check_expr_with_type_hint(c, o, elem, et);
  9049. if (is_constant) {
  9050. is_constant = o->mode == Addressing_Constant;
  9051. }
  9052. if (elem->kind == Ast_BinaryExpr) {
  9053. switch (elem->BinaryExpr.op.kind) {
  9054. case Token_Or:
  9055. {
  9056. gbString x = expr_to_string(elem->BinaryExpr.left);
  9057. gbString y = expr_to_string(elem->BinaryExpr.right);
  9058. gbString e = expr_to_string(elem);
  9059. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9060. gb_string_free(e);
  9061. gb_string_free(y);
  9062. gb_string_free(x);
  9063. }
  9064. break;
  9065. }
  9066. }
  9067. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9068. if (o->mode == Addressing_Constant) {
  9069. i64 lower = t->BitSet.lower;
  9070. i64 upper = t->BitSet.upper;
  9071. i64 v = exact_value_to_i64(o->value);
  9072. if (lower <= v && v <= upper) {
  9073. // okay
  9074. } else {
  9075. gbString s = expr_to_string(o->expr);
  9076. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9077. gb_string_free(s);
  9078. continue;
  9079. }
  9080. }
  9081. }
  9082. break;
  9083. }
  9084. case Type_BitField: {
  9085. if (cl->elems.count == 0) {
  9086. break; // NOTE(bill): No need to init
  9087. }
  9088. is_constant = false;
  9089. if (cl->elems[0]->kind != Ast_FieldValue) {
  9090. gbString type_str = type_to_string(type);
  9091. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9092. gb_string_free(type_str);
  9093. } else {
  9094. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9095. }
  9096. break;
  9097. }
  9098. default: {
  9099. if (cl->elems.count == 0) {
  9100. break; // NOTE(bill): No need to init
  9101. }
  9102. gbString str = type_to_string(type);
  9103. error(node, "Invalid compound literal type '%s'", str);
  9104. gb_string_free(str);
  9105. return kind;
  9106. }
  9107. }
  9108. if (is_constant) {
  9109. o->mode = Addressing_Constant;
  9110. if (is_type_bit_set(type)) {
  9111. // NOTE(bill): Encode as an integer
  9112. Type *bt = base_type(type);
  9113. BigInt bits = {};
  9114. BigInt one = {};
  9115. big_int_from_u64(&one, 1);
  9116. for (Ast *e : cl->elems) {
  9117. GB_ASSERT(e->kind != Ast_FieldValue);
  9118. TypeAndValue tav = e->tav;
  9119. if (tav.mode != Addressing_Constant) {
  9120. continue;
  9121. }
  9122. if (tav.value.kind != ExactValue_Integer) {
  9123. continue;
  9124. }
  9125. i64 v = big_int_to_i64(&tav.value.value_integer);
  9126. i64 lower = bt->BitSet.lower;
  9127. u64 index = cast(u64)(v-lower);
  9128. BigInt bit = {};
  9129. big_int_from_u64(&bit, index);
  9130. big_int_shl(&bit, &one, &bit);
  9131. big_int_or(&bits, &bits, &bit);
  9132. }
  9133. o->value.kind = ExactValue_Integer;
  9134. o->value.value_integer = bits;
  9135. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9136. ExactValue value = exact_value_compound(node);
  9137. Type *bt = core_type(type);
  9138. if (bt->kind == Type_Basic) {
  9139. if (bt->Basic.flags & BasicFlag_Boolean) {
  9140. value = exact_value_bool(false);
  9141. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9142. value = exact_value_i64(0);
  9143. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9144. value = exact_value_i64(0);
  9145. } else if (bt->Basic.flags & BasicFlag_Float) {
  9146. value = exact_value_float(0);
  9147. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9148. value = exact_value_complex(0, 0);
  9149. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9150. value = exact_value_quaternion(0, 0, 0, 0);
  9151. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9152. value = exact_value_pointer(0);
  9153. } else if (bt->Basic.flags & BasicFlag_String) {
  9154. String empty_string = {};
  9155. value = exact_value_string(empty_string);
  9156. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9157. value = exact_value_i64(0);
  9158. }
  9159. }
  9160. o->value = value;
  9161. } else {
  9162. o->value = exact_value_compound(node);
  9163. }
  9164. } else {
  9165. o->mode = Addressing_Value;
  9166. }
  9167. o->type = type;
  9168. return kind;
  9169. }
  9170. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9171. ExprKind kind = Expr_Expr;
  9172. ast_node(ta, TypeAssertion, node);
  9173. check_expr(c, o, ta->expr);
  9174. node->viral_state_flags |= ta->expr->viral_state_flags;
  9175. if (o->mode == Addressing_Invalid) {
  9176. o->expr = node;
  9177. return kind;
  9178. }
  9179. if (o->mode == Addressing_Constant) {
  9180. gbString expr_str = expr_to_string(o->expr);
  9181. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9182. gb_string_free(expr_str);
  9183. o->mode = Addressing_Invalid;
  9184. o->expr = node;
  9185. return kind;
  9186. }
  9187. if (is_type_untyped(o->type)) {
  9188. gbString expr_str = expr_to_string(o->expr);
  9189. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9190. gb_string_free(expr_str);
  9191. o->mode = Addressing_Invalid;
  9192. o->expr = node;
  9193. return kind;
  9194. }
  9195. Type *src = type_deref(o->type);
  9196. Type *bsrc = base_type(src);
  9197. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9198. if (!is_type_union(src)) {
  9199. gbString str = type_to_string(o->type);
  9200. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9201. gb_string_free(str);
  9202. o->mode = Addressing_Invalid;
  9203. o->expr = node;
  9204. return kind;
  9205. }
  9206. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9207. bool allowed = false;
  9208. for (Type *vt : bsrc->Union.variants) {
  9209. if (are_types_identical(vt, type_hint)) {
  9210. allowed = true;
  9211. add_type_info_type(c, vt);
  9212. break;
  9213. }
  9214. }
  9215. if (allowed) {
  9216. add_type_info_type(c, o->type);
  9217. o->type = type_hint;
  9218. o->mode = Addressing_OptionalOk;
  9219. goto end;
  9220. }
  9221. }
  9222. if (bsrc->Union.variants.count != 1) {
  9223. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9224. o->mode = Addressing_Invalid;
  9225. o->expr = node;
  9226. return kind;
  9227. }
  9228. add_type_info_type(c, o->type);
  9229. add_type_info_type(c, bsrc->Union.variants[0]);
  9230. o->type = bsrc->Union.variants[0];
  9231. o->mode = Addressing_OptionalOk;
  9232. } else {
  9233. Type *t = check_type(c, ta->type);
  9234. Type *dst = t;
  9235. if (is_type_union(src)) {
  9236. bool ok = false;
  9237. for (Type *vt : bsrc->Union.variants) {
  9238. if (are_types_identical(vt, dst)) {
  9239. ok = true;
  9240. break;
  9241. }
  9242. }
  9243. if (!ok) {
  9244. gbString expr_str = expr_to_string(o->expr);
  9245. gbString dst_type_str = type_to_string(t);
  9246. defer (gb_string_free(expr_str));
  9247. defer (gb_string_free(dst_type_str));
  9248. if (bsrc->Union.variants.count == 0) {
  9249. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9250. } else {
  9251. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9252. }
  9253. o->mode = Addressing_Invalid;
  9254. o->expr = node;
  9255. return kind;
  9256. }
  9257. add_type_info_type(c, o->type);
  9258. add_type_info_type(c, t);
  9259. o->type = t;
  9260. o->mode = Addressing_OptionalOk;
  9261. } else if (is_type_any(src)) {
  9262. o->type = t;
  9263. o->mode = Addressing_OptionalOk;
  9264. add_type_info_type(c, o->type);
  9265. add_type_info_type(c, t);
  9266. } else {
  9267. gbString str = type_to_string(o->type);
  9268. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9269. gb_string_free(str);
  9270. o->mode = Addressing_Invalid;
  9271. o->expr = node;
  9272. return kind;
  9273. }
  9274. }
  9275. end:;
  9276. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9277. add_package_dependency(c, "runtime", "type_assertion_check");
  9278. add_package_dependency(c, "runtime", "type_assertion_check2");
  9279. }
  9280. return kind;
  9281. }
  9282. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9283. ast_node(se, SelectorCallExpr, node);
  9284. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9285. // COM APIs is a great example of where this kind of thing is extremely useful
  9286. // General idea:
  9287. //
  9288. // x->y(123) == x.y(x, 123)
  9289. //
  9290. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9291. // Just regenerating a new AST aids things
  9292. //
  9293. // TODO(bill): Is this a good hack or not?
  9294. //
  9295. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9296. if (se->modified_call) {
  9297. // Prevent double evaluation
  9298. o->expr = node;
  9299. o->type = node->tav.type;
  9300. o->value = node->tav.value;
  9301. o->mode = node->tav.mode;
  9302. return Expr_Expr;
  9303. }
  9304. bool allow_arrow_right_selector_expr;
  9305. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9306. c->allow_arrow_right_selector_expr = true;
  9307. Operand x = {};
  9308. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9309. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9310. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9311. o->mode = Addressing_Invalid;
  9312. o->type = t_invalid;
  9313. o->expr = node;
  9314. return kind;
  9315. }
  9316. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9317. gbString type_str = type_to_string(x.type);
  9318. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9319. gb_string_free(type_str);
  9320. o->mode = Addressing_Invalid;
  9321. o->type = t_invalid;
  9322. o->expr = node;
  9323. return Expr_Stmt;
  9324. }
  9325. ast_node(ce, CallExpr, se->call);
  9326. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9327. Ast *first_arg = x.expr->SelectorExpr.expr;
  9328. GB_ASSERT(first_arg != nullptr);
  9329. Entity *e = entity_of_node(se->expr);
  9330. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9331. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9332. }
  9333. if (e->kind != Entity_ProcGroup) {
  9334. Type *pt = base_type(x.type);
  9335. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9336. Type *first_type = nullptr;
  9337. String first_arg_name = {};
  9338. if (pt->Proc.param_count > 0) {
  9339. Entity *f = pt->Proc.params->Tuple.variables[0];
  9340. first_type = f->type;
  9341. first_arg_name = f->token.string;
  9342. }
  9343. if (first_arg_name.len == 0) {
  9344. first_arg_name = str_lit("_");
  9345. }
  9346. if (first_type == nullptr) {
  9347. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9348. o->mode = Addressing_Invalid;
  9349. o->type = t_invalid;
  9350. o->expr = node;
  9351. return Expr_Stmt;
  9352. }
  9353. Operand y = {};
  9354. y.mode = first_arg->tav.mode;
  9355. y.type = first_arg->tav.type;
  9356. y.value = first_arg->tav.value;
  9357. if (check_is_assignable_to(c, &y, first_type)) {
  9358. // Do nothing, it's valid
  9359. } else {
  9360. Operand z = y;
  9361. z.type = type_deref(y.type);
  9362. if (check_is_assignable_to(c, &z, first_type)) {
  9363. // NOTE(bill): AST GENERATION HACK!
  9364. Token op = {Token_Pointer};
  9365. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9366. } else if (y.mode == Addressing_Variable) {
  9367. Operand w = y;
  9368. w.type = alloc_type_pointer(y.type);
  9369. if (check_is_assignable_to(c, &w, first_type)) {
  9370. // NOTE(bill): AST GENERATION HACK!
  9371. Token op = {Token_And};
  9372. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9373. }
  9374. }
  9375. }
  9376. if (ce->args.count > 0) {
  9377. bool fail = false;
  9378. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9379. for (Ast *arg : ce->args) {
  9380. bool mix = false;
  9381. if (first_is_field_value) {
  9382. mix = arg->kind != Ast_FieldValue;
  9383. } else {
  9384. mix = arg->kind == Ast_FieldValue;
  9385. }
  9386. if (mix) {
  9387. fail = true;
  9388. break;
  9389. }
  9390. }
  9391. if (!fail && first_is_field_value) {
  9392. Token op = {Token_Eq};
  9393. AstFile *f = first_arg->file();
  9394. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9395. }
  9396. }
  9397. }
  9398. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9399. modified_args[0] = first_arg;
  9400. slice_copy(&modified_args, ce->args, 1);
  9401. ce->args = modified_args;
  9402. se->modified_call = true;
  9403. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9404. c->allow_arrow_right_selector_expr = true;
  9405. check_expr_base(c, o, se->call, type_hint);
  9406. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9407. o->expr = node;
  9408. return Expr_Expr;
  9409. }
  9410. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9411. ExprKind kind = Expr_Expr;
  9412. ast_node(ie, IndexExpr, node);
  9413. check_expr(c, o, ie->expr);
  9414. node->viral_state_flags |= ie->expr->viral_state_flags;
  9415. if (o->mode == Addressing_Invalid) {
  9416. o->expr = node;
  9417. return kind;
  9418. }
  9419. Type *t = base_type(type_deref(o->type));
  9420. bool is_ptr = is_type_pointer(o->type);
  9421. bool is_const = o->mode == Addressing_Constant;
  9422. if (is_type_map(t)) {
  9423. Operand key = {};
  9424. if (is_type_typeid(t->Map.key)) {
  9425. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9426. } else {
  9427. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9428. }
  9429. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9430. if (key.mode == Addressing_Invalid) {
  9431. o->mode = Addressing_Invalid;
  9432. o->expr = node;
  9433. return kind;
  9434. }
  9435. o->mode = Addressing_MapIndex;
  9436. o->type = t->Map.value;
  9437. o->expr = node;
  9438. add_map_get_dependencies(c);
  9439. add_map_set_dependencies(c);
  9440. return Expr_Expr;
  9441. }
  9442. i64 max_count = -1;
  9443. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9444. if (is_const) {
  9445. if (is_type_array(t)) {
  9446. // Okay
  9447. } else if (is_type_slice(t)) {
  9448. // Okay
  9449. } else if (is_type_enumerated_array(t)) {
  9450. // Okay
  9451. } else if (is_type_string(t)) {
  9452. // Okay
  9453. } else if (is_type_matrix(t)) {
  9454. // Okay
  9455. } else {
  9456. valid = false;
  9457. }
  9458. }
  9459. if (!valid) {
  9460. gbString str = expr_to_string(o->expr);
  9461. gbString type_str = type_to_string(o->type);
  9462. defer (gb_string_free(str));
  9463. defer (gb_string_free(type_str));
  9464. if (is_const) {
  9465. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9466. } else {
  9467. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9468. }
  9469. o->mode = Addressing_Invalid;
  9470. o->expr = node;
  9471. return kind;
  9472. }
  9473. if (ie->index == nullptr) {
  9474. gbString str = expr_to_string(o->expr);
  9475. error(o->expr, "Missing index for '%s'", str);
  9476. gb_string_free(str);
  9477. o->mode = Addressing_Invalid;
  9478. o->expr = node;
  9479. return kind;
  9480. }
  9481. Type *index_type_hint = nullptr;
  9482. if (is_type_enumerated_array(t)) {
  9483. Type *bt = base_type(t);
  9484. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9485. index_type_hint = bt->EnumeratedArray.index;
  9486. }
  9487. i64 index = 0;
  9488. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9489. if (is_const) {
  9490. if (index < 0) {
  9491. ERROR_BLOCK();
  9492. gbString str = expr_to_string(o->expr);
  9493. error(o->expr, "Cannot index a constant '%s'", str);
  9494. if (!build_context.terse_errors) {
  9495. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9496. }
  9497. gb_string_free(str);
  9498. o->mode = Addressing_Invalid;
  9499. o->expr = node;
  9500. return kind;
  9501. } else if (ok && !is_type_matrix(t)) {
  9502. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9503. ExactValue value = tav.value;
  9504. o->mode = Addressing_Constant;
  9505. bool success = false;
  9506. bool finish = false;
  9507. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9508. if (!success) {
  9509. ERROR_BLOCK();
  9510. gbString str = expr_to_string(o->expr);
  9511. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9512. if (!build_context.terse_errors) {
  9513. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9514. }
  9515. gb_string_free(str);
  9516. o->mode = Addressing_Invalid;
  9517. o->expr = node;
  9518. return kind;
  9519. }
  9520. }
  9521. }
  9522. if (type_hint != nullptr && is_type_matrix(t)) {
  9523. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9524. // if a type hint exists
  9525. }
  9526. return kind;
  9527. }
  9528. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9529. ExprKind kind = Expr_Stmt;
  9530. ast_node(se, SliceExpr, node);
  9531. check_expr(c, o, se->expr);
  9532. node->viral_state_flags |= se->expr->viral_state_flags;
  9533. if (o->mode == Addressing_Invalid) {
  9534. o->mode = Addressing_Invalid;
  9535. o->expr = node;
  9536. return kind;
  9537. }
  9538. bool valid = false;
  9539. i64 max_count = -1;
  9540. Type *t = base_type(type_deref(o->type));
  9541. switch (t->kind) {
  9542. case Type_Basic:
  9543. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9544. valid = true;
  9545. if (o->mode == Addressing_Constant) {
  9546. max_count = o->value.value_string.len;
  9547. }
  9548. o->type = type_deref(o->type);
  9549. }
  9550. break;
  9551. case Type_Array:
  9552. valid = true;
  9553. max_count = t->Array.count;
  9554. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9555. gbString str = expr_to_string(node);
  9556. error(node, "Cannot slice array '%s', value is not addressable", str);
  9557. gb_string_free(str);
  9558. o->mode = Addressing_Invalid;
  9559. o->expr = node;
  9560. return kind;
  9561. }
  9562. o->type = alloc_type_slice(t->Array.elem);
  9563. break;
  9564. case Type_MultiPointer:
  9565. valid = true;
  9566. o->type = type_deref(o->type);
  9567. break;
  9568. case Type_Slice:
  9569. valid = true;
  9570. o->type = type_deref(o->type);
  9571. break;
  9572. case Type_DynamicArray:
  9573. valid = true;
  9574. o->type = alloc_type_slice(t->DynamicArray.elem);
  9575. break;
  9576. case Type_Struct:
  9577. if (is_type_soa_struct(t)) {
  9578. valid = true;
  9579. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9580. max_count = t->Struct.soa_count;
  9581. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9582. gbString str = expr_to_string(node);
  9583. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9584. gb_string_free(str);
  9585. o->mode = Addressing_Invalid;
  9586. o->expr = node;
  9587. return kind;
  9588. }
  9589. }
  9590. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9591. }
  9592. break;
  9593. case Type_EnumeratedArray:
  9594. {
  9595. gbString str = expr_to_string(o->expr);
  9596. gbString type_str = type_to_string(o->type);
  9597. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9598. gb_string_free(type_str);
  9599. gb_string_free(str);
  9600. o->mode = Addressing_Invalid;
  9601. o->expr = node;
  9602. return kind;
  9603. }
  9604. break;
  9605. }
  9606. if (!valid) {
  9607. gbString str = expr_to_string(o->expr);
  9608. gbString type_str = type_to_string(o->type);
  9609. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9610. gb_string_free(type_str);
  9611. gb_string_free(str);
  9612. o->mode = Addressing_Invalid;
  9613. o->expr = node;
  9614. return kind;
  9615. }
  9616. if (se->low == nullptr && se->high != nullptr) {
  9617. // It is okay to continue as it will assume the 1st index is zero
  9618. }
  9619. i64 indices[2] = {};
  9620. Ast *nodes[2] = {se->low, se->high};
  9621. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9622. i64 index = max_count;
  9623. if (nodes[i] != nullptr) {
  9624. i64 capacity = -1;
  9625. if (max_count >= 0) {
  9626. capacity = max_count;
  9627. }
  9628. i64 j = 0;
  9629. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9630. index = j;
  9631. }
  9632. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9633. } else if (i == 0) {
  9634. index = 0;
  9635. }
  9636. indices[i] = index;
  9637. }
  9638. for (isize i = 0; i < gb_count_of(indices); i++) {
  9639. i64 a = indices[i];
  9640. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9641. i64 b = indices[j];
  9642. if (a > b && b >= 0) {
  9643. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9644. }
  9645. }
  9646. }
  9647. if (max_count < 0) {
  9648. if (o->mode == Addressing_Constant) {
  9649. gbString s = expr_to_string(se->expr);
  9650. error(se->expr, "Cannot slice constant value '%s'", s);
  9651. gb_string_free(s);
  9652. }
  9653. }
  9654. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9655. /*
  9656. x[:] -> [^]T
  9657. x[i:] -> [^]T
  9658. x[:n] -> []T
  9659. x[i:n] -> []T
  9660. */
  9661. o->type = alloc_type_slice(t->MultiPointer.elem);
  9662. }
  9663. o->mode = Addressing_Value;
  9664. if (is_type_string(t) && max_count >= 0) {
  9665. bool all_constant = true;
  9666. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9667. if (nodes[i] != nullptr) {
  9668. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9669. if (tav.mode != Addressing_Constant) {
  9670. all_constant = false;
  9671. break;
  9672. }
  9673. }
  9674. }
  9675. if (!all_constant) {
  9676. ERROR_BLOCK();
  9677. gbString str = expr_to_string(o->expr);
  9678. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9679. if (!build_context.terse_errors) {
  9680. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9681. }
  9682. gb_string_free(str);
  9683. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9684. o->expr = node;
  9685. return kind;
  9686. }
  9687. String s = {};
  9688. if (o->value.kind == ExactValue_String) {
  9689. s = o->value.value_string;
  9690. }
  9691. o->mode = Addressing_Constant;
  9692. o->type = t;
  9693. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9694. }
  9695. return kind;
  9696. }
  9697. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9698. u32 prev_state_flags = c->state_flags;
  9699. defer (c->state_flags = prev_state_flags);
  9700. if (node->state_flags != 0) {
  9701. u32 in = node->state_flags;
  9702. u32 out = c->state_flags;
  9703. if (in & StateFlag_no_bounds_check) {
  9704. out |= StateFlag_no_bounds_check;
  9705. out &= ~StateFlag_bounds_check;
  9706. } else if (in & StateFlag_bounds_check) {
  9707. out |= StateFlag_bounds_check;
  9708. out &= ~StateFlag_no_bounds_check;
  9709. }
  9710. if (in & StateFlag_no_type_assert) {
  9711. out |= StateFlag_no_type_assert;
  9712. out &= ~StateFlag_type_assert;
  9713. } else if (in & StateFlag_type_assert) {
  9714. out |= StateFlag_type_assert;
  9715. out &= ~StateFlag_no_type_assert;
  9716. }
  9717. c->state_flags = out;
  9718. }
  9719. ExprKind kind = Expr_Stmt;
  9720. o->mode = Addressing_Invalid;
  9721. o->type = t_invalid;
  9722. o->value = {ExactValue_Invalid};
  9723. switch (node->kind) {
  9724. default:
  9725. return kind;
  9726. case_ast_node(be, BadExpr, node)
  9727. return kind;
  9728. case_end;
  9729. case_ast_node(i, Implicit, node);
  9730. switch (i->kind) {
  9731. case Token_context:
  9732. {
  9733. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9734. error(node, "'context' is only allowed within procedures");
  9735. return kind;
  9736. }
  9737. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9738. c->scope->flags |= ScopeFlag_ContextDefined;
  9739. }
  9740. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9741. error(node, "'context' has not been defined within this scope");
  9742. // Continue with value
  9743. }
  9744. init_core_context(c->checker);
  9745. o->mode = Addressing_Context;
  9746. o->type = t_context;
  9747. }
  9748. break;
  9749. default:
  9750. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9751. return kind;
  9752. }
  9753. case_end;
  9754. case_ast_node(i, Ident, node);
  9755. check_ident(c, o, node, nullptr, type_hint, false);
  9756. case_end;
  9757. case_ast_node(u, Uninit, node);
  9758. o->mode = Addressing_Value;
  9759. o->type = t_untyped_uninit;
  9760. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  9761. case_end;
  9762. case_ast_node(bl, BasicLit, node);
  9763. Type *t = t_invalid;
  9764. switch (node->tav.value.kind) {
  9765. case ExactValue_String: t = t_untyped_string; break;
  9766. case ExactValue_Float: t = t_untyped_float; break;
  9767. case ExactValue_Complex: t = t_untyped_complex; break;
  9768. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9769. case ExactValue_Integer:
  9770. t = t_untyped_integer;
  9771. if (bl->token.kind == Token_Rune) {
  9772. t = t_untyped_rune;
  9773. }
  9774. break;
  9775. default:
  9776. GB_PANIC("Unhandled value type for basic literal");
  9777. break;
  9778. }
  9779. o->mode = Addressing_Constant;
  9780. o->type = t;
  9781. o->value = node->tav.value;
  9782. case_end;
  9783. case_ast_node(bd, BasicDirective, node);
  9784. kind = check_basic_directive_expr(c, o, node, type_hint);
  9785. case_end;
  9786. case_ast_node(pg, ProcGroup, node);
  9787. error(node, "Illegal use of a procedure group");
  9788. o->mode = Addressing_Invalid;
  9789. case_end;
  9790. case_ast_node(pl, ProcLit, node);
  9791. CheckerContext ctx = *c;
  9792. DeclInfo *decl = nullptr;
  9793. Type *type = alloc_type(Type_Proc);
  9794. check_open_scope(&ctx, pl->type);
  9795. {
  9796. decl = make_decl_info(ctx.scope, ctx.decl);
  9797. decl->proc_lit = node;
  9798. ctx.decl = decl;
  9799. defer (ctx.decl = ctx.decl->parent);
  9800. if (pl->tags != 0) {
  9801. error(node, "A procedure literal cannot have tags");
  9802. pl->tags = 0; // TODO(bill): Should I zero this?!
  9803. }
  9804. check_procedure_type(&ctx, type, pl->type);
  9805. if (!is_type_proc(type)) {
  9806. gbString str = expr_to_string(node);
  9807. error(node, "Invalid procedure literal '%s'", str);
  9808. gb_string_free(str);
  9809. check_close_scope(&ctx);
  9810. return kind;
  9811. }
  9812. if (pl->body == nullptr) {
  9813. error(node, "A procedure literal must have a body");
  9814. return kind;
  9815. }
  9816. pl->decl = decl;
  9817. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9818. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9819. array_add(&ctx.checker->nested_proc_lits, decl);
  9820. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9821. }
  9822. check_close_scope(&ctx);
  9823. o->mode = Addressing_Value;
  9824. o->type = type;
  9825. case_end;
  9826. case_ast_node(te, TernaryIfExpr, node);
  9827. kind = check_ternary_if_expr(c, o, node, type_hint);
  9828. case_end;
  9829. case_ast_node(te, TernaryWhenExpr, node);
  9830. kind = check_ternary_when_expr(c, o, node, type_hint);
  9831. case_end;
  9832. case_ast_node(oe, OrElseExpr, node);
  9833. return check_or_else_expr(c, o, node, type_hint);
  9834. case_end;
  9835. case_ast_node(re, OrReturnExpr, node);
  9836. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9837. return check_or_return_expr(c, o, node, type_hint);
  9838. case_end;
  9839. case_ast_node(re, OrBranchExpr, node);
  9840. return check_or_branch_expr(c, o, node, type_hint);
  9841. case_end;
  9842. case_ast_node(cl, CompoundLit, node);
  9843. kind = check_compound_literal(c, o, node, type_hint);
  9844. case_end;
  9845. case_ast_node(pe, ParenExpr, node);
  9846. kind = check_expr_base(c, o, pe->expr, type_hint);
  9847. node->viral_state_flags |= pe->expr->viral_state_flags;
  9848. o->expr = node;
  9849. case_end;
  9850. case_ast_node(te, TagExpr, node);
  9851. String name = te->name.string;
  9852. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9853. if (te->expr) {
  9854. kind = check_expr_base(c, o, te->expr, type_hint);
  9855. node->viral_state_flags |= te->expr->viral_state_flags;
  9856. }
  9857. o->expr = node;
  9858. case_end;
  9859. case_ast_node(ta, TypeAssertion, node);
  9860. kind = check_type_assertion(c, o, node, type_hint);
  9861. case_end;
  9862. case_ast_node(tc, TypeCast, node);
  9863. check_expr_or_type(c, o, tc->type);
  9864. if (o->mode != Addressing_Type) {
  9865. gbString str = expr_to_string(tc->type);
  9866. error(tc->type, "Expected a type, got %s", str);
  9867. gb_string_free(str);
  9868. o->mode = Addressing_Invalid;
  9869. }
  9870. if (o->mode == Addressing_Invalid) {
  9871. o->expr = node;
  9872. return kind;
  9873. }
  9874. Type *type = o->type;
  9875. check_expr_base(c, o, tc->expr, type);
  9876. node->viral_state_flags |= tc->expr->viral_state_flags;
  9877. if (o->mode != Addressing_Invalid) {
  9878. switch (tc->token.kind) {
  9879. case Token_transmute:
  9880. check_transmute(c, node, o, type, true);
  9881. break;
  9882. case Token_cast:
  9883. check_cast(c, o, type, true);
  9884. break;
  9885. default:
  9886. error(node, "Invalid AST: Invalid casting expression");
  9887. o->mode = Addressing_Invalid;
  9888. break;
  9889. }
  9890. }
  9891. return Expr_Expr;
  9892. case_end;
  9893. case_ast_node(ac, AutoCast, node);
  9894. check_expr_base(c, o, ac->expr, type_hint);
  9895. node->viral_state_flags |= ac->expr->viral_state_flags;
  9896. if (o->mode == Addressing_Invalid) {
  9897. o->expr = node;
  9898. return kind;
  9899. }
  9900. if (type_hint) {
  9901. check_cast(c, o, type_hint);
  9902. }
  9903. o->expr = node;
  9904. return Expr_Expr;
  9905. case_end;
  9906. case_ast_node(ue, UnaryExpr, node);
  9907. Type *th = type_hint;
  9908. if (ue->op.kind == Token_And) {
  9909. th = type_deref(th);
  9910. }
  9911. check_expr_base(c, o, ue->expr, th);
  9912. node->viral_state_flags |= ue->expr->viral_state_flags;
  9913. if (o->mode != Addressing_Invalid) {
  9914. check_unary_expr(c, o, ue->op, node);
  9915. }
  9916. o->expr = node;
  9917. return Expr_Expr;
  9918. case_end;
  9919. case_ast_node(be, BinaryExpr, node);
  9920. check_binary_expr(c, o, node, type_hint, true);
  9921. if (o->mode == Addressing_Invalid) {
  9922. o->expr = node;
  9923. return kind;
  9924. }
  9925. case_end;
  9926. case_ast_node(se, SelectorExpr, node);
  9927. check_selector(c, o, node, type_hint);
  9928. node->viral_state_flags |= se->expr->viral_state_flags;
  9929. case_end;
  9930. case_ast_node(se, SelectorCallExpr, node);
  9931. return check_selector_call_expr(c, o, node, type_hint);
  9932. case_end;
  9933. case_ast_node(ise, ImplicitSelectorExpr, node);
  9934. return check_implicit_selector_expr(c, o, node, type_hint);
  9935. case_end;
  9936. case_ast_node(ie, IndexExpr, node);
  9937. kind = check_index_expr(c, o, node, type_hint);
  9938. case_end;
  9939. case_ast_node(se, SliceExpr, node);
  9940. kind = check_slice_expr(c, o, node, type_hint);
  9941. case_end;
  9942. case_ast_node(mie, MatrixIndexExpr, node);
  9943. check_matrix_index_expr(c, o, node, type_hint);
  9944. o->expr = node;
  9945. return Expr_Expr;
  9946. case_end;
  9947. case_ast_node(ce, CallExpr, node);
  9948. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9949. case_end;
  9950. case_ast_node(de, DerefExpr, node);
  9951. check_expr_or_type(c, o, de->expr);
  9952. node->viral_state_flags |= de->expr->viral_state_flags;
  9953. if (o->mode == Addressing_Invalid) {
  9954. o->mode = Addressing_Invalid;
  9955. o->expr = node;
  9956. return kind;
  9957. } else if (o->mode == Addressing_Type) {
  9958. gbString str = expr_to_string(o->expr);
  9959. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  9960. o->mode = Addressing_Invalid;
  9961. o->expr = node;
  9962. return kind;
  9963. } else {
  9964. Type *t = base_type(o->type);
  9965. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9966. o->mode = Addressing_Variable;
  9967. o->type = t->Pointer.elem;
  9968. } else if (t->kind == Type_SoaPointer) {
  9969. o->mode = Addressing_SoaVariable;
  9970. o->type = type_deref(t);
  9971. } else {
  9972. gbString str = expr_to_string(o->expr);
  9973. gbString typ = type_to_string(o->type);
  9974. ERROR_BLOCK();
  9975. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9976. if (o->type && is_type_multi_pointer(o->type)) {
  9977. if (!build_context.terse_errors) {
  9978. error_line("\tDid you mean '%s[0]'?\n", str);
  9979. }
  9980. }
  9981. gb_string_free(typ);
  9982. gb_string_free(str);
  9983. o->mode = Addressing_Invalid;
  9984. o->expr = node;
  9985. return kind;
  9986. }
  9987. }
  9988. case_end;
  9989. case_ast_node(ia, InlineAsmExpr, node);
  9990. if (c->curr_proc_decl == nullptr) {
  9991. error(node, "Inline asm expressions are only allowed within a procedure body");
  9992. }
  9993. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9994. Type *return_type = nullptr;
  9995. for_array(i, ia->param_types) {
  9996. param_types[i] = check_type(c, ia->param_types[i]);
  9997. }
  9998. if (ia->return_type != nullptr) {
  9999. return_type = check_type(c, ia->return_type);
  10000. }
  10001. Operand x = {};
  10002. check_expr(c, &x, ia->asm_string);
  10003. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10004. error(x.expr, "Expected a constant string for the inline asm main parameter");
  10005. }
  10006. check_expr(c, &x, ia->constraints_string);
  10007. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10008. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  10009. }
  10010. Scope *scope = create_scope(c->info, c->scope);
  10011. scope->flags |= ScopeFlag_Proc;
  10012. Type *params = alloc_type_tuple();
  10013. Type *results = alloc_type_tuple();
  10014. if (param_types.count != 0) {
  10015. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  10016. for_array(i, param_types) {
  10017. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  10018. }
  10019. }
  10020. if (return_type != nullptr) {
  10021. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  10022. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  10023. }
  10024. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  10025. o->type = pt;
  10026. o->mode = Addressing_Value;
  10027. o->expr = node;
  10028. return Expr_Expr;
  10029. case_end;
  10030. case Ast_DistinctType:
  10031. case Ast_TypeidType:
  10032. case Ast_PolyType:
  10033. case Ast_ProcType:
  10034. case Ast_PointerType:
  10035. case Ast_MultiPointerType:
  10036. case Ast_ArrayType:
  10037. case Ast_DynamicArrayType:
  10038. case Ast_StructType:
  10039. case Ast_UnionType:
  10040. case Ast_EnumType:
  10041. case Ast_MapType:
  10042. case Ast_BitSetType:
  10043. case Ast_MatrixType:
  10044. case Ast_RelativeType:
  10045. o->mode = Addressing_Type;
  10046. o->type = check_type(c, node);
  10047. break;
  10048. }
  10049. kind = Expr_Expr;
  10050. o->expr = node;
  10051. return kind;
  10052. }
  10053. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10054. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10055. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10056. o->type = t_invalid;
  10057. gbString xs = expr_to_string(o->expr);
  10058. if (o->mode == Addressing_Type) {
  10059. error(o->expr, "Invalid type usage '%s'", xs);
  10060. } else {
  10061. error(o->expr, "Invalid expression '%s'", xs);
  10062. }
  10063. gb_string_free(xs);
  10064. }
  10065. if (o->type != nullptr && is_type_untyped(o->type)) {
  10066. add_untyped(c, node, o->mode, o->type, o->value);
  10067. }
  10068. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10069. add_type_and_value(c, node, o->mode, o->type, o->value);
  10070. return kind;
  10071. }
  10072. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10073. check_expr_base(c, o, e, nullptr);
  10074. switch (o->mode) {
  10075. default:
  10076. return; // NOTE(bill): Valid
  10077. case Addressing_NoValue:
  10078. error_operand_no_value(o);
  10079. break;
  10080. }
  10081. o->mode = Addressing_Invalid;
  10082. }
  10083. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10084. check_expr_base(c, o, e, nullptr);
  10085. switch (o->mode) {
  10086. default:
  10087. return; // NOTE(bill): Valid
  10088. case Addressing_NoValue:
  10089. error_operand_no_value(o);
  10090. break;
  10091. case Addressing_Type:
  10092. error_operand_not_expression(o);
  10093. break;
  10094. }
  10095. o->mode = Addressing_Invalid;
  10096. }
  10097. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10098. check_expr_base(c, o, e, type_hint);
  10099. switch (o->mode) {
  10100. default:
  10101. return; // NOTE(bill): Valid
  10102. case Addressing_NoValue:
  10103. error_operand_no_value(o);
  10104. break;
  10105. case Addressing_Type:
  10106. error_operand_not_expression(o);
  10107. break;
  10108. }
  10109. o->mode = Addressing_Invalid;
  10110. }
  10111. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10112. if (o->mode == Addressing_Value) {
  10113. // NOTE(bill): Tuples are not first class thus never named
  10114. if (o->type->kind == Type_Tuple) {
  10115. isize count = o->type->Tuple.variables.count;
  10116. error(o->expr,
  10117. "%td-valued expression found where single value expected", count);
  10118. o->mode = Addressing_Invalid;
  10119. GB_ASSERT(count != 1);
  10120. }
  10121. }
  10122. }
  10123. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10124. check_multi_expr(c, o, e);
  10125. check_not_tuple(c, o);
  10126. }
  10127. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10128. check_expr_base(c, o, e, type_hint);
  10129. check_not_tuple(c, o);
  10130. error_operand_no_value(o);
  10131. }
  10132. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10133. switch (v.kind) {
  10134. case ExactValue_Invalid:
  10135. return true;
  10136. case ExactValue_Bool:
  10137. return !v.value_bool;
  10138. case ExactValue_String:
  10139. return v.value_string.len == 0;
  10140. case ExactValue_Integer:
  10141. return big_int_is_zero(&v.value_integer);
  10142. case ExactValue_Float:
  10143. return v.value_float == 0.0;
  10144. case ExactValue_Complex:
  10145. if (v.value_complex) {
  10146. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10147. }
  10148. return true;
  10149. case ExactValue_Quaternion:
  10150. if (v.value_quaternion) {
  10151. return v.value_quaternion->real == 0.0 &&
  10152. v.value_quaternion->imag == 0.0 &&
  10153. v.value_quaternion->jmag == 0.0 &&
  10154. v.value_quaternion->kmag == 0.0;
  10155. }
  10156. return true;
  10157. case ExactValue_Pointer:
  10158. return v.value_pointer == 0;
  10159. case ExactValue_Compound:
  10160. if (v.value_compound == nullptr) {
  10161. return true;
  10162. } else {
  10163. ast_node(cl, CompoundLit, v.value_compound);
  10164. if (cl->elems.count == 0) {
  10165. return true;
  10166. } else {
  10167. for (Ast *elem : cl->elems) {
  10168. if (elem->tav.mode != Addressing_Constant) {
  10169. return false;
  10170. }
  10171. if (!is_exact_value_zero(elem->tav.value)) {
  10172. return false;
  10173. }
  10174. }
  10175. return true;
  10176. }
  10177. }
  10178. case ExactValue_Procedure:
  10179. return v.value_procedure == nullptr;
  10180. case ExactValue_Typeid:
  10181. return v.value_typeid == nullptr;
  10182. }
  10183. return true;
  10184. }
  10185. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10186. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10187. for_array(i, params) {
  10188. if (i > 0) {
  10189. str = gb_string_appendc(str, ", ");
  10190. }
  10191. str = write_expr_to_string(str, params[i], false);
  10192. }
  10193. return str;
  10194. }
  10195. gb_internal gbString string_append_string(gbString str, String string) {
  10196. if (string.len > 0) {
  10197. return gb_string_append_length(str, &string[0], string.len);
  10198. }
  10199. return str;
  10200. }
  10201. gb_internal gbString string_append_token(gbString str, Token token) {
  10202. str = string_append_string(str, token.string);
  10203. return str;
  10204. }
  10205. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10206. if (node == nullptr)
  10207. return str;
  10208. if (is_ast_stmt(node)) {
  10209. GB_ASSERT("stmt passed to write_expr_to_string");
  10210. }
  10211. switch (node->kind) {
  10212. default:
  10213. str = gb_string_appendc(str, "(BadExpr)");
  10214. break;
  10215. case_ast_node(i, Ident, node);
  10216. str = string_append_token(str, i->token);
  10217. case_end;
  10218. case_ast_node(i, Implicit, node);
  10219. str = string_append_token(str, *i);
  10220. case_end;
  10221. case_ast_node(bl, BasicLit, node);
  10222. str = string_append_token(str, bl->token);
  10223. case_end;
  10224. case_ast_node(bd, BasicDirective, node);
  10225. str = gb_string_append_rune(str, '#');
  10226. str = string_append_string(str, bd->name.string);
  10227. case_end;
  10228. case_ast_node(ud, Uninit, node);
  10229. str = gb_string_appendc(str, "---");
  10230. case_end;
  10231. case_ast_node(pg, ProcGroup, node);
  10232. str = gb_string_appendc(str, "proc{");
  10233. for_array(i, pg->args) {
  10234. if (i > 0) str = gb_string_appendc(str, ", ");
  10235. str = write_expr_to_string(str, pg->args[i], shorthand);
  10236. }
  10237. str = gb_string_append_rune(str, '}');
  10238. case_end;
  10239. case_ast_node(pl, ProcLit, node);
  10240. str = write_expr_to_string(str, pl->type, shorthand);
  10241. if (pl->body) {
  10242. str = gb_string_appendc(str, " {...}");
  10243. } else {
  10244. str = gb_string_appendc(str, " ---");
  10245. }
  10246. case_end;
  10247. case_ast_node(cl, CompoundLit, node);
  10248. str = write_expr_to_string(str, cl->type, shorthand);
  10249. str = gb_string_append_rune(str, '{');
  10250. if (shorthand) {
  10251. str = gb_string_appendc(str, "...");
  10252. } else {
  10253. for_array(i, cl->elems) {
  10254. if (i > 0) str = gb_string_appendc(str, ", ");
  10255. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10256. }
  10257. }
  10258. str = gb_string_append_rune(str, '}');
  10259. case_end;
  10260. case_ast_node(te, TagExpr, node);
  10261. str = gb_string_append_rune(str, '#');
  10262. str = string_append_token(str, te->name);
  10263. str = write_expr_to_string(str, te->expr, shorthand);
  10264. case_end;
  10265. case_ast_node(ue, UnaryExpr, node);
  10266. str = string_append_token(str, ue->op);
  10267. str = write_expr_to_string(str, ue->expr, shorthand);
  10268. case_end;
  10269. case_ast_node(de, DerefExpr, node);
  10270. str = write_expr_to_string(str, de->expr, shorthand);
  10271. str = gb_string_append_rune(str, '^');
  10272. case_end;
  10273. case_ast_node(be, BinaryExpr, node);
  10274. str = write_expr_to_string(str, be->left, shorthand);
  10275. str = gb_string_append_rune(str, ' ');
  10276. str = string_append_token(str, be->op);
  10277. str = gb_string_append_rune(str, ' ');
  10278. str = write_expr_to_string(str, be->right, shorthand);
  10279. case_end;
  10280. case_ast_node(te, TernaryIfExpr, node);
  10281. TokenPos x = ast_token(te->x).pos;
  10282. TokenPos cond = ast_token(te->cond).pos;
  10283. if (x < cond) {
  10284. str = write_expr_to_string(str, te->x, shorthand);
  10285. str = gb_string_appendc(str, " if ");
  10286. str = write_expr_to_string(str, te->cond, shorthand);
  10287. str = gb_string_appendc(str, " else ");
  10288. str = write_expr_to_string(str, te->y, shorthand);
  10289. } else {
  10290. str = write_expr_to_string(str, te->cond, shorthand);
  10291. str = gb_string_appendc(str, " ? ");
  10292. str = write_expr_to_string(str, te->x, shorthand);
  10293. str = gb_string_appendc(str, " : ");
  10294. str = write_expr_to_string(str, te->y, shorthand);
  10295. }
  10296. case_end;
  10297. case_ast_node(te, TernaryWhenExpr, node);
  10298. str = write_expr_to_string(str, te->x, shorthand);
  10299. str = gb_string_appendc(str, " when ");
  10300. str = write_expr_to_string(str, te->cond, shorthand);
  10301. str = gb_string_appendc(str, " else ");
  10302. str = write_expr_to_string(str, te->y, shorthand);
  10303. case_end;
  10304. case_ast_node(oe, OrElseExpr, node);
  10305. str = write_expr_to_string(str, oe->x, shorthand);
  10306. str = gb_string_appendc(str, " or_else ");
  10307. str = write_expr_to_string(str, oe->y, shorthand);
  10308. case_end;
  10309. case_ast_node(oe, OrReturnExpr, node);
  10310. str = write_expr_to_string(str, oe->expr, shorthand);
  10311. str = gb_string_appendc(str, " or_return");
  10312. case_end;
  10313. case_ast_node(oe, OrBranchExpr, node);
  10314. str = write_expr_to_string(str, oe->expr, shorthand);
  10315. str = gb_string_append_rune(str, ' ');
  10316. str = string_append_token(str, oe->token);
  10317. if (oe->label) {
  10318. str = gb_string_append_rune(str, ' ');
  10319. str = write_expr_to_string(str, oe->label, shorthand);
  10320. }
  10321. case_end;
  10322. case_ast_node(pe, ParenExpr, node);
  10323. str = gb_string_append_rune(str, '(');
  10324. str = write_expr_to_string(str, pe->expr, shorthand);
  10325. str = gb_string_append_rune(str, ')');
  10326. case_end;
  10327. case_ast_node(se, SelectorExpr, node);
  10328. str = write_expr_to_string(str, se->expr, shorthand);
  10329. str = string_append_token(str, se->token);
  10330. str = write_expr_to_string(str, se->selector, shorthand);
  10331. case_end;
  10332. case_ast_node(se, ImplicitSelectorExpr, node);
  10333. str = gb_string_append_rune(str, '.');
  10334. str = write_expr_to_string(str, se->selector, shorthand);
  10335. case_end;
  10336. case_ast_node(se, SelectorCallExpr, node);
  10337. str = write_expr_to_string(str, se->expr, shorthand);
  10338. str = gb_string_appendc(str, "(");
  10339. ast_node(ce, CallExpr, se->call);
  10340. isize start = se->modified_call ? 1 : 0;
  10341. for (isize i = start; i < ce->args.count; i++) {
  10342. Ast *arg = ce->args[i];
  10343. if (i > start) {
  10344. str = gb_string_appendc(str, ", ");
  10345. }
  10346. str = write_expr_to_string(str, arg, shorthand);
  10347. }
  10348. str = gb_string_appendc(str, ")");
  10349. case_end;
  10350. case_ast_node(ta, TypeAssertion, node);
  10351. str = write_expr_to_string(str, ta->expr, shorthand);
  10352. if (ta->type != nullptr &&
  10353. ta->type->kind == Ast_UnaryExpr &&
  10354. ta->type->UnaryExpr.op.kind == Token_Question) {
  10355. str = gb_string_appendc(str, ".?");
  10356. } else {
  10357. str = gb_string_appendc(str, ".(");
  10358. str = write_expr_to_string(str, ta->type, shorthand);
  10359. str = gb_string_append_rune(str, ')');
  10360. }
  10361. case_end;
  10362. case_ast_node(tc, TypeCast, node);
  10363. str = string_append_token(str, tc->token);
  10364. str = gb_string_append_rune(str, '(');
  10365. str = write_expr_to_string(str, tc->type, shorthand);
  10366. str = gb_string_append_rune(str, ')');
  10367. str = write_expr_to_string(str, tc->expr, shorthand);
  10368. case_end;
  10369. case_ast_node(ac, AutoCast, node);
  10370. str = string_append_token(str, ac->token);
  10371. str = gb_string_append_rune(str, ' ');
  10372. str = write_expr_to_string(str, ac->expr, shorthand);
  10373. case_end;
  10374. case_ast_node(ie, IndexExpr, node);
  10375. str = write_expr_to_string(str, ie->expr, shorthand);
  10376. str = gb_string_append_rune(str, '[');
  10377. str = write_expr_to_string(str, ie->index, shorthand);
  10378. str = gb_string_append_rune(str, ']');
  10379. case_end;
  10380. case_ast_node(se, SliceExpr, node);
  10381. str = write_expr_to_string(str, se->expr, shorthand);
  10382. str = gb_string_append_rune(str, '[');
  10383. str = write_expr_to_string(str, se->low, shorthand);
  10384. str = string_append_token(str, se->interval);
  10385. str = write_expr_to_string(str, se->high, shorthand);
  10386. str = gb_string_append_rune(str, ']');
  10387. case_end;
  10388. case_ast_node(mie, MatrixIndexExpr, node);
  10389. str = write_expr_to_string(str, mie->expr, shorthand);
  10390. str = gb_string_append_rune(str, '[');
  10391. str = write_expr_to_string(str, mie->row_index, shorthand);
  10392. str = gb_string_appendc(str, ", ");
  10393. str = write_expr_to_string(str, mie->column_index, shorthand);
  10394. str = gb_string_append_rune(str, ']');
  10395. case_end;
  10396. case_ast_node(e, Ellipsis, node);
  10397. str = gb_string_appendc(str, "..");
  10398. str = write_expr_to_string(str, e->expr, shorthand);
  10399. case_end;
  10400. case_ast_node(fv, FieldValue, node);
  10401. str = write_expr_to_string(str, fv->field, shorthand);
  10402. str = gb_string_appendc(str, " = ");
  10403. str = write_expr_to_string(str, fv->value, shorthand);
  10404. case_end;
  10405. case_ast_node(fv, EnumFieldValue, node);
  10406. str = write_expr_to_string(str, fv->name, shorthand);
  10407. if (fv->value) {
  10408. str = gb_string_appendc(str, " = ");
  10409. str = write_expr_to_string(str, fv->value, shorthand);
  10410. }
  10411. case_end;
  10412. case_ast_node(ht, HelperType, node);
  10413. str = gb_string_appendc(str, "#type ");
  10414. str = write_expr_to_string(str, ht->type, shorthand);
  10415. case_end;
  10416. case_ast_node(ht, DistinctType, node);
  10417. str = gb_string_appendc(str, "distinct ");
  10418. str = write_expr_to_string(str, ht->type, shorthand);
  10419. case_end;
  10420. case_ast_node(pt, PolyType, node);
  10421. str = gb_string_append_rune(str, '$');
  10422. str = write_expr_to_string(str, pt->type, shorthand);
  10423. if (pt->specialization != nullptr) {
  10424. str = gb_string_append_rune(str, '/');
  10425. str = write_expr_to_string(str, pt->specialization, shorthand);
  10426. }
  10427. case_end;
  10428. case_ast_node(pt, PointerType, node);
  10429. if (pt->tag) {
  10430. str = write_expr_to_string(str, pt->tag, false);
  10431. }
  10432. str = gb_string_append_rune(str, '^');
  10433. str = write_expr_to_string(str, pt->type, shorthand);
  10434. case_end;
  10435. case_ast_node(pt, MultiPointerType, node);
  10436. str = gb_string_appendc(str, "[^]");
  10437. str = write_expr_to_string(str, pt->type, shorthand);
  10438. case_end;
  10439. case_ast_node(at, ArrayType, node);
  10440. if (at->tag) {
  10441. str = write_expr_to_string(str, at->tag, false);
  10442. }
  10443. str = gb_string_append_rune(str, '[');
  10444. if (at->count != nullptr &&
  10445. at->count->kind == Ast_UnaryExpr &&
  10446. at->count->UnaryExpr.op.kind == Token_Question) {
  10447. str = gb_string_appendc(str, "?");
  10448. } else {
  10449. str = write_expr_to_string(str, at->count, shorthand);
  10450. }
  10451. str = gb_string_append_rune(str, ']');
  10452. str = write_expr_to_string(str, at->elem, shorthand);
  10453. case_end;
  10454. case_ast_node(at, DynamicArrayType, node);
  10455. if (at->tag) {
  10456. str = write_expr_to_string(str, at->tag, false);
  10457. }
  10458. str = gb_string_appendc(str, "[dynamic]");
  10459. str = write_expr_to_string(str, at->elem, shorthand);
  10460. case_end;
  10461. case_ast_node(bs, BitSetType, node);
  10462. str = gb_string_appendc(str, "bit_set[");
  10463. str = write_expr_to_string(str, bs->elem, shorthand);
  10464. str = gb_string_appendc(str, "]");
  10465. case_end;
  10466. case_ast_node(mt, MapType, node);
  10467. str = gb_string_appendc(str, "map[");
  10468. str = write_expr_to_string(str, mt->key, shorthand);
  10469. str = gb_string_append_rune(str, ']');
  10470. str = write_expr_to_string(str, mt->value, shorthand);
  10471. case_end;
  10472. case_ast_node(mt, MatrixType, node);
  10473. str = gb_string_appendc(str, "matrix[");
  10474. str = write_expr_to_string(str, mt->row_count, shorthand);
  10475. str = gb_string_appendc(str, ", ");
  10476. str = write_expr_to_string(str, mt->column_count, shorthand);
  10477. str = gb_string_append_rune(str, ']');
  10478. str = write_expr_to_string(str, mt->elem, shorthand);
  10479. case_end;
  10480. case_ast_node(f, Field, node);
  10481. if (f->flags&FieldFlag_using) {
  10482. str = gb_string_appendc(str, "using ");
  10483. }
  10484. if (f->flags&FieldFlag_no_alias) {
  10485. str = gb_string_appendc(str, "#no_alias ");
  10486. }
  10487. if (f->flags&FieldFlag_c_vararg) {
  10488. str = gb_string_appendc(str, "#c_vararg ");
  10489. }
  10490. if (f->flags&FieldFlag_any_int) {
  10491. str = gb_string_appendc(str, "#any_int ");
  10492. }
  10493. if (f->flags&FieldFlag_no_broadcast) {
  10494. str = gb_string_appendc(str, "#no_broadcast ");
  10495. }
  10496. if (f->flags&FieldFlag_const) {
  10497. str = gb_string_appendc(str, "#const ");
  10498. }
  10499. if (f->flags&FieldFlag_subtype) {
  10500. str = gb_string_appendc(str, "#subtype ");
  10501. }
  10502. for_array(i, f->names) {
  10503. Ast *name = f->names[i];
  10504. if (i > 0) str = gb_string_appendc(str, ", ");
  10505. str = write_expr_to_string(str, name, shorthand);
  10506. }
  10507. if (f->names.count > 0) {
  10508. if (f->type == nullptr && f->default_value != nullptr) {
  10509. str = gb_string_append_rune(str, ' ');
  10510. }
  10511. str = gb_string_appendc(str, ":");
  10512. }
  10513. if (f->type != nullptr) {
  10514. str = gb_string_append_rune(str, ' ');
  10515. str = write_expr_to_string(str, f->type, shorthand);
  10516. }
  10517. if (f->default_value != nullptr) {
  10518. if (f->type != nullptr) {
  10519. str = gb_string_append_rune(str, ' ');
  10520. }
  10521. str = gb_string_appendc(str, "= ");
  10522. str = write_expr_to_string(str, f->default_value, shorthand);
  10523. }
  10524. case_end;
  10525. case_ast_node(f, FieldList, node);
  10526. bool has_name = false;
  10527. for_array(i, f->list) {
  10528. ast_node(field, Field, f->list[i]);
  10529. if (field->names.count > 1) {
  10530. has_name = true;
  10531. break;
  10532. }
  10533. if (field->names.count == 0) {
  10534. continue;
  10535. }
  10536. if (!is_blank_ident(field->names[0])) {
  10537. has_name = true;
  10538. break;
  10539. }
  10540. }
  10541. for_array(i, f->list) {
  10542. if (i > 0) str = gb_string_appendc(str, ", ");
  10543. if (has_name) {
  10544. str = write_expr_to_string(str, f->list[i], shorthand);
  10545. } else {
  10546. ast_node(field, Field, f->list[i]);
  10547. if (field->flags&FieldFlag_using) {
  10548. str = gb_string_appendc(str, "using ");
  10549. }
  10550. if (field->flags&FieldFlag_no_alias) {
  10551. str = gb_string_appendc(str, "#no_alias ");
  10552. }
  10553. if (field->flags&FieldFlag_c_vararg) {
  10554. str = gb_string_appendc(str, "#c_vararg ");
  10555. }
  10556. if (field->flags&FieldFlag_any_int) {
  10557. str = gb_string_appendc(str, "#any_int ");
  10558. }
  10559. if (field->flags&FieldFlag_no_broadcast) {
  10560. str = gb_string_appendc(str, "#no_broadcast ");
  10561. }
  10562. if (field->flags&FieldFlag_const) {
  10563. str = gb_string_appendc(str, "#const ");
  10564. }
  10565. if (field->flags&FieldFlag_subtype) {
  10566. str = gb_string_appendc(str, "#subtype ");
  10567. }
  10568. str = write_expr_to_string(str, field->type, shorthand);
  10569. }
  10570. }
  10571. case_end;
  10572. case_ast_node(ce, CallExpr, node);
  10573. switch (ce->inlining) {
  10574. case ProcInlining_inline:
  10575. str = gb_string_appendc(str, "#force_inline ");
  10576. break;
  10577. case ProcInlining_no_inline:
  10578. str = gb_string_appendc(str, "#force_no_inline ");
  10579. break;
  10580. }
  10581. str = write_expr_to_string(str, ce->proc, shorthand);
  10582. str = gb_string_appendc(str, "(");
  10583. isize idx0 = cast(isize)ce->was_selector;
  10584. for (isize i = idx0; i < ce->args.count; i++) {
  10585. Ast *arg = ce->args[i];
  10586. if (i > idx0) {
  10587. str = gb_string_appendc(str, ", ");
  10588. }
  10589. str = write_expr_to_string(str, arg, shorthand);
  10590. }
  10591. str = gb_string_appendc(str, ")");
  10592. case_end;
  10593. case_ast_node(tt, TypeidType, node);
  10594. str = gb_string_appendc(str, "typeid");
  10595. if (tt->specialization) {
  10596. str = gb_string_appendc(str, "/");
  10597. str = write_expr_to_string(str, tt->specialization, shorthand);
  10598. }
  10599. case_end;
  10600. case_ast_node(pt, ProcType, node);
  10601. str = gb_string_appendc(str, "proc(");
  10602. str = write_expr_to_string(str, pt->params, shorthand);
  10603. str = gb_string_appendc(str, ")");
  10604. if (pt->results != nullptr) {
  10605. str = gb_string_appendc(str, " -> ");
  10606. bool parens_needed = false;
  10607. if (pt->results && pt->results->kind == Ast_FieldList) {
  10608. for (Ast *field : pt->results->FieldList.list) {
  10609. ast_node(f, Field, field);
  10610. if (f->names.count != 0) {
  10611. parens_needed = true;
  10612. break;
  10613. }
  10614. }
  10615. }
  10616. if (parens_needed) {
  10617. str = gb_string_append_rune(str, '(');
  10618. }
  10619. str = write_expr_to_string(str, pt->results, shorthand);
  10620. if (parens_needed) {
  10621. str = gb_string_append_rune(str, ')');
  10622. }
  10623. }
  10624. case_end;
  10625. case_ast_node(st, StructType, node);
  10626. str = gb_string_appendc(str, "struct ");
  10627. if (st->polymorphic_params) {
  10628. str = gb_string_append_rune(str, '(');
  10629. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10630. str = gb_string_appendc(str, ") ");
  10631. }
  10632. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10633. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10634. if (st->align) {
  10635. str = gb_string_appendc(str, "#align ");
  10636. str = write_expr_to_string(str, st->align, shorthand);
  10637. str = gb_string_append_rune(str, ' ');
  10638. }
  10639. str = gb_string_append_rune(str, '{');
  10640. if (shorthand) {
  10641. str = gb_string_appendc(str, "...");
  10642. } else {
  10643. str = write_struct_fields_to_string(str, st->fields);
  10644. }
  10645. str = gb_string_append_rune(str, '}');
  10646. case_end;
  10647. case_ast_node(st, UnionType, node);
  10648. str = gb_string_appendc(str, "union ");
  10649. if (st->polymorphic_params) {
  10650. str = gb_string_append_rune(str, '(');
  10651. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10652. str = gb_string_appendc(str, ") ");
  10653. }
  10654. switch (st->kind) {
  10655. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10656. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10657. }
  10658. if (st->align) {
  10659. str = gb_string_appendc(str, "#align ");
  10660. str = write_expr_to_string(str, st->align, shorthand);
  10661. str = gb_string_append_rune(str, ' ');
  10662. }
  10663. str = gb_string_append_rune(str, '{');
  10664. if (shorthand) {
  10665. str = gb_string_appendc(str, "...");
  10666. } else {
  10667. str = write_struct_fields_to_string(str, st->variants);
  10668. }
  10669. str = gb_string_append_rune(str, '}');
  10670. case_end;
  10671. case_ast_node(et, EnumType, node);
  10672. str = gb_string_appendc(str, "enum ");
  10673. if (et->base_type != nullptr) {
  10674. str = write_expr_to_string(str, et->base_type, shorthand);
  10675. str = gb_string_append_rune(str, ' ');
  10676. }
  10677. str = gb_string_append_rune(str, '{');
  10678. if (shorthand) {
  10679. str = gb_string_appendc(str, "...");
  10680. } else {
  10681. for_array(i, et->fields) {
  10682. if (i > 0) {
  10683. str = gb_string_appendc(str, ", ");
  10684. }
  10685. str = write_expr_to_string(str, et->fields[i], shorthand);
  10686. }
  10687. }
  10688. str = gb_string_append_rune(str, '}');
  10689. case_end;
  10690. case_ast_node(rt, RelativeType, node);
  10691. str = write_expr_to_string(str, rt->tag, shorthand);
  10692. str = gb_string_appendc(str, "" );
  10693. str = write_expr_to_string(str, rt->type, shorthand);
  10694. case_end;
  10695. case_ast_node(f, BitFieldField, node);
  10696. str = write_expr_to_string(str, f->name, shorthand);
  10697. str = gb_string_appendc(str, ": ");
  10698. str = write_expr_to_string(str, f->type, shorthand);
  10699. str = gb_string_appendc(str, " | ");
  10700. str = write_expr_to_string(str, f->bit_size, shorthand);
  10701. case_end;
  10702. case_ast_node(bf, BitFieldType, node);
  10703. str = gb_string_appendc(str, "bit_field ");
  10704. if (!shorthand) {
  10705. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10706. }
  10707. str = gb_string_appendc(str, " {");
  10708. if (shorthand) {
  10709. str = gb_string_appendc(str, "...");
  10710. } else {
  10711. for_array(i, bf->fields) {
  10712. if (i > 0) {
  10713. str = gb_string_appendc(str, ", ");
  10714. }
  10715. str = write_expr_to_string(str, bf->fields[i], false);
  10716. }
  10717. }
  10718. str = gb_string_appendc(str, "}");
  10719. case_end;
  10720. case_ast_node(ia, InlineAsmExpr, node);
  10721. str = gb_string_appendc(str, "asm(");
  10722. for_array(i, ia->param_types) {
  10723. if (i > 0) {
  10724. str = gb_string_appendc(str, ", ");
  10725. }
  10726. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10727. }
  10728. str = gb_string_appendc(str, ")");
  10729. if (ia->return_type != nullptr) {
  10730. str = gb_string_appendc(str, " -> ");
  10731. str = write_expr_to_string(str, ia->return_type, shorthand);
  10732. }
  10733. if (ia->has_side_effects) {
  10734. str = gb_string_appendc(str, " #side_effects");
  10735. }
  10736. if (ia->is_align_stack) {
  10737. str = gb_string_appendc(str, " #stack_align");
  10738. }
  10739. if (ia->dialect) {
  10740. str = gb_string_appendc(str, " #");
  10741. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10742. }
  10743. str = gb_string_appendc(str, " {");
  10744. if (shorthand) {
  10745. str = gb_string_appendc(str, "...");
  10746. } else {
  10747. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10748. str = gb_string_appendc(str, ", ");
  10749. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10750. }
  10751. str = gb_string_appendc(str, "}");
  10752. case_end;
  10753. }
  10754. return str;
  10755. }
  10756. gb_internal gbString expr_to_string(Ast *expression) {
  10757. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10758. }
  10759. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10760. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10761. }
  10762. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10763. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10764. }