check_expr.cpp 333 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527
  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_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  92. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  94. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
  95. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  96. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  97. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  98. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  99. gb_internal bool is_diverging_expr(Ast *expr);
  100. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  101. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  102. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  103. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  104. enum LoadDirectiveResult {
  105. LoadDirective_Success = 0,
  106. LoadDirective_Error = 1,
  107. LoadDirective_NotFound = 2,
  108. };
  109. gb_internal bool is_load_directive_call(Ast *call) {
  110. call = unparen_expr(call);
  111. if (call->kind != Ast_CallExpr) {
  112. return false;
  113. }
  114. ast_node(ce, CallExpr, call);
  115. if (ce->proc->kind != Ast_BasicDirective) {
  116. return false;
  117. }
  118. ast_node(bd, BasicDirective, ce->proc);
  119. String name = bd->name.string;
  120. return name == "load";
  121. }
  122. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  123. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  124. auto results = did_you_mean_results(d);
  125. if (results.count != 0) {
  126. error_line("\tSuggestion: Did you mean?\n");
  127. for (auto const &result : results) {
  128. String const &target = result.target;
  129. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  130. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  131. }
  132. }
  133. }
  134. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  135. if (e->kind != Entity_TypeName) {
  136. return;
  137. }
  138. if (e->TypeName.objc_metadata == nullptr) {
  139. return;
  140. }
  141. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  142. Type *t = base_type(e->type);
  143. GB_ASSERT(t->kind == Type_Struct);
  144. if (is_type) {
  145. for (auto const &entry : objc_metadata->type_entries) {
  146. string_set_add(set, entry.name);
  147. }
  148. } else {
  149. for (auto const &entry : objc_metadata->value_entries) {
  150. string_set_add(set, entry.name);
  151. }
  152. }
  153. for (Entity *f : t->Struct.fields) {
  154. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  155. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  156. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  157. }
  158. }
  159. }
  160. }
  161. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  162. if (build_context.terse_errors) { return; }
  163. ERROR_BLOCK();
  164. GB_ASSERT(e->kind == Entity_TypeName);
  165. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  166. auto *objc_metadata = e->TypeName.objc_metadata;
  167. MUTEX_GUARD(objc_metadata->mutex);
  168. StringSet set = {};
  169. defer (string_set_destroy(&set));
  170. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  171. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  172. defer (did_you_mean_destroy(&d));
  173. for (String const &target : set) {
  174. did_you_mean_append(&d, target);
  175. }
  176. check_did_you_mean_print(&d, prefix);
  177. }
  178. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  179. if (build_context.terse_errors) { return; }
  180. ERROR_BLOCK();
  181. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  182. defer (did_you_mean_destroy(&d));
  183. for (Entity *e : fields) {
  184. did_you_mean_append(&d, e->token.string);
  185. }
  186. check_did_you_mean_print(&d, prefix);
  187. }
  188. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  189. if (build_context.terse_errors) { return; }
  190. ERROR_BLOCK();
  191. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  192. defer (did_you_mean_destroy(&d));
  193. for (Entity *e : fields) {
  194. did_you_mean_append(&d, e->token.string);
  195. }
  196. check_did_you_mean_print(&d, prefix);
  197. }
  198. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  199. if (build_context.terse_errors) { return; }
  200. ERROR_BLOCK();
  201. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  202. defer (did_you_mean_destroy(&d));
  203. rw_mutex_shared_lock(&scope->mutex);
  204. for (auto const &entry : scope->elements) {
  205. Entity *e = entry.value;
  206. did_you_mean_append(&d, e->token.string);
  207. }
  208. rw_mutex_shared_unlock(&scope->mutex);
  209. check_did_you_mean_print(&d, prefix);
  210. }
  211. gb_internal Entity *entity_from_expr(Ast *expr) {
  212. expr = unparen_expr(expr);
  213. switch (expr->kind) {
  214. case Ast_Ident:
  215. return expr->Ident.entity;
  216. case Ast_SelectorExpr:
  217. return entity_from_expr(expr->SelectorExpr.selector);
  218. }
  219. return nullptr;
  220. }
  221. gb_internal void error_operand_not_expression(Operand *o) {
  222. if (o->mode == Addressing_Type) {
  223. gbString err = expr_to_string(o->expr);
  224. error(o->expr, "'%s' is not an expression but a type", err);
  225. gb_string_free(err);
  226. o->mode = Addressing_Invalid;
  227. }
  228. }
  229. gb_internal void error_operand_no_value(Operand *o) {
  230. if (o->mode == Addressing_NoValue) {
  231. gbString err = expr_to_string(o->expr);
  232. Ast *x = unparen_expr(o->expr);
  233. if (x->kind == Ast_CallExpr) {
  234. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  235. } else {
  236. error(o->expr, "'%s' used as a value", err);
  237. }
  238. gb_string_free(err);
  239. o->mode = Addressing_Invalid;
  240. }
  241. }
  242. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  243. if (build_context.dynamic_map_calls) {
  244. add_package_dependency(c, "runtime", "__dynamic_map_get");
  245. } else {
  246. add_package_dependency(c, "runtime", "map_desired_position");
  247. add_package_dependency(c, "runtime", "map_probe_distance");
  248. }
  249. }
  250. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  251. init_core_source_code_location(c->checker);
  252. if (t_map_set_proc == nullptr) {
  253. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  254. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  255. }
  256. if (build_context.dynamic_map_calls) {
  257. add_package_dependency(c, "runtime", "__dynamic_map_set");
  258. } else {
  259. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  260. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  261. }
  262. }
  263. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  264. init_core_source_code_location(c->checker);
  265. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  266. }
  267. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  268. Scope *s = c->scope;
  269. check_collect_entities(c, nodes);
  270. for (auto const &entry : s->elements) {
  271. Entity *e = entry.value;
  272. switch (e->kind) {
  273. case Entity_Constant:
  274. case Entity_TypeName:
  275. case Entity_Procedure:
  276. break;
  277. default:
  278. continue;
  279. }
  280. DeclInfo *d = decl_info_of_entity(e);
  281. if (d != nullptr) {
  282. check_entity_decl(c, e, d, nullptr);
  283. }
  284. }
  285. }
  286. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  287. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  288. ///////////////////////////////////////////////////////////////////////////////
  289. // //
  290. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  291. // //
  292. ///////////////////////////////////////////////////////////////////////////////
  293. CheckerInfo *info = old_c->info;
  294. if (base_entity == nullptr) {
  295. return false;
  296. }
  297. if (!is_type_proc(base_entity->type)) {
  298. return false;
  299. }
  300. if (base_entity->flags & EntityFlag_Disabled) {
  301. return false;
  302. }
  303. String name = base_entity->token.string;
  304. Type *src = base_type(base_entity->type);
  305. Type *dst = nullptr;
  306. if (type != nullptr) {
  307. dst = base_type(type);
  308. }
  309. if (param_operands == nullptr) {
  310. GB_ASSERT(dst != nullptr);
  311. }
  312. if (param_operands != nullptr) {
  313. GB_ASSERT(dst == nullptr);
  314. }
  315. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  316. return false;
  317. }
  318. if (dst != nullptr) {
  319. if (dst->Proc.is_polymorphic) {
  320. return false;
  321. }
  322. if (dst->Proc.param_count != src->Proc.param_count ||
  323. dst->Proc.result_count != src->Proc.result_count) {
  324. return false;
  325. }
  326. }
  327. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  328. if (old_decl == nullptr) {
  329. return false;
  330. }
  331. gbAllocator a = heap_allocator();
  332. Array<Operand> operands = {};
  333. if (param_operands) {
  334. operands = *param_operands;
  335. } else {
  336. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  337. for (isize i = 0; i < dst->Proc.param_count; i++) {
  338. Entity *param = dst->Proc.params->Tuple.variables[i];
  339. Operand o = {Addressing_Value};
  340. o.type = param->type;
  341. array_add(&operands, o);
  342. }
  343. }
  344. defer (if (param_operands == nullptr) {
  345. array_free(&operands);
  346. });
  347. CheckerContext nctx = *old_c;
  348. Scope *scope = create_scope(info, base_entity->scope);
  349. scope->flags |= ScopeFlag_Proc;
  350. nctx.scope = scope;
  351. nctx.allow_polymorphic_types = true;
  352. if (nctx.polymorphic_scope == nullptr) {
  353. nctx.polymorphic_scope = scope;
  354. }
  355. auto *pt = &src->Proc;
  356. // NOTE(bill): This is slightly memory leaking if the type already exists
  357. // Maybe it's better to check with the previous types first?
  358. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  359. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  360. if (!success) {
  361. return false;
  362. }
  363. GenProcsData *gen_procs = nullptr;
  364. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  365. GB_ASSERT(base_entity->kind == Entity_Procedure);
  366. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  367. gen_procs = base_entity->Procedure.gen_procs;
  368. if (gen_procs) {
  369. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  370. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  371. for (Entity *other : gen_procs->procs) {
  372. Type *pt = base_type(other->type);
  373. if (are_types_identical(pt, final_proc_type)) {
  374. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  375. if (poly_proc_data) {
  376. poly_proc_data->gen_entity = other;
  377. }
  378. return true;
  379. }
  380. }
  381. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  382. } else {
  383. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  384. gen_procs->procs.allocator = heap_allocator();
  385. base_entity->Procedure.gen_procs = gen_procs;
  386. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  387. }
  388. {
  389. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  390. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  391. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  392. nctx.no_polymorphic_errors = false;
  393. // NOTE(bill): Reset scope from the failed procedure type
  394. scope_reset(scope);
  395. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  396. Ast *cloned_proc_type_node = clone_ast(pt->node);
  397. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  398. if (!success) {
  399. return false;
  400. }
  401. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  402. for (Entity *other : gen_procs->procs) {
  403. Type *pt = base_type(other->type);
  404. if (are_types_identical(pt, final_proc_type)) {
  405. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  406. if (poly_proc_data) {
  407. poly_proc_data->gen_entity = other;
  408. }
  409. DeclInfo *decl = other->decl_info;
  410. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  411. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  412. proc_info->file = other->file;
  413. proc_info->token = other->token;
  414. proc_info->decl = decl;
  415. proc_info->type = other->type;
  416. proc_info->body = decl->proc_lit->ProcLit.body;
  417. proc_info->tags = other->Procedure.tags;;
  418. proc_info->generated_from_polymorphic = true;
  419. proc_info->poly_def_node = poly_def_node;
  420. check_procedure_later(nctx.checker, proc_info);
  421. }
  422. return true;
  423. }
  424. }
  425. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  426. }
  427. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  428. ast_node(pl, ProcLit, proc_lit);
  429. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  430. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  431. final_proc_type->Proc.is_poly_specialized = true;
  432. final_proc_type->Proc.is_polymorphic = true;
  433. final_proc_type->Proc.variadic = src->Proc.variadic;
  434. final_proc_type->Proc.require_results = src->Proc.require_results;
  435. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  436. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  437. final_proc_type->Proc.diverging = src->Proc.diverging;
  438. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  439. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  440. for (isize i = 0; i < operands.count; i++) {
  441. Operand o = operands[i];
  442. if (final_proc_type == o.type ||
  443. base_entity->type == o.type) {
  444. // NOTE(bill): Cycle
  445. final_proc_type->Proc.is_poly_specialized = false;
  446. break;
  447. }
  448. }
  449. u64 tags = base_entity->Procedure.tags;
  450. Ast *ident = clone_ast(base_entity->identifier);
  451. Token token = ident->Ident.token;
  452. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  453. d->gen_proc_type = final_proc_type;
  454. d->type_expr = pl->type;
  455. d->proc_lit = proc_lit;
  456. d->proc_checked_state = ProcCheckedState_Unchecked;
  457. d->defer_use_checked = false;
  458. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  459. entity->identifier = ident;
  460. add_entity_and_decl_info(&nctx, ident, entity, d);
  461. // NOTE(bill): Set the scope afterwards as this is not real overloading
  462. entity->scope = scope->parent;
  463. entity->file = base_entity->file;
  464. entity->pkg = base_entity->pkg;
  465. entity->flags = 0;
  466. d->entity = entity;
  467. AstFile *file = nullptr;
  468. {
  469. Scope *s = entity->scope;
  470. while (s != nullptr && s->file == nullptr) {
  471. file = s->file;
  472. s = s->parent;
  473. }
  474. }
  475. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  476. array_add(&gen_procs->procs, entity);
  477. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  478. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  479. proc_info->file = file;
  480. proc_info->token = token;
  481. proc_info->decl = d;
  482. proc_info->type = final_proc_type;
  483. proc_info->body = pl->body;
  484. proc_info->tags = tags;
  485. proc_info->generated_from_polymorphic = true;
  486. proc_info->poly_def_node = poly_def_node;
  487. if (poly_proc_data) {
  488. poly_proc_data->gen_entity = entity;
  489. poly_proc_data->proc_info = proc_info;
  490. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  491. }
  492. // NOTE(bill): Check the newly generated procedure body
  493. check_procedure_later(nctx.checker, proc_info);
  494. return true;
  495. }
  496. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  497. if (operand->expr == nullptr) return false;
  498. Entity *base_entity = entity_of_node(operand->expr);
  499. if (base_entity == nullptr) return false;
  500. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  501. }
  502. 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) {
  503. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  504. }
  505. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  506. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  507. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  508. #define MAXIMUM_TYPE_DISTANCE 10
  509. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  510. if (c == nullptr) {
  511. GB_ASSERT(operand->mode == Addressing_Value);
  512. GB_ASSERT(is_type_typed(operand->type));
  513. }
  514. if (operand->mode == Addressing_Invalid ||
  515. type == t_invalid) {
  516. return -1;
  517. }
  518. if (operand->mode == Addressing_Builtin) {
  519. return -1;
  520. }
  521. if (operand->mode == Addressing_Type) {
  522. if (is_type_typeid(type)) {
  523. if (is_type_polymorphic(operand->type)) {
  524. return -1;
  525. }
  526. add_type_info_type(c, operand->type);
  527. return 4;
  528. }
  529. return -1;
  530. }
  531. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  532. return -1;
  533. }
  534. Type *s = operand->type;
  535. if (are_types_identical(s, type)) {
  536. return 0;
  537. }
  538. Type *src = base_type(s);
  539. Type *dst = base_type(type);
  540. if (is_type_untyped_uninit(src)) {
  541. return 1;
  542. }
  543. if (is_type_untyped_nil(src)) {
  544. if (type_has_nil(dst)) {
  545. return 1;
  546. }
  547. return -1;
  548. }
  549. if (is_type_untyped(src)) {
  550. if (is_type_any(dst)) {
  551. // NOTE(bill): Anything can cast to 'Any'
  552. add_type_info_type(c, s);
  553. return MAXIMUM_TYPE_DISTANCE;
  554. }
  555. if (dst->kind == Type_Basic) {
  556. if (operand->mode == Addressing_Constant) {
  557. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  558. if (is_type_typed(dst) && src->kind == Type_Basic) {
  559. switch (src->Basic.kind) {
  560. case Basic_UntypedBool:
  561. if (is_type_boolean(dst)) {
  562. return 1;
  563. }
  564. break;
  565. case Basic_UntypedRune:
  566. if (is_type_integer(dst) || is_type_rune(dst)) {
  567. return 1;
  568. }
  569. break;
  570. case Basic_UntypedInteger:
  571. if (is_type_integer(dst) || is_type_rune(dst)) {
  572. return 1;
  573. }
  574. break;
  575. case Basic_UntypedString:
  576. if (is_type_string(dst)) {
  577. return 1;
  578. }
  579. break;
  580. case Basic_UntypedFloat:
  581. if (is_type_float(dst)) {
  582. return 1;
  583. }
  584. break;
  585. case Basic_UntypedComplex:
  586. if (is_type_complex(dst)) {
  587. return 1;
  588. }
  589. if (is_type_quaternion(dst)) {
  590. return 2;
  591. }
  592. break;
  593. case Basic_UntypedQuaternion:
  594. if (is_type_quaternion(dst)) {
  595. return 1;
  596. }
  597. break;
  598. }
  599. }
  600. return 2;
  601. }
  602. return -1;
  603. }
  604. if (src->kind == Type_Basic) {
  605. Type *d = base_array_type(dst);
  606. i64 score = -1;
  607. switch (src->Basic.kind) {
  608. case Basic_UntypedBool:
  609. if (is_type_boolean(d)) {
  610. score = 1;
  611. }
  612. break;
  613. case Basic_UntypedRune:
  614. if (is_type_integer(d) || is_type_rune(d)) {
  615. score = 1;
  616. }
  617. break;
  618. case Basic_UntypedInteger:
  619. if (is_type_integer(d) || is_type_rune(d)) {
  620. score = 1;
  621. }
  622. break;
  623. case Basic_UntypedString:
  624. if (is_type_string(d)) {
  625. score = 1;
  626. }
  627. break;
  628. case Basic_UntypedFloat:
  629. if (is_type_float(d)) {
  630. score = 1;
  631. }
  632. break;
  633. case Basic_UntypedComplex:
  634. if (is_type_complex(d)) {
  635. score = 1;
  636. }
  637. if (is_type_quaternion(d)) {
  638. score = 2;
  639. }
  640. break;
  641. case Basic_UntypedQuaternion:
  642. if (is_type_quaternion(d)) {
  643. score = 1;
  644. }
  645. break;
  646. }
  647. if (score > 0) {
  648. if (is_type_typed(d)) {
  649. score += 1;
  650. }
  651. if (d != dst) {
  652. score += 6;
  653. }
  654. }
  655. return score;
  656. }
  657. }
  658. }
  659. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  660. if (c->in_enum_type) {
  661. return 3;
  662. }
  663. }
  664. {
  665. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  666. if (subtype_level > 0) {
  667. return 4 + subtype_level;
  668. }
  669. }
  670. // rawptr <- ^T
  671. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  672. return 5;
  673. }
  674. // rawptr <- [^]T
  675. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  676. return 5;
  677. }
  678. // ^T <- [^]T
  679. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  680. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  681. return 4;
  682. }
  683. }
  684. // [^]T <- ^T
  685. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  686. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  687. return 4;
  688. }
  689. }
  690. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  691. bool modify_type = !c->no_polymorphic_errors;
  692. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  693. return 2;
  694. }
  695. }
  696. if (is_type_union(dst)) {
  697. for (Type *vt : dst->Union.variants) {
  698. if (are_types_identical(vt, s)) {
  699. return 1;
  700. }
  701. }
  702. if (dst->Union.variants.count == 1) {
  703. Type *vt = dst->Union.variants[0];
  704. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  705. if (score >= 0) {
  706. return score+2;
  707. }
  708. } else if (is_type_untyped(src)) {
  709. i64 prev_lowest_score = -1;
  710. i64 lowest_score = -1;
  711. for (Type *vt : dst->Union.variants) {
  712. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  713. if (score >= 0) {
  714. if (lowest_score < 0) {
  715. lowest_score = score;
  716. } else {
  717. if (prev_lowest_score < 0) {
  718. prev_lowest_score = lowest_score;
  719. } else {
  720. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  721. }
  722. lowest_score = gb_min(lowest_score, score);
  723. }
  724. }
  725. }
  726. if (lowest_score >= 0) {
  727. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  728. return lowest_score+2;
  729. }
  730. }
  731. }
  732. }
  733. if (is_type_relative_pointer(dst)) {
  734. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type, allow_array_programming);
  735. if (score >= 0) {
  736. return score+2;
  737. }
  738. }
  739. if (is_type_relative_multi_pointer(dst)) {
  740. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type, allow_array_programming);
  741. if (score >= 0) {
  742. return score+2;
  743. }
  744. }
  745. if (is_type_proc(dst)) {
  746. if (are_types_identical(src, dst)) {
  747. return 3;
  748. }
  749. PolyProcData poly_proc_data = {};
  750. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  751. Entity *e = poly_proc_data.gen_entity;
  752. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  753. add_entity_use(c, operand->expr, e);
  754. return 4;
  755. }
  756. }
  757. if (is_type_complex_or_quaternion(dst)) {
  758. Type *elem = base_complex_elem_type(dst);
  759. if (are_types_identical(elem, base_type(src))) {
  760. return 5;
  761. }
  762. }
  763. if (allow_array_programming) {
  764. if (is_type_array(dst)) {
  765. Type *elem = base_array_type(dst);
  766. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  767. if (distance >= 0) {
  768. return distance + 6;
  769. }
  770. }
  771. if (is_type_simd_vector(dst)) {
  772. Type *dst_elem = base_array_type(dst);
  773. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  774. if (distance >= 0) {
  775. return distance + 6;
  776. }
  777. }
  778. }
  779. if (is_type_matrix(dst)) {
  780. if (are_types_identical(src, dst)) {
  781. return 5;
  782. }
  783. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  784. Type *dst_elem = base_array_type(dst);
  785. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  786. if (distance >= 0) {
  787. return distance + 7;
  788. }
  789. }
  790. }
  791. if (is_type_any(dst)) {
  792. if (!is_type_polymorphic(src)) {
  793. if (operand->mode == Addressing_Context && operand->type == t_context) {
  794. return -1;
  795. } else {
  796. // NOTE(bill): Anything can cast to 'Any'
  797. add_type_info_type(c, s);
  798. return MAXIMUM_TYPE_DISTANCE;
  799. }
  800. }
  801. }
  802. Ast *expr = unparen_expr(operand->expr);
  803. if (expr != nullptr) {
  804. if (expr->kind == Ast_AutoCast) {
  805. Operand x = *operand;
  806. x.expr = expr->AutoCast.expr;
  807. if (check_cast_internal(c, &x, type)) {
  808. return MAXIMUM_TYPE_DISTANCE;
  809. }
  810. }
  811. }
  812. return -1;
  813. }
  814. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  815. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  816. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  817. // TODO(bill): A decent score function
  818. i64 d = distance*distance; // x^2
  819. if (is_variadic && d >= 0) {
  820. d += distance + 1; // x^2 + x + 1
  821. }
  822. return gb_max(c - d, 0);
  823. }
  824. 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) {
  825. i64 score = 0;
  826. i64 distance = check_distance_between_types(c, operand, type, allow_array_programming);
  827. bool ok = distance >= 0;
  828. if (ok) {
  829. score = assign_score_function(distance, is_variadic);
  830. }
  831. if (score_) *score_ = score;
  832. return ok;
  833. }
  834. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  835. i64 score = 0;
  836. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  837. }
  838. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  839. Operand x = {};
  840. x.type = src;
  841. x.mode = Addressing_Value;
  842. return check_is_assignable_to(nullptr, &x, dst);
  843. }
  844. gb_internal AstPackage *get_package_of_type(Type *type) {
  845. for (;;) {
  846. if (type == nullptr) {
  847. return nullptr;
  848. }
  849. switch (type->kind) {
  850. case Type_Basic:
  851. return builtin_pkg;
  852. case Type_Named:
  853. if (type->Named.type_name != nullptr) {
  854. return type->Named.type_name->pkg;
  855. }
  856. return nullptr;
  857. case Type_Pointer:
  858. type = type->Pointer.elem;
  859. continue;
  860. case Type_Array:
  861. type = type->Array.elem;
  862. continue;
  863. case Type_Slice:
  864. type = type->Slice.elem;
  865. continue;
  866. case Type_DynamicArray:
  867. type = type->DynamicArray.elem;
  868. continue;
  869. case Type_RelativePointer:
  870. type = type->RelativePointer.pointer_type;
  871. continue;
  872. case Type_RelativeMultiPointer:
  873. type = type->RelativeMultiPointer.pointer_type;
  874. continue;
  875. }
  876. return nullptr;
  877. }
  878. }
  879. // NOTE(bill): 'content_name' is for debugging and error messages
  880. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  881. check_not_tuple(c, operand);
  882. if (operand->mode == Addressing_Invalid) {
  883. return;
  884. }
  885. if (is_type_untyped(operand->type)) {
  886. Type *target_type = type;
  887. if (type == nullptr || is_type_any(type)) {
  888. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  889. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  890. operand->mode = Addressing_Invalid;
  891. return;
  892. }
  893. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  894. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  895. operand->mode = Addressing_Invalid;
  896. return;
  897. }
  898. target_type = default_type(operand->type);
  899. if (type != nullptr && !is_type_any(type)) {
  900. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  901. }
  902. add_type_info_type(c, type);
  903. add_type_info_type(c, target_type);
  904. }
  905. convert_to_typed(c, operand, target_type);
  906. if (operand->mode == Addressing_Invalid) {
  907. return;
  908. }
  909. }
  910. if (type == nullptr) {
  911. return;
  912. }
  913. if (operand->mode == Addressing_ProcGroup) {
  914. bool good = false;
  915. if (type != nullptr && is_type_proc(type)) {
  916. Array<Entity *> procs = proc_group_entities(c, *operand);
  917. // NOTE(bill): These should be done
  918. for (Entity *e : procs) {
  919. Type *t = base_type(e->type);
  920. if (t == t_invalid) {
  921. continue;
  922. }
  923. Operand x = {};
  924. x.mode = Addressing_Value;
  925. x.type = t;
  926. if (check_is_assignable_to(c, &x, type)) {
  927. add_entity_use(c, operand->expr, e);
  928. good = true;
  929. break;
  930. }
  931. }
  932. }
  933. if (!good) {
  934. gbString expr_str = expr_to_string(operand->expr);
  935. gbString op_type_str = type_to_string(operand->type);
  936. gbString type_str = type_to_string(type);
  937. defer (gb_string_free(type_str));
  938. defer (gb_string_free(op_type_str));
  939. defer (gb_string_free(expr_str));
  940. // TODO(bill): is this a good enough error message?
  941. error(operand->expr,
  942. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  943. expr_str,
  944. op_type_str,
  945. LIT(context_name));
  946. operand->mode = Addressing_Invalid;
  947. }
  948. convert_to_typed(c, operand, type);
  949. return;
  950. }
  951. if (check_is_assignable_to(c, operand, type)) {
  952. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  953. add_type_info_type(c, operand->type);
  954. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  955. }
  956. } else {
  957. gbString expr_str = expr_to_string(operand->expr);
  958. gbString op_type_str = type_to_string(operand->type);
  959. gbString type_str = type_to_string(type);
  960. defer (gb_string_free(type_str));
  961. defer (gb_string_free(op_type_str));
  962. defer (gb_string_free(expr_str));
  963. switch (operand->mode) {
  964. case Addressing_Builtin:
  965. error(operand->expr,
  966. "Cannot assign built-in procedure '%s' in %.*s",
  967. expr_str,
  968. LIT(context_name));
  969. break;
  970. case Addressing_Type:
  971. if (is_type_polymorphic(operand->type)) {
  972. error(operand->expr,
  973. "Cannot assign '%s' which is a polymorphic type in %.*s",
  974. op_type_str,
  975. LIT(context_name));
  976. } else {
  977. error(operand->expr,
  978. "Cannot assign '%s' which is a type in %.*s",
  979. op_type_str,
  980. LIT(context_name));
  981. }
  982. break;
  983. default:
  984. // TODO(bill): is this a good enough error message?
  985. {
  986. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  987. gbString type_extra = gb_string_make(heap_allocator(), "");
  988. defer (gb_string_free(op_type_extra));
  989. defer (gb_string_free(type_extra));
  990. isize on = gb_string_length(op_type_str);
  991. isize tn = gb_string_length(type_str);
  992. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  993. AstPackage *op_pkg = get_package_of_type(operand->type);
  994. AstPackage *type_pkg = get_package_of_type(type);
  995. if (op_pkg != nullptr) {
  996. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  997. }
  998. if (type_pkg != nullptr) {
  999. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1000. }
  1001. }
  1002. ERROR_BLOCK();
  1003. error(operand->expr,
  1004. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  1005. expr_str,
  1006. op_type_str, op_type_extra,
  1007. type_str, type_extra,
  1008. LIT(context_name));
  1009. check_assignment_error_suggestion(c, operand, type);
  1010. if (context_name == "procedure argument") {
  1011. Type *src = base_type(operand->type);
  1012. Type *dst = base_type(type);
  1013. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1014. gbString a = expr_to_string(operand->expr);
  1015. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1016. gb_string_free(a);
  1017. }
  1018. }
  1019. }
  1020. break;
  1021. }
  1022. operand->mode = Addressing_Invalid;
  1023. return;
  1024. }
  1025. }
  1026. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1027. Type *gt = *gt_;
  1028. GB_ASSERT(gt->kind == Type_Generic);
  1029. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1030. GB_ASSERT(e != nullptr);
  1031. if (e->kind == Entity_TypeName) {
  1032. *gt_ = nullptr;
  1033. *dst_count = source_count;
  1034. e->kind = Entity_Constant;
  1035. e->Constant.value = exact_value_i64(source_count);
  1036. e->type = t_untyped_integer;
  1037. return true;
  1038. } else if (e->kind == Entity_Constant) {
  1039. *gt_ = nullptr;
  1040. if (e->Constant.value.kind != ExactValue_Integer) {
  1041. return false;
  1042. }
  1043. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1044. if (count != source_count) {
  1045. return false;
  1046. }
  1047. *dst_count = source_count;
  1048. return true;
  1049. }
  1050. return false;
  1051. }
  1052. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1053. Operand o = {Addressing_Value};
  1054. o.type = source;
  1055. switch (poly->kind) {
  1056. case Type_Basic:
  1057. if (compound) return are_types_identical(poly, source);
  1058. return check_is_assignable_to(c, &o, poly);
  1059. case Type_Named: {
  1060. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1061. return true;
  1062. }
  1063. if (compound || !is_type_generic(poly)) {
  1064. return are_types_identical(poly, source);
  1065. }
  1066. return check_is_assignable_to(c, &o, poly);
  1067. }
  1068. case Type_Generic: {
  1069. if (poly->Generic.specialized != nullptr) {
  1070. Type *s = poly->Generic.specialized;
  1071. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1072. return false;
  1073. }
  1074. }
  1075. if (modify_type) {
  1076. Type *ds = default_type(source);
  1077. gb_memmove(poly, ds, gb_size_of(Type));
  1078. }
  1079. return true;
  1080. }
  1081. case Type_Pointer:
  1082. if (source->kind == Type_Pointer) {
  1083. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1084. if (level > 0) {
  1085. return true;
  1086. }
  1087. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1088. } else if (source->kind == Type_MultiPointer) {
  1089. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1090. if (level > 0) {
  1091. return true;
  1092. }
  1093. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1094. }
  1095. return false;
  1096. case Type_MultiPointer:
  1097. if (source->kind == Type_MultiPointer) {
  1098. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1099. if (level > 0) {
  1100. return true;
  1101. }
  1102. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1103. } else if (source->kind == Type_Pointer) {
  1104. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1105. if (level > 0) {
  1106. return true;
  1107. }
  1108. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1109. }
  1110. return false;
  1111. case Type_Array:
  1112. if (source->kind == Type_Array) {
  1113. if (poly->Array.generic_count != nullptr) {
  1114. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1115. return false;
  1116. }
  1117. }
  1118. if (poly->Array.count == source->Array.count) {
  1119. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1120. }
  1121. } else if (source->kind == Type_EnumeratedArray) {
  1122. if (poly->Array.generic_count != nullptr) {
  1123. Type *gt = poly->Array.generic_count;
  1124. GB_ASSERT(gt->kind == Type_Generic);
  1125. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1126. GB_ASSERT(e != nullptr);
  1127. if (e->kind == Entity_TypeName) {
  1128. Type *index = source->EnumeratedArray.index;
  1129. Type *it = base_type(index);
  1130. if (it->kind != Type_Enum) {
  1131. return false;
  1132. }
  1133. poly->kind = Type_EnumeratedArray;
  1134. poly->cached_size = -1;
  1135. poly->cached_align = -1;
  1136. poly->flags.exchange(source->flags);
  1137. poly->failure = false;
  1138. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1139. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1140. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1141. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1142. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1143. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1144. e->kind = Entity_TypeName;
  1145. e->TypeName.is_type_alias = true;
  1146. e->type = index;
  1147. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1148. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. return false;
  1154. case Type_EnumeratedArray:
  1155. if (source->kind == Type_EnumeratedArray) {
  1156. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1157. return false;
  1158. }
  1159. if (poly->EnumeratedArray.op) {
  1160. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1161. return false;
  1162. }
  1163. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1164. return false;
  1165. }
  1166. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1167. return false;
  1168. }
  1169. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1170. }
  1171. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1172. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1173. return index || elem;
  1174. }
  1175. return false;
  1176. case Type_DynamicArray:
  1177. if (source->kind == Type_DynamicArray) {
  1178. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1179. }
  1180. return false;
  1181. case Type_Slice:
  1182. if (source->kind == Type_Slice) {
  1183. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1184. }
  1185. return false;
  1186. case Type_Enum:
  1187. return false;
  1188. case Type_BitSet:
  1189. if (source->kind == Type_BitSet) {
  1190. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1191. return false;
  1192. }
  1193. if (poly->BitSet.underlying == nullptr) {
  1194. if (modify_type) {
  1195. poly->BitSet.underlying = source->BitSet.underlying;
  1196. }
  1197. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1198. return false;
  1199. }
  1200. return true;
  1201. }
  1202. return false;
  1203. case Type_Union:
  1204. if (source->kind == Type_Union) {
  1205. TypeUnion *x = &poly->Union;
  1206. TypeUnion *y = &source->Union;
  1207. if (x->variants.count != y->variants.count) {
  1208. return false;
  1209. }
  1210. for_array(i, x->variants) {
  1211. Type *a = x->variants[i];
  1212. Type *b = y->variants[i];
  1213. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1214. if (!ok) return false;
  1215. }
  1216. return true;
  1217. }
  1218. return false;
  1219. case Type_Struct:
  1220. if (source->kind == Type_Struct) {
  1221. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1222. poly->Struct.soa_kind != StructSoa_None) {
  1223. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1224. if (ok) switch (source->Struct.soa_kind) {
  1225. case StructSoa_Fixed:
  1226. default:
  1227. GB_PANIC("Unhandled SOA Kind");
  1228. break;
  1229. case StructSoa_Slice:
  1230. if (modify_type) {
  1231. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1232. gb_memmove(poly, type, gb_size_of(*type));
  1233. }
  1234. break;
  1235. case StructSoa_Dynamic:
  1236. if (modify_type) {
  1237. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1238. gb_memmove(poly, type, gb_size_of(*type));
  1239. }
  1240. break;
  1241. }
  1242. return ok;
  1243. }
  1244. // NOTE(bill): Check for subtypes of
  1245. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1246. }
  1247. return false;
  1248. case Type_Tuple:
  1249. GB_PANIC("This should never happen");
  1250. return false;
  1251. case Type_Proc:
  1252. if (source->kind == Type_Proc) {
  1253. TypeProc *x = &poly->Proc;
  1254. TypeProc *y = &source->Proc;
  1255. if (x->calling_convention != y->calling_convention) {
  1256. return false;
  1257. }
  1258. if (x->c_vararg != y->c_vararg) {
  1259. return false;
  1260. }
  1261. if (x->variadic != y->variadic) {
  1262. return false;
  1263. }
  1264. if (x->param_count != y->param_count) {
  1265. return false;
  1266. }
  1267. if (x->result_count != y->result_count) {
  1268. return false;
  1269. }
  1270. for (isize i = 0; i < x->param_count; i++) {
  1271. Entity *a = x->params->Tuple.variables[i];
  1272. Entity *b = y->params->Tuple.variables[i];
  1273. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1274. if (!ok) return false;
  1275. }
  1276. for (isize i = 0; i < x->result_count; i++) {
  1277. Entity *a = x->results->Tuple.variables[i];
  1278. Entity *b = y->results->Tuple.variables[i];
  1279. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1280. if (!ok) return false;
  1281. }
  1282. return true;
  1283. }
  1284. return false;
  1285. case Type_Map:
  1286. if (source->kind == Type_Map) {
  1287. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1288. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1289. if (key || value) {
  1290. poly->Map.lookup_result_type = nullptr;
  1291. init_map_internal_types(poly);
  1292. return true;
  1293. }
  1294. }
  1295. return false;
  1296. case Type_Matrix:
  1297. if (source->kind == Type_Matrix) {
  1298. if (poly->Matrix.generic_row_count != nullptr) {
  1299. poly->Matrix.stride_in_bytes = 0;
  1300. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1301. return false;
  1302. }
  1303. }
  1304. if (poly->Matrix.generic_column_count != nullptr) {
  1305. poly->Matrix.stride_in_bytes = 0;
  1306. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1307. return false;
  1308. }
  1309. }
  1310. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1311. poly->Matrix.column_count == source->Matrix.column_count) {
  1312. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1313. }
  1314. }
  1315. return false;
  1316. case Type_SimdVector:
  1317. if (source->kind == Type_SimdVector) {
  1318. if (poly->SimdVector.generic_count != nullptr) {
  1319. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1320. return false;
  1321. }
  1322. }
  1323. if (poly->SimdVector.count == source->SimdVector.count) {
  1324. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1325. }
  1326. }
  1327. return false;
  1328. }
  1329. return false;
  1330. }
  1331. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1332. if (curr->state != EntityState_InProgress) {
  1333. return false;
  1334. }
  1335. for_array(i, *c->type_path) {
  1336. Entity *prev = c->type_path->data[i];
  1337. if (prev == curr) {
  1338. if (report) {
  1339. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1340. for (isize j = i; j < c->type_path->count; j++) {
  1341. Entity *curr = (*c->type_path)[j];
  1342. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1343. }
  1344. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1345. curr->type = t_invalid;
  1346. }
  1347. return true;
  1348. }
  1349. }
  1350. return false;
  1351. }
  1352. struct CIdentSuggestion {
  1353. String name;
  1354. String msg;
  1355. };
  1356. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1357. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1358. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1359. {str_lit("sizeof"), str_lit("'size_of'?")},
  1360. {str_lit("alignof"), str_lit("'align_of'?")},
  1361. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1362. {str_lit("_Bool"), str_lit("'bool'?")},
  1363. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1364. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1365. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1366. {str_lit("float"), str_lit("'f32'?")},
  1367. {str_lit("double"), str_lit("'f64'?")},
  1368. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1369. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1370. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1371. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1372. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1373. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1374. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1375. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1376. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1377. {str_lit("uint8_t"), str_lit("'u8'?")},
  1378. {str_lit("int8_t"), str_lit("'i8'?")},
  1379. {str_lit("uint16_t"), str_lit("'u16'?")},
  1380. {str_lit("int16_t"), str_lit("'i16'?")},
  1381. {str_lit("uint32_t"), str_lit("'u32'?")},
  1382. {str_lit("int32_t"), str_lit("'i32'?")},
  1383. {str_lit("uint64_t"), str_lit("'u64'?")},
  1384. {str_lit("int64_t"), str_lit("'i64'?")},
  1385. {str_lit("uint128_t"), str_lit("'u128'?")},
  1386. {str_lit("int128_t"), str_lit("'i128'?")},
  1387. {str_lit("float32"), str_lit("'f32'?")},
  1388. {str_lit("float64"), str_lit("'f64'?")},
  1389. {str_lit("float32_t"), str_lit("'f32'?")},
  1390. {str_lit("float64_t"), str_lit("'f64'?")},
  1391. };
  1392. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1393. GB_ASSERT(n->kind == Ast_Ident);
  1394. o->mode = Addressing_Invalid;
  1395. o->expr = n;
  1396. String name = n->Ident.token.string;
  1397. Entity *e = scope_lookup(c->scope, name);
  1398. if (e == nullptr) {
  1399. if (is_blank_ident(name)) {
  1400. error(n, "'_' cannot be used as a value");
  1401. } else {
  1402. ERROR_BLOCK();
  1403. error(n, "Undeclared name: %.*s", LIT(name));
  1404. // NOTE(bill): Loads of checks for C programmers
  1405. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1406. if (name == suggestion.name) {
  1407. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1408. }
  1409. }
  1410. }
  1411. o->type = t_invalid;
  1412. o->mode = Addressing_Invalid;
  1413. if (named_type != nullptr) {
  1414. set_base_type(named_type, t_invalid);
  1415. }
  1416. return nullptr;
  1417. }
  1418. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1419. if (e->parent_proc_decl != nullptr &&
  1420. e->parent_proc_decl != c->curr_proc_decl) {
  1421. if (e->kind == Entity_Variable) {
  1422. if ((e->flags & EntityFlag_Static) == 0) {
  1423. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1424. return nullptr;
  1425. }
  1426. } else if (e->kind == Entity_Label) {
  1427. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1428. return nullptr;
  1429. }
  1430. }
  1431. if (e->kind == Entity_ProcGroup) {
  1432. auto *pge = &e->ProcGroup;
  1433. DeclInfo *d = decl_info_of_entity(e);
  1434. check_entity_decl(c, e, d, nullptr);
  1435. Array<Entity *> procs = pge->entities;
  1436. bool skip = false;
  1437. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1438. // NOTE(bill): These should be done
  1439. for (Entity *proc : procs) {
  1440. Type *t = base_type(proc->type);
  1441. if (t == t_invalid) {
  1442. continue;
  1443. }
  1444. Operand x = {};
  1445. x.mode = Addressing_Value;
  1446. x.type = t;
  1447. if (check_is_assignable_to(c, &x, type_hint)) {
  1448. e = proc;
  1449. add_entity_use(c, n, e);
  1450. skip = true;
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. if (!skip) {
  1456. o->mode = Addressing_ProcGroup;
  1457. o->type = t_invalid;
  1458. o->proc_group = e;
  1459. return nullptr;
  1460. }
  1461. }
  1462. add_entity_use(c, n, e);
  1463. if (e->state == EntityState_Unresolved) {
  1464. check_entity_decl(c, e, nullptr, named_type);
  1465. }
  1466. if (e->type == nullptr) {
  1467. // TODO(bill): Which is correct? return or compiler_error?
  1468. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1469. return nullptr;
  1470. }
  1471. e->flags |= EntityFlag_Used;
  1472. Type *type = e->type;
  1473. o->type = type;
  1474. switch (e->kind) {
  1475. case Entity_Constant:
  1476. if (type == t_invalid) {
  1477. o->type = t_invalid;
  1478. return e;
  1479. }
  1480. o->value = e->Constant.value;
  1481. if (o->value.kind == ExactValue_Invalid) {
  1482. return e;
  1483. }
  1484. if (o->value.kind == ExactValue_Procedure) {
  1485. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1486. if (proc != nullptr) {
  1487. o->mode = Addressing_Value;
  1488. o->type = proc->type;
  1489. return proc;
  1490. }
  1491. }
  1492. o->mode = Addressing_Constant;
  1493. break;
  1494. case Entity_Variable:
  1495. e->flags |= EntityFlag_Used;
  1496. if (type == t_invalid) {
  1497. o->type = t_invalid;
  1498. return e;
  1499. }
  1500. o->mode = Addressing_Variable;
  1501. if (e->flags & EntityFlag_Value) {
  1502. o->mode = Addressing_Value;
  1503. }
  1504. break;
  1505. case Entity_Procedure:
  1506. o->mode = Addressing_Value;
  1507. o->value = exact_value_procedure(n);
  1508. break;
  1509. case Entity_Builtin:
  1510. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1511. o->mode = Addressing_Builtin;
  1512. break;
  1513. case Entity_TypeName:
  1514. o->mode = Addressing_Type;
  1515. if (check_cycle(c, e, true)) {
  1516. o->type = t_invalid;
  1517. }
  1518. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1519. o->type = base_type(o->type);
  1520. }
  1521. break;
  1522. case Entity_ImportName:
  1523. if (!allow_import_name) {
  1524. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1525. }
  1526. return e;
  1527. case Entity_LibraryName:
  1528. if (!allow_import_name) {
  1529. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1530. }
  1531. return e;
  1532. case Entity_Label:
  1533. o->mode = Addressing_NoValue;
  1534. break;
  1535. case Entity_Nil:
  1536. o->mode = Addressing_Value;
  1537. break;
  1538. default:
  1539. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1540. break;
  1541. }
  1542. return e;
  1543. }
  1544. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1545. if (o->type == nullptr) {
  1546. gbString str = expr_to_string(o->expr);
  1547. error(o->expr, "Expression has no value '%s'", str);
  1548. gb_string_free(str);
  1549. return false;
  1550. }
  1551. Type *type = base_type(core_array_type(o->type));
  1552. gbString str = nullptr;
  1553. switch (op.kind) {
  1554. case Token_Add:
  1555. case Token_Sub:
  1556. if (!is_type_numeric(type)) {
  1557. str = expr_to_string(o->expr);
  1558. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1559. gb_string_free(str);
  1560. }
  1561. break;
  1562. case Token_Xor:
  1563. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1564. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1565. }
  1566. break;
  1567. case Token_Not:
  1568. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1569. ERROR_BLOCK();
  1570. str = expr_to_string(o->expr);
  1571. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1572. gb_string_free(str);
  1573. if (is_type_integer(type)) {
  1574. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1575. }
  1576. } else {
  1577. o->type = t_untyped_bool;
  1578. }
  1579. break;
  1580. case Token_Mul:
  1581. {
  1582. ERROR_BLOCK();
  1583. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1584. if (is_type_pointer(o->type)) {
  1585. str = expr_to_string(o->expr);
  1586. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1587. o->type = type_deref(o->type);
  1588. } else if (is_type_multi_pointer(o->type)) {
  1589. str = expr_to_string(o->expr);
  1590. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1591. o->type = type_deref(o->type, true);
  1592. }
  1593. }
  1594. break;
  1595. default:
  1596. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1597. return false;
  1598. }
  1599. return true;
  1600. }
  1601. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1602. Type *main_type = o->type;
  1603. Type *type = base_type(core_array_type(main_type));
  1604. Type *ct = core_type(type);
  1605. switch (op.kind) {
  1606. case Token_Sub:
  1607. case Token_SubEq:
  1608. if (is_type_bit_set(type)) {
  1609. return true;
  1610. } else if (!is_type_numeric(type)) {
  1611. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1612. return false;
  1613. }
  1614. break;
  1615. case Token_Quo:
  1616. case Token_QuoEq:
  1617. if (is_type_matrix(main_type)) {
  1618. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1619. return false;
  1620. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1621. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1622. return false;
  1623. }
  1624. /*fallthrough*/
  1625. case Token_Mul:
  1626. case Token_MulEq:
  1627. case Token_AddEq:
  1628. if (is_type_bit_set(type)) {
  1629. return true;
  1630. } else if (!is_type_numeric(type)) {
  1631. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1632. return false;
  1633. }
  1634. break;
  1635. case Token_Add:
  1636. if (is_type_string(type)) {
  1637. if (o->mode == Addressing_Constant) {
  1638. return true;
  1639. }
  1640. error(op, "String concatenation is only allowed with constant strings");
  1641. return false;
  1642. } else if (is_type_bit_set(type)) {
  1643. return true;
  1644. } else if (!is_type_numeric(type)) {
  1645. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1646. return false;
  1647. }
  1648. break;
  1649. case Token_And:
  1650. case Token_Or:
  1651. case Token_AndEq:
  1652. case Token_OrEq:
  1653. case Token_Xor:
  1654. case Token_XorEq:
  1655. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1656. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1657. return false;
  1658. }
  1659. break;
  1660. case Token_Mod:
  1661. case Token_ModMod:
  1662. case Token_ModEq:
  1663. case Token_ModModEq:
  1664. if (is_type_matrix(main_type)) {
  1665. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1666. return false;
  1667. }
  1668. if (!is_type_integer(type)) {
  1669. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1670. return false;
  1671. } else if (is_type_simd_vector(main_type)) {
  1672. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1673. return false;
  1674. }
  1675. break;
  1676. case Token_AndNot:
  1677. case Token_AndNotEq:
  1678. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1679. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1680. return false;
  1681. }
  1682. break;
  1683. case Token_CmpAnd:
  1684. case Token_CmpOr:
  1685. case Token_CmpAndEq:
  1686. case Token_CmpOrEq:
  1687. if (!is_type_boolean(type)) {
  1688. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1689. return false;
  1690. }
  1691. break;
  1692. default:
  1693. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1694. return false;
  1695. }
  1696. return true;
  1697. }
  1698. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1699. if (in_value.kind == ExactValue_Invalid) {
  1700. // NOTE(bill): There's already been an error
  1701. return true;
  1702. }
  1703. type = core_type(type);
  1704. if (type == t_invalid) {
  1705. return false;
  1706. } else if (is_type_boolean(type)) {
  1707. return in_value.kind == ExactValue_Bool;
  1708. } else if (is_type_string(type)) {
  1709. return in_value.kind == ExactValue_String;
  1710. } else if (is_type_integer(type) || is_type_rune(type)) {
  1711. if (in_value.kind == ExactValue_Bool) {
  1712. return false;
  1713. }
  1714. ExactValue v = exact_value_to_integer(in_value);
  1715. if (v.kind != ExactValue_Integer) {
  1716. return false;
  1717. }
  1718. if (out_value) *out_value = v;
  1719. if (is_type_untyped(type)) {
  1720. return true;
  1721. }
  1722. BigInt i = v.value_integer;
  1723. i64 byte_size = type_size_of(type);
  1724. BigInt umax = {};
  1725. BigInt imin = {};
  1726. BigInt imax = {};
  1727. if (c->bit_field_bit_size > 0) {
  1728. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1729. big_int_from_u64(&umax, 1);
  1730. big_int_from_i64(&imin, 1);
  1731. big_int_from_i64(&imax, 1);
  1732. BigInt bu = {};
  1733. BigInt bi = {};
  1734. big_int_from_i64(&bu, bit_size);
  1735. big_int_from_i64(&bi, bit_size-1);
  1736. big_int_shl_eq(&umax, &bu);
  1737. mp_decr(&umax);
  1738. big_int_shl_eq(&imin, &bi);
  1739. big_int_neg(&imin, &imin);
  1740. big_int_shl_eq(&imax, &bi);
  1741. mp_decr(&imax);
  1742. } else {
  1743. if (byte_size < 16) {
  1744. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1745. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1746. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1747. } else {
  1748. big_int_from_u64(&umax, 1);
  1749. big_int_from_i64(&imin, 1);
  1750. big_int_from_i64(&imax, 1);
  1751. BigInt bi128 = {};
  1752. BigInt bi127 = {};
  1753. big_int_from_i64(&bi128, 128);
  1754. big_int_from_i64(&bi127, 127);
  1755. big_int_shl_eq(&umax, &bi128);
  1756. mp_decr(&umax);
  1757. big_int_shl_eq(&imin, &bi127);
  1758. big_int_neg(&imin, &imin);
  1759. big_int_shl_eq(&imax, &bi127);
  1760. mp_decr(&imax);
  1761. }
  1762. }
  1763. switch (type->Basic.kind) {
  1764. case Basic_rune:
  1765. case Basic_i8:
  1766. case Basic_i16:
  1767. case Basic_i32:
  1768. case Basic_i64:
  1769. case Basic_i128:
  1770. case Basic_int:
  1771. case Basic_i16le:
  1772. case Basic_i32le:
  1773. case Basic_i64le:
  1774. case Basic_i128le:
  1775. case Basic_i16be:
  1776. case Basic_i32be:
  1777. case Basic_i64be:
  1778. case Basic_i128be:
  1779. {
  1780. // return imin <= i && i <= imax;
  1781. int a = big_int_cmp(&imin, &i);
  1782. int b = big_int_cmp(&i, &imax);
  1783. return (a <= 0) && (b <= 0);
  1784. }
  1785. case Basic_u8:
  1786. case Basic_u16:
  1787. case Basic_u32:
  1788. case Basic_u64:
  1789. case Basic_u128:
  1790. case Basic_uint:
  1791. case Basic_uintptr:
  1792. case Basic_u16le:
  1793. case Basic_u32le:
  1794. case Basic_u64le:
  1795. case Basic_u128le:
  1796. case Basic_u16be:
  1797. case Basic_u32be:
  1798. case Basic_u64be:
  1799. case Basic_u128be:
  1800. {
  1801. // return 0ull <= i && i <= umax;
  1802. int b = big_int_cmp(&i, &umax);
  1803. return !i.sign && (b <= 0);
  1804. }
  1805. case Basic_UntypedInteger:
  1806. return true;
  1807. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1808. }
  1809. } else if (is_type_float(type)) {
  1810. ExactValue v = exact_value_to_float(in_value);
  1811. if (v.kind != ExactValue_Float) {
  1812. return false;
  1813. }
  1814. if (out_value) *out_value = v;
  1815. switch (type->Basic.kind) {
  1816. case Basic_f16:
  1817. case Basic_f32:
  1818. case Basic_f64:
  1819. return true;
  1820. case Basic_f16le:
  1821. case Basic_f16be:
  1822. case Basic_f32le:
  1823. case Basic_f32be:
  1824. case Basic_f64le:
  1825. case Basic_f64be:
  1826. return true;
  1827. case Basic_UntypedFloat:
  1828. return true;
  1829. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1830. }
  1831. } else if (is_type_complex(type)) {
  1832. ExactValue v = exact_value_to_complex(in_value);
  1833. if (v.kind != ExactValue_Complex) {
  1834. return false;
  1835. }
  1836. switch (type->Basic.kind) {
  1837. case Basic_complex32:
  1838. case Basic_complex64:
  1839. case Basic_complex128: {
  1840. ExactValue real = exact_value_real(v);
  1841. ExactValue imag = exact_value_imag(v);
  1842. if (real.kind != ExactValue_Invalid &&
  1843. imag.kind != ExactValue_Invalid) {
  1844. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1845. return true;
  1846. }
  1847. break;
  1848. }
  1849. case Basic_UntypedComplex:
  1850. return true;
  1851. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1852. }
  1853. return false;
  1854. } else if (is_type_quaternion(type)) {
  1855. ExactValue v = exact_value_to_quaternion(in_value);
  1856. if (v.kind != ExactValue_Quaternion) {
  1857. return false;
  1858. }
  1859. switch (type->Basic.kind) {
  1860. case Basic_quaternion64:
  1861. case Basic_quaternion128:
  1862. case Basic_quaternion256: {
  1863. ExactValue real = exact_value_real(v);
  1864. ExactValue imag = exact_value_imag(v);
  1865. ExactValue jmag = exact_value_jmag(v);
  1866. ExactValue kmag = exact_value_kmag(v);
  1867. if (real.kind != ExactValue_Invalid &&
  1868. imag.kind != ExactValue_Invalid) {
  1869. 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));
  1870. return true;
  1871. }
  1872. break;
  1873. }
  1874. case Basic_UntypedComplex:
  1875. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1876. return true;
  1877. case Basic_UntypedQuaternion:
  1878. return true;
  1879. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1880. }
  1881. return false;
  1882. } else if (is_type_pointer(type)) {
  1883. if (in_value.kind == ExactValue_Pointer) {
  1884. return true;
  1885. }
  1886. if (in_value.kind == ExactValue_Integer) {
  1887. return false;
  1888. // return true;
  1889. }
  1890. if (in_value.kind == ExactValue_String) {
  1891. return false;
  1892. }
  1893. if (out_value) *out_value = in_value;
  1894. } else if (is_type_bit_set(type)) {
  1895. if (in_value.kind == ExactValue_Integer) {
  1896. return true;
  1897. }
  1898. }
  1899. return false;
  1900. }
  1901. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  1902. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1903. gbString b = type_to_string(type);
  1904. i64 sz = type_size_of(type);
  1905. i64 bit_size = 8*sz;
  1906. bool size_changed = false;
  1907. if (max_bit_size > 0) {
  1908. size_changed = (bit_size != max_bit_size);
  1909. bit_size = gb_min(bit_size, max_bit_size);
  1910. }
  1911. BigInt *bi = &o->value.value_integer;
  1912. if (is_type_unsigned(type)) {
  1913. if (big_int_is_neg(bi)) {
  1914. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1915. } else {
  1916. BigInt one = big_int_make_u64(1);
  1917. BigInt max_size = big_int_make_u64(1);
  1918. BigInt bits = big_int_make_i64(bit_size);
  1919. big_int_shl_eq(&max_size, &bits);
  1920. big_int_sub_eq(&max_size, &one);
  1921. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1922. if (size_changed) {
  1923. 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));
  1924. } else {
  1925. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1926. }
  1927. }
  1928. } else {
  1929. BigInt zero = big_int_make_u64(0);
  1930. BigInt one = big_int_make_u64(1);
  1931. BigInt max_size = big_int_make_u64(1);
  1932. BigInt bits = big_int_make_i64(bit_size - 1);
  1933. big_int_shl_eq(&max_size, &bits);
  1934. String max_size_str = {};
  1935. if (big_int_is_neg(bi)) {
  1936. big_int_neg(&max_size, &max_size);
  1937. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1938. } else {
  1939. big_int_sub_eq(&max_size, &one);
  1940. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1941. }
  1942. if (size_changed) {
  1943. 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));
  1944. } else {
  1945. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1946. }
  1947. }
  1948. gb_string_free(b);
  1949. return true;
  1950. }
  1951. return false;
  1952. }
  1953. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  1954. gbString a = expr_to_string(o->expr);
  1955. gbString b = type_to_string(type);
  1956. defer(
  1957. gb_string_free(b);
  1958. gb_string_free(a);
  1959. );
  1960. Type *src = base_type(o->type);
  1961. Type *dst = base_type(type);
  1962. if (is_type_array(src) && is_type_slice(dst)) {
  1963. Type *s = src->Array.elem;
  1964. Type *d = dst->Slice.elem;
  1965. if (are_types_identical(s, d)) {
  1966. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1967. }
  1968. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1969. Type *s = src->DynamicArray.elem;
  1970. Type *d = dst->Slice.elem;
  1971. if (are_types_identical(s, d)) {
  1972. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1973. }
  1974. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1975. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1976. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1977. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1978. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1979. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1980. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1981. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1982. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  1983. return;
  1984. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  1985. gbString s = expr_to_string(c->type_hint_expr);
  1986. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  1987. gb_string_free(s);
  1988. } else if (is_type_pointer(type) &&
  1989. o->mode == Addressing_Variable &&
  1990. are_types_identical(type_deref(type), o->type)) {
  1991. gbString s = expr_to_string(o->expr);
  1992. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  1993. gb_string_free(s);
  1994. } else if (is_type_pointer(o->type) &&
  1995. are_types_identical(type_deref(o->type), type)) {
  1996. gbString s = expr_to_string(o->expr);
  1997. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  1998. gb_string_free(s);
  1999. }
  2000. }
  2001. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2002. gbString a = expr_to_string(o->expr);
  2003. gbString b = type_to_string(type);
  2004. defer(
  2005. gb_string_free(b);
  2006. gb_string_free(a);
  2007. );
  2008. Type *src = base_type(o->type);
  2009. Type *dst = base_type(type);
  2010. if (is_type_array(src) && is_type_slice(dst)) {
  2011. Type *s = src->Array.elem;
  2012. Type *d = dst->Slice.elem;
  2013. if (are_types_identical(s, d)) {
  2014. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2015. }
  2016. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2017. if (is_type_uintptr(type)) {
  2018. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2019. } else {
  2020. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2021. i64 x = type_size_of(o->type);
  2022. i64 y = type_size_of(type);
  2023. if (x != y) {
  2024. 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);
  2025. }
  2026. }
  2027. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2028. if (is_type_uintptr(o->type)) {
  2029. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2030. } else {
  2031. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2032. }
  2033. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2034. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2035. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2036. return;
  2037. }
  2038. }
  2039. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2040. GB_ASSERT(o->mode == Addressing_Constant);
  2041. ExactValue out_value = o->value;
  2042. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2043. o->value = out_value;
  2044. return true;
  2045. } else {
  2046. o->value = out_value;
  2047. gbString a = expr_to_string(o->expr);
  2048. gbString b = type_to_string(type);
  2049. gbString c = type_to_string(o->type);
  2050. gbString s = exact_value_to_string(o->value);
  2051. defer(
  2052. gb_string_free(s);
  2053. gb_string_free(c);
  2054. gb_string_free(b);
  2055. gb_string_free(a);
  2056. o->mode = Addressing_Invalid;
  2057. );
  2058. ERROR_BLOCK();
  2059. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2060. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2061. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2062. } else {
  2063. i64 max_bit_size = 0;
  2064. if (ctx->bit_field_bit_size) {
  2065. max_bit_size = ctx->bit_field_bit_size;
  2066. }
  2067. if (are_types_identical(o->type, type)) {
  2068. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2069. } else {
  2070. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2071. }
  2072. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2073. }
  2074. } else {
  2075. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2076. check_assignment_error_suggestion(ctx, o, type);
  2077. }
  2078. return false;
  2079. }
  2080. }
  2081. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2082. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2083. if (o->expr->SelectorExpr.is_bit_field) {
  2084. return true;
  2085. }
  2086. }
  2087. if (o->mode == Addressing_OptionalOk) {
  2088. Ast *expr = unselector_expr(o->expr);
  2089. if (expr->kind != Ast_TypeAssertion) {
  2090. return true;
  2091. }
  2092. ast_node(ta, TypeAssertion, expr);
  2093. TypeAndValue tv = ta->expr->tav;
  2094. if (is_type_pointer(tv.type)) {
  2095. return false;
  2096. }
  2097. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2098. return false;
  2099. }
  2100. if (is_type_any(tv.type)) {
  2101. return false;
  2102. }
  2103. return true;
  2104. }
  2105. if (o->mode == Addressing_MapIndex) {
  2106. return false;
  2107. }
  2108. Ast *expr = unparen_expr(o->expr);
  2109. if (expr->kind == Ast_CompoundLit) {
  2110. return false;
  2111. }
  2112. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2113. }
  2114. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  2115. Entity *e = entity_of_node(expr);
  2116. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  2117. GB_ASSERT(e->kind == Entity_Variable);
  2118. ERROR_BLOCK();
  2119. if ((e->flags & EntityFlag_ForValue) != 0) {
  2120. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2121. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed.");
  2122. if (is_type_map(parent_type)) {
  2123. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2124. } else {
  2125. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2126. }
  2127. } else {
  2128. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  2129. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed.");
  2130. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2131. }
  2132. }
  2133. }
  2134. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2135. switch (op.kind) {
  2136. case Token_And: { // Pointer address
  2137. if (check_is_not_addressable(c, o)) {
  2138. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2139. ast_node(ue, UnaryExpr, node);
  2140. gbString str = expr_to_string(ue->expr);
  2141. defer (gb_string_free(str));
  2142. Entity *e = entity_of_node(ue->expr);
  2143. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2144. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2145. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2146. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2147. } else {
  2148. switch (o->mode) {
  2149. case Addressing_Constant:
  2150. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2151. break;
  2152. case Addressing_SwizzleValue:
  2153. case Addressing_SwizzleVariable:
  2154. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2155. break;
  2156. default:
  2157. {
  2158. ERROR_BLOCK();
  2159. error(op, "Cannot take the pointer address of '%s'", str);
  2160. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2161. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2162. if (parent_type != nullptr && is_type_string(parent_type)) {
  2163. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2164. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2165. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2166. } else {
  2167. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2168. }
  2169. }
  2170. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2171. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2172. }
  2173. }
  2174. break;
  2175. }
  2176. }
  2177. }
  2178. o->mode = Addressing_Invalid;
  2179. return;
  2180. }
  2181. if (o->mode == Addressing_SoaVariable) {
  2182. ast_node(ue, UnaryExpr, node);
  2183. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2184. ast_node(ie, IndexExpr, ue->expr);
  2185. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2186. GB_ASSERT(is_type_soa_struct(soa_type));
  2187. o->type = alloc_type_soa_pointer(soa_type);
  2188. } else {
  2189. o->type = alloc_type_pointer(o->type);
  2190. }
  2191. } else {
  2192. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2193. ast_node(ue, UnaryExpr, node);
  2194. check_old_for_or_switch_value_usage(ue->expr);
  2195. }
  2196. o->type = alloc_type_pointer(o->type);
  2197. }
  2198. switch (o->mode) {
  2199. case Addressing_OptionalOk:
  2200. case Addressing_MapIndex:
  2201. o->mode = Addressing_OptionalOkPtr;
  2202. break;
  2203. default:
  2204. o->mode = Addressing_Value;
  2205. break;
  2206. }
  2207. return;
  2208. }
  2209. }
  2210. if (!check_unary_op(c, o, op)) {
  2211. o->mode = Addressing_Invalid;
  2212. return;
  2213. }
  2214. if (o->mode == Addressing_Constant) {
  2215. Type *type = base_type(o->type);
  2216. if (!is_type_constant_type(o->type)) {
  2217. gbString xt = type_to_string(o->type);
  2218. gbString err_str = expr_to_string(node);
  2219. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2220. gb_string_free(err_str);
  2221. gb_string_free(xt);
  2222. o->mode = Addressing_Invalid;
  2223. return;
  2224. }
  2225. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2226. gbString err_str = expr_to_string(node);
  2227. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2228. gb_string_free(err_str);
  2229. o->mode = Addressing_Invalid;
  2230. return;
  2231. }
  2232. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2233. gbString err_str = expr_to_string(node);
  2234. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2235. gb_string_free(err_str);
  2236. o->mode = Addressing_Invalid;
  2237. return;
  2238. }
  2239. i32 precision = 0;
  2240. if (is_type_typed(type)) {
  2241. precision = cast(i32)(8 * type_size_of(type));
  2242. }
  2243. bool is_unsigned = is_type_unsigned(type);
  2244. if (is_type_rune(type)) {
  2245. GB_ASSERT(!is_unsigned);
  2246. }
  2247. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2248. if (is_type_typed(type)) {
  2249. if (node != nullptr) {
  2250. o->expr = node;
  2251. }
  2252. check_is_expressible(c, o, type);
  2253. }
  2254. return;
  2255. }
  2256. o->mode = Addressing_Value;
  2257. }
  2258. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2259. if (t == nullptr) {
  2260. return;
  2261. }
  2262. t = base_type(t);
  2263. if (!is_type_comparable(t)) {
  2264. return;
  2265. }
  2266. switch (t->kind) {
  2267. case Type_Basic:
  2268. switch (t->Basic.kind) {
  2269. case Basic_complex32:
  2270. add_package_dependency(c, "runtime", "complex32_eq");
  2271. add_package_dependency(c, "runtime", "complex32_ne");
  2272. break;
  2273. case Basic_complex64:
  2274. add_package_dependency(c, "runtime", "complex64_eq");
  2275. add_package_dependency(c, "runtime", "complex64_ne");
  2276. break;
  2277. case Basic_complex128:
  2278. add_package_dependency(c, "runtime", "complex128_eq");
  2279. add_package_dependency(c, "runtime", "complex128_ne");
  2280. break;
  2281. case Basic_quaternion64:
  2282. add_package_dependency(c, "runtime", "quaternion64_eq");
  2283. add_package_dependency(c, "runtime", "quaternion64_ne");
  2284. break;
  2285. case Basic_quaternion128:
  2286. add_package_dependency(c, "runtime", "quaternion128_eq");
  2287. add_package_dependency(c, "runtime", "quaternion128_ne");
  2288. break;
  2289. case Basic_quaternion256:
  2290. add_package_dependency(c, "runtime", "quaternion256_eq");
  2291. add_package_dependency(c, "runtime", "quaternion256_ne");
  2292. break;
  2293. case Basic_cstring:
  2294. add_package_dependency(c, "runtime", "cstring_eq");
  2295. add_package_dependency(c, "runtime", "cstring_ne");
  2296. break;
  2297. case Basic_string:
  2298. add_package_dependency(c, "runtime", "string_eq");
  2299. add_package_dependency(c, "runtime", "string_ne");
  2300. break;
  2301. }
  2302. break;
  2303. case Type_Struct:
  2304. for (Entity *field : t->Struct.fields) {
  2305. add_comparison_procedures_for_fields(c, field->type);
  2306. }
  2307. break;
  2308. }
  2309. }
  2310. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2311. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2312. bool comp = are_types_identical(x->type, y->type);
  2313. switch (op) {
  2314. case Token_CmpEq: /* comp = comp; */ break;
  2315. case Token_NotEq: comp = !comp; break;
  2316. }
  2317. x->mode = Addressing_Constant;
  2318. x->type = t_untyped_bool;
  2319. x->value = exact_value_bool(comp);
  2320. return;
  2321. }
  2322. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2323. add_type_info_type(c, x->type);
  2324. add_type_info_type(c, y->type);
  2325. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2326. x->mode = Addressing_Value;
  2327. x->type = t_untyped_bool;
  2328. return;
  2329. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2330. add_type_info_type(c, x->type);
  2331. add_type_info_type(c, y->type);
  2332. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2333. x->mode = Addressing_Value;
  2334. x->type = t_untyped_bool;
  2335. return;
  2336. }
  2337. TEMPORARY_ALLOCATOR_GUARD();
  2338. gbString err_str = nullptr;
  2339. if (check_is_assignable_to(c, x, y->type) ||
  2340. check_is_assignable_to(c, y, x->type)) {
  2341. Type *err_type = x->type;
  2342. bool defined = false;
  2343. switch (op) {
  2344. case Token_CmpEq:
  2345. case Token_NotEq:
  2346. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2347. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2348. (is_operand_nil(*y) && type_has_nil(x->type));
  2349. break;
  2350. case Token_Lt:
  2351. case Token_Gt:
  2352. case Token_LtEq:
  2353. case Token_GtEq:
  2354. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2355. defined = true;
  2356. } else {
  2357. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2358. }
  2359. break;
  2360. }
  2361. if (!defined) {
  2362. gbString xs = type_to_string(x->type, temporary_allocator());
  2363. gbString ys = type_to_string(y->type, temporary_allocator());
  2364. err_str = gb_string_make(temporary_allocator(),
  2365. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2366. );
  2367. } else {
  2368. Type *comparison_type = x->type;
  2369. if (x->type == err_type && is_operand_nil(*x)) {
  2370. comparison_type = y->type;
  2371. }
  2372. add_comparison_procedures_for_fields(c, comparison_type);
  2373. }
  2374. } else {
  2375. gbString xt, yt;
  2376. if (x->mode == Addressing_ProcGroup) {
  2377. xt = gb_string_make(temporary_allocator(), "procedure group");
  2378. } else {
  2379. xt = type_to_string(x->type);
  2380. }
  2381. if (y->mode == Addressing_ProcGroup) {
  2382. yt = gb_string_make(temporary_allocator(), "procedure group");
  2383. } else {
  2384. yt = type_to_string(y->type);
  2385. }
  2386. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2387. }
  2388. if (err_str != nullptr) {
  2389. error(node, "Cannot compare expression, %s", err_str);
  2390. x->type = t_untyped_bool;
  2391. } else {
  2392. if (x->mode == Addressing_Constant &&
  2393. y->mode == Addressing_Constant) {
  2394. if (is_type_constant_type(x->type)) {
  2395. if (is_type_bit_set(x->type)) {
  2396. switch (op) {
  2397. case Token_CmpEq:
  2398. case Token_NotEq:
  2399. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2400. break;
  2401. case Token_Lt:
  2402. case Token_LtEq:
  2403. {
  2404. ExactValue lhs = x->value;
  2405. ExactValue rhs = y->value;
  2406. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2407. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2408. if (op == Token_Lt) {
  2409. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2410. }
  2411. x->value = res;
  2412. break;
  2413. }
  2414. case Token_Gt:
  2415. case Token_GtEq:
  2416. {
  2417. ExactValue lhs = x->value;
  2418. ExactValue rhs = y->value;
  2419. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2420. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2421. if (op == Token_Gt) {
  2422. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2423. }
  2424. x->value = res;
  2425. break;
  2426. }
  2427. }
  2428. } else {
  2429. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2430. }
  2431. } else {
  2432. x->mode = Addressing_Value;
  2433. }
  2434. } else {
  2435. x->mode = Addressing_Value;
  2436. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2437. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2438. i64 size = 0;
  2439. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2440. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2441. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2442. switch (op) {
  2443. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2444. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2445. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2446. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2447. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2448. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2449. }
  2450. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2451. switch (op) {
  2452. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2453. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2454. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2455. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2456. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2457. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2458. }
  2459. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2460. switch (op) {
  2461. case Token_CmpEq:
  2462. switch (8*size) {
  2463. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2464. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2465. }
  2466. break;
  2467. case Token_NotEq:
  2468. switch (8*size) {
  2469. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2470. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2471. }
  2472. break;
  2473. }
  2474. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2475. switch (op) {
  2476. case Token_CmpEq:
  2477. switch (8*size) {
  2478. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2479. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2480. }
  2481. break;
  2482. case Token_NotEq:
  2483. switch (8*size) {
  2484. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2485. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2486. }
  2487. break;
  2488. }
  2489. }
  2490. }
  2491. x->type = t_untyped_bool;
  2492. }
  2493. }
  2494. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2495. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2496. ast_node(be, BinaryExpr, node);
  2497. ExactValue x_val = {};
  2498. if (x->mode == Addressing_Constant) {
  2499. x_val = exact_value_to_integer(x->value);
  2500. }
  2501. bool x_is_untyped = is_type_untyped(x->type);
  2502. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2503. gbString err_str = expr_to_string(x->expr);
  2504. error(node, "Shifted operand '%s' must be an integer", err_str);
  2505. gb_string_free(err_str);
  2506. x->mode = Addressing_Invalid;
  2507. return;
  2508. }
  2509. if (is_type_unsigned(y->type)) {
  2510. } else if (is_type_untyped(y->type)) {
  2511. convert_to_typed(c, y, t_untyped_integer);
  2512. if (y->mode == Addressing_Invalid) {
  2513. x->mode = Addressing_Invalid;
  2514. return;
  2515. }
  2516. } else {
  2517. gbString err_str = expr_to_string(y->expr);
  2518. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2519. gb_string_free(err_str);
  2520. x->mode = Addressing_Invalid;
  2521. return;
  2522. }
  2523. if (x->mode == Addressing_Constant) {
  2524. if (y->mode == Addressing_Constant) {
  2525. ExactValue y_val = exact_value_to_integer(y->value);
  2526. if (y_val.kind != ExactValue_Integer) {
  2527. gbString err_str = expr_to_string(y->expr);
  2528. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2529. gb_string_free(err_str);
  2530. x->mode = Addressing_Invalid;
  2531. return;
  2532. }
  2533. BigInt max_shift = {};
  2534. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2535. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2536. gbString err_str = expr_to_string(y->expr);
  2537. error(node, "Shift amount too large: '%s'", err_str);
  2538. gb_string_free(err_str);
  2539. x->mode = Addressing_Invalid;
  2540. return;
  2541. }
  2542. if (!is_type_integer(x->type)) {
  2543. // NOTE(bill): It could be an untyped float but still representable
  2544. // as an integer
  2545. x->type = t_untyped_integer;
  2546. }
  2547. x->expr = node;
  2548. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2549. if (is_type_typed(x->type)) {
  2550. check_is_expressible(c, x, x->type);
  2551. }
  2552. return;
  2553. }
  2554. TokenPos pos = ast_token(x->expr).pos;
  2555. if (x_is_untyped) {
  2556. if (x->expr != nullptr) {
  2557. x->expr->tav.is_lhs = true;
  2558. }
  2559. x->mode = Addressing_Value;
  2560. if (type_hint) {
  2561. if (is_type_integer(type_hint)) {
  2562. x->type = type_hint;
  2563. } else {
  2564. gbString x_str = expr_to_string(x->expr);
  2565. gbString to_type = type_to_string(type_hint);
  2566. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2567. gb_string_free(x_str);
  2568. gb_string_free(to_type);
  2569. x->mode = Addressing_Invalid;
  2570. }
  2571. } else if (!is_type_integer(x->type)) {
  2572. gbString x_str = expr_to_string(x->expr);
  2573. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2574. gb_string_free(x_str);
  2575. x->mode = Addressing_Invalid;
  2576. }
  2577. // x->value = x_val;
  2578. return;
  2579. }
  2580. }
  2581. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2582. gbString err_str = expr_to_string(y->expr);
  2583. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2584. gb_string_free(err_str);
  2585. }
  2586. if (!is_type_integer(x->type)) {
  2587. gbString err_str = expr_to_string(x->expr);
  2588. error(node, "Shift operand '%s' must be an integer", err_str);
  2589. gb_string_free(err_str);
  2590. x->mode = Addressing_Invalid;
  2591. return;
  2592. }
  2593. if (is_type_untyped(y->type)) {
  2594. convert_to_typed(c, y, t_uint);
  2595. }
  2596. x->mode = Addressing_Value;
  2597. }
  2598. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2599. if (check_is_assignable_to(c, operand, y)) {
  2600. return true;
  2601. }
  2602. bool is_constant = operand->mode == Addressing_Constant;
  2603. Type *x = operand->type;
  2604. Type *src = core_type(x);
  2605. Type *dst = core_type(y);
  2606. if (are_types_identical(src, dst)) {
  2607. return true;
  2608. }
  2609. // if (is_type_tuple(src)) {
  2610. // Ast *expr = unparen_expr(operand->expr);
  2611. // if (expr && expr->kind == Ast_CallExpr) {
  2612. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2613. // ast_node(ce, CallExpr, expr);
  2614. // Type *pt = base_type(type_of_expr(ce->proc));
  2615. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2616. // if (pt->Proc.result_count > 0) {
  2617. // Operand op = *operand;
  2618. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2619. // bool ok = check_is_castable_to(c, &op, y);
  2620. // if (ok) {
  2621. // ce->optional_ok_one = true;
  2622. // }
  2623. // return ok;
  2624. // }
  2625. // }
  2626. // }
  2627. // }
  2628. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2629. if (is_type_u8_array(dst)) {
  2630. String s = operand->value.value_string;
  2631. return s.len == dst->Array.count;
  2632. }
  2633. if (is_type_rune_array(dst)) {
  2634. String s = operand->value.value_string;
  2635. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2636. }
  2637. }
  2638. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2639. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2640. return dst->Array.count == src->Array.count;
  2641. }
  2642. }
  2643. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2644. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2645. }
  2646. // Cast between booleans and integers
  2647. if (is_type_boolean(src) || is_type_integer(src)) {
  2648. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2649. return true;
  2650. }
  2651. }
  2652. // Cast between numbers
  2653. if (is_type_integer(src) || is_type_float(src)) {
  2654. if (is_type_integer(dst) || is_type_float(dst)) {
  2655. return true;
  2656. }
  2657. }
  2658. if (is_type_bit_field(src)) {
  2659. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2660. }
  2661. if (is_type_bit_field(dst)) {
  2662. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2663. }
  2664. if (is_type_integer(src) && is_type_rune(dst)) {
  2665. return true;
  2666. }
  2667. if (is_type_rune(src) && is_type_integer(dst)) {
  2668. return true;
  2669. }
  2670. if (is_type_complex(src) && is_type_complex(dst)) {
  2671. return true;
  2672. }
  2673. if (is_type_float(src) && is_type_complex(dst)) {
  2674. return true;
  2675. }
  2676. if (is_type_float(src) && is_type_quaternion(dst)) {
  2677. return true;
  2678. }
  2679. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2680. return true;
  2681. }
  2682. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2683. return true;
  2684. }
  2685. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2686. GB_ASSERT(src->kind == Type_Matrix);
  2687. GB_ASSERT(dst->kind == Type_Matrix);
  2688. Operand op = *operand;
  2689. op.type = src->Matrix.elem;
  2690. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2691. return false;
  2692. }
  2693. if (src->Matrix.row_count != src->Matrix.column_count) {
  2694. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2695. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2696. return src_count == dst_count;
  2697. }
  2698. return is_matrix_square(dst) && is_matrix_square(src);
  2699. }
  2700. // Cast between pointers
  2701. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2702. return true;
  2703. }
  2704. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2705. return true;
  2706. }
  2707. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2708. return true;
  2709. }
  2710. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2711. return true;
  2712. }
  2713. // uintptr <-> pointer
  2714. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2715. return true;
  2716. }
  2717. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2718. return true;
  2719. }
  2720. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2721. return true;
  2722. }
  2723. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2724. return true;
  2725. }
  2726. // []byte/[]u8 <-> string (not cstring)
  2727. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2728. return true;
  2729. }
  2730. // cstring -> string
  2731. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2732. if (operand->mode != Addressing_Constant) {
  2733. add_package_dependency(c, "runtime", "cstring_to_string");
  2734. }
  2735. return true;
  2736. }
  2737. // cstring -> ^u8
  2738. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2739. return !is_constant;
  2740. }
  2741. // cstring -> [^]u8
  2742. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2743. return !is_constant;
  2744. }
  2745. // cstring -> rawptr
  2746. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2747. return !is_constant;
  2748. }
  2749. // ^u8 -> cstring
  2750. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2751. return !is_constant;
  2752. }
  2753. // [^]u8 -> cstring
  2754. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2755. return !is_constant;
  2756. }
  2757. // rawptr -> cstring
  2758. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2759. return !is_constant;
  2760. }
  2761. // proc <-> proc
  2762. if (is_type_proc(src) && is_type_proc(dst)) {
  2763. if (is_type_polymorphic(dst)) {
  2764. if (is_type_polymorphic(src) &&
  2765. operand->mode == Addressing_Variable) {
  2766. return true;
  2767. }
  2768. return false;
  2769. }
  2770. return true;
  2771. }
  2772. // proc -> rawptr
  2773. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2774. return true;
  2775. }
  2776. // rawptr -> proc
  2777. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2778. return true;
  2779. }
  2780. if (is_type_array(dst)) {
  2781. Type *elem = base_array_type(dst);
  2782. if (check_is_castable_to(c, operand, elem)) {
  2783. return true;
  2784. }
  2785. }
  2786. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2787. if (src->SimdVector.count != dst->SimdVector.count) {
  2788. return false;
  2789. }
  2790. Type *elem_src = base_array_type(src);
  2791. Type *elem_dst = base_array_type(dst);
  2792. Operand x = {};
  2793. x.type = elem_src;
  2794. x.mode = Addressing_Value;
  2795. return check_is_castable_to(c, &x, elem_dst);
  2796. }
  2797. if (is_type_simd_vector(dst)) {
  2798. Type *elem = base_array_type(dst);
  2799. if (check_is_castable_to(c, operand, elem)) {
  2800. return true;
  2801. }
  2802. }
  2803. return false;
  2804. }
  2805. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2806. bool is_const_expr = x->mode == Addressing_Constant;
  2807. Type *bt = base_type(type);
  2808. if (is_const_expr && is_type_constant_type(bt)) {
  2809. if (core_type(bt)->kind == Type_Basic) {
  2810. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2811. return true;
  2812. } else if (check_is_castable_to(c, x, type)) {
  2813. if (is_type_pointer(type)) {
  2814. return true;
  2815. }
  2816. }
  2817. } else if (check_is_castable_to(c, x, type)) {
  2818. x->value = {};
  2819. x->mode = Addressing_Value;
  2820. return true;
  2821. }
  2822. } else if (check_is_castable_to(c, x, type)) {
  2823. if (x->mode != Addressing_Constant) {
  2824. x->mode = Addressing_Value;
  2825. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2826. x->mode = Addressing_Value;
  2827. } else if (is_type_union(type)) {
  2828. x->mode = Addressing_Value;
  2829. }
  2830. if (x->mode == Addressing_Value) {
  2831. x->value = {};
  2832. }
  2833. return true;
  2834. }
  2835. return false;
  2836. }
  2837. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2838. if (!is_operand_value(*x)) {
  2839. error(x->expr, "Only values can be casted");
  2840. x->mode = Addressing_Invalid;
  2841. return;
  2842. }
  2843. bool is_const_expr = x->mode == Addressing_Constant;
  2844. bool can_convert = check_cast_internal(c, x, type);
  2845. if (!can_convert) {
  2846. TEMPORARY_ALLOCATOR_GUARD();
  2847. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2848. gbString to_type = type_to_string(type, temporary_allocator());
  2849. gbString from_type = type_to_string(x->type, temporary_allocator());
  2850. x->mode = Addressing_Invalid;
  2851. ERROR_BLOCK();
  2852. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2853. if (is_const_expr) {
  2854. gbString val_str = exact_value_to_string(x->value);
  2855. if (is_type_float(x->type) && is_type_integer(type)) {
  2856. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2857. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2858. x->mode = Addressing_Constant;
  2859. x->type = type;
  2860. } else {
  2861. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2862. if (is_type_numeric(type)) {
  2863. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2864. x->mode = Addressing_Constant;
  2865. x->type = type;
  2866. }
  2867. }
  2868. gb_string_free(val_str);
  2869. }
  2870. check_cast_error_suggestion(c, x, type);
  2871. return;
  2872. }
  2873. if (is_type_untyped(x->type)) {
  2874. Type *final_type = type;
  2875. if (is_const_expr && !is_type_constant_type(type)) {
  2876. final_type = default_type(x->type);
  2877. }
  2878. update_untyped_expr_type(c, x->expr, final_type, true);
  2879. } else {
  2880. Type *src = core_type(x->type);
  2881. Type *dst = core_type(type);
  2882. if (src != dst) {
  2883. bool const REQUIRE = true;
  2884. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  2885. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  2886. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  2887. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  2888. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  2889. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  2890. } else if (src == t_f16 && is_type_float(dst)) {
  2891. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  2892. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  2893. } else if (is_type_float(dst) && dst == t_f16) {
  2894. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  2895. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  2896. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  2897. }
  2898. }
  2899. }
  2900. x->type = type;
  2901. }
  2902. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2903. if (!is_operand_value(*o)) {
  2904. error(o->expr, "'transmute' can only be applied to values");
  2905. o->mode = Addressing_Invalid;
  2906. return false;
  2907. }
  2908. // if (o->mode == Addressing_Constant) {
  2909. // gbString expr_str = expr_to_string(o->expr);
  2910. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2911. // gb_string_free(expr_str);
  2912. // o->mode = Addressing_Invalid;
  2913. // o->expr = node;
  2914. // return false;
  2915. // }
  2916. Type *src_t = o->type;
  2917. Type *dst_t = t;
  2918. Type *src_bt = base_type(src_t);
  2919. Type *dst_bt = base_type(dst_t);
  2920. if (is_type_untyped(src_t)) {
  2921. gbString expr_str = expr_to_string(o->expr);
  2922. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2923. gb_string_free(expr_str);
  2924. o->mode = Addressing_Invalid;
  2925. o->expr = node;
  2926. return false;
  2927. }
  2928. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2929. GB_ASSERT(global_error_collector.count != 0);
  2930. o->mode = Addressing_Invalid;
  2931. o->expr = node;
  2932. return false;
  2933. }
  2934. if (src_bt == nullptr || src_bt == t_invalid) {
  2935. // NOTE(bill): this should be an error
  2936. GB_ASSERT(global_error_collector.count != 0);
  2937. o->mode = Addressing_Value;
  2938. o->expr = node;
  2939. o->type = dst_t;
  2940. return true;
  2941. }
  2942. i64 srcz = type_size_of(src_t);
  2943. i64 dstz = type_size_of(dst_t);
  2944. if (srcz != dstz) {
  2945. gbString expr_str = expr_to_string(o->expr);
  2946. gbString type_str = type_to_string(dst_t);
  2947. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2948. gb_string_free(type_str);
  2949. gb_string_free(expr_str);
  2950. o->mode = Addressing_Invalid;
  2951. o->expr = node;
  2952. return false;
  2953. }
  2954. o->expr = node;
  2955. o->type = dst_t;
  2956. if (o->mode == Addressing_Constant) {
  2957. if (are_types_identical(src_bt, dst_bt)) {
  2958. return true;
  2959. }
  2960. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2961. if (types_have_same_internal_endian(src_t, dst_t)) {
  2962. ExactValue src_v = exact_value_to_integer(o->value);
  2963. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2964. BigInt v = src_v.value_integer;
  2965. BigInt smax = {};
  2966. BigInt umax = {};
  2967. big_int_from_u64(&smax, 0);
  2968. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2969. big_int_from_u64(&umax, 1);
  2970. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2971. big_int_shl_eq(&umax, &sz_in_bits);
  2972. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2973. if (big_int_cmp(&v, &smax) >= 0) {
  2974. big_int_sub_eq(&v, &umax);
  2975. }
  2976. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2977. if (big_int_is_neg(&v)) {
  2978. big_int_add_eq(&v, &umax);
  2979. }
  2980. }
  2981. o->value.kind = ExactValue_Integer;
  2982. o->value.value_integer = v;
  2983. return true;
  2984. }
  2985. }
  2986. }
  2987. o->mode = Addressing_Value;
  2988. o->value = {};
  2989. return true;
  2990. }
  2991. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2992. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2993. if (check_is_assignable_to(c, y, x->type)) {
  2994. if (check_binary_op(c, x, op)) {
  2995. return true;
  2996. }
  2997. }
  2998. }
  2999. return false;
  3000. }
  3001. gb_internal bool is_ise_expr(Ast *node) {
  3002. node = unparen_expr(node);
  3003. return node->kind == Ast_ImplicitSelectorExpr;
  3004. }
  3005. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3006. if (use_lhs_as_type_hint) { // RHS in this case
  3007. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3008. }
  3009. return false;
  3010. }
  3011. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3012. Type *xt = base_type(matrix);
  3013. if (type_hint != nullptr) {
  3014. Type *th = base_type(type_hint);
  3015. if (are_types_identical(th, xt)) {
  3016. return type_hint;
  3017. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3018. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3019. // ignore
  3020. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3021. xt->Matrix.column_count == th->Matrix.column_count) {
  3022. return type_hint;
  3023. }
  3024. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3025. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3026. // ignore
  3027. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3028. return type_hint;
  3029. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3030. return type_hint;
  3031. }
  3032. }
  3033. }
  3034. return matrix;
  3035. }
  3036. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3037. if (!check_binary_op(c, x, op)) {
  3038. x->mode = Addressing_Invalid;
  3039. return;
  3040. }
  3041. Type *xt = base_type(x->type);
  3042. Type *yt = base_type(y->type);
  3043. if (is_type_matrix(x->type)) {
  3044. GB_ASSERT(xt->kind == Type_Matrix);
  3045. if (op.kind == Token_Mul) {
  3046. if (yt->kind == Type_Matrix) {
  3047. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3048. goto matrix_error;
  3049. }
  3050. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3051. goto matrix_error;
  3052. }
  3053. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3054. goto matrix_error;
  3055. }
  3056. x->mode = Addressing_Value;
  3057. if (are_types_identical(xt, yt)) {
  3058. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3059. // prefer the named type
  3060. x->type = y->type;
  3061. }
  3062. } else {
  3063. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3064. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3065. }
  3066. goto matrix_success;
  3067. } else if (yt->kind == Type_Array) {
  3068. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3069. goto matrix_error;
  3070. }
  3071. if (xt->Matrix.column_count != yt->Array.count) {
  3072. goto matrix_error;
  3073. }
  3074. // Treat arrays as column vectors
  3075. x->mode = Addressing_Value;
  3076. if (xt->Matrix.row_count == yt->Array.count) {
  3077. x->type = y->type;
  3078. } else {
  3079. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3080. }
  3081. goto matrix_success;
  3082. }
  3083. }
  3084. if (!are_types_identical(xt, yt)) {
  3085. goto matrix_error;
  3086. }
  3087. x->mode = Addressing_Value;
  3088. x->type = xt;
  3089. goto matrix_success;
  3090. } else {
  3091. GB_ASSERT(!is_type_matrix(xt));
  3092. GB_ASSERT(is_type_matrix(yt));
  3093. if (op.kind == Token_Mul) {
  3094. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3095. if (xt->kind == Type_Array) {
  3096. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3097. goto matrix_error;
  3098. }
  3099. if (xt->Array.count != yt->Matrix.row_count) {
  3100. goto matrix_error;
  3101. }
  3102. // Treat arrays as row vectors
  3103. x->mode = Addressing_Value;
  3104. if (yt->Matrix.column_count == xt->Array.count) {
  3105. x->type = x->type;
  3106. } else {
  3107. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3108. }
  3109. goto matrix_success;
  3110. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3111. x->type = check_matrix_type_hint(y->type, type_hint);
  3112. return;
  3113. }
  3114. }
  3115. if (!are_types_identical(xt, yt)) {
  3116. goto matrix_error;
  3117. }
  3118. x->mode = Addressing_Value;
  3119. x->type = xt;
  3120. goto matrix_success;
  3121. }
  3122. matrix_success:
  3123. x->type = check_matrix_type_hint(x->type, type_hint);
  3124. return;
  3125. matrix_error:
  3126. gbString xts = type_to_string(x->type);
  3127. gbString yts = type_to_string(y->type);
  3128. gbString expr_str = expr_to_string(x->expr);
  3129. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3130. gb_string_free(expr_str);
  3131. gb_string_free(yts);
  3132. gb_string_free(xts);
  3133. x->type = t_invalid;
  3134. x->mode = Addressing_Invalid;
  3135. return;
  3136. }
  3137. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3138. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3139. Operand y_ = {}, *y = &y_;
  3140. ast_node(be, BinaryExpr, node);
  3141. defer({
  3142. node->viral_state_flags |= be->left->viral_state_flags;
  3143. node->viral_state_flags |= be->right->viral_state_flags;
  3144. });
  3145. Token op = be->op;
  3146. switch (op.kind) {
  3147. case Token_CmpEq:
  3148. case Token_NotEq: {
  3149. // NOTE(bill): Allow comparisons between types
  3150. if (is_ise_expr(be->left)) {
  3151. // Evalute the right before the left for an '.X' expression
  3152. check_expr_or_type(c, y, be->right, type_hint);
  3153. check_expr_or_type(c, x, be->left, y->type);
  3154. } else {
  3155. check_expr_or_type(c, x, be->left, type_hint);
  3156. check_expr_or_type(c, y, be->right, x->type);
  3157. }
  3158. bool xt = x->mode == Addressing_Type;
  3159. bool yt = y->mode == Addressing_Type;
  3160. // If only one is a type, this is an error
  3161. if (xt ^ yt) {
  3162. GB_ASSERT(xt != yt);
  3163. if (xt) {
  3164. if (!is_type_typeid(y->type)) {
  3165. error_operand_not_expression(x);
  3166. }
  3167. }
  3168. if (yt) {
  3169. if (!is_type_typeid(x->type)) {
  3170. error_operand_not_expression(y);
  3171. }
  3172. }
  3173. }
  3174. break;
  3175. }
  3176. case Token_in:
  3177. case Token_not_in:
  3178. {
  3179. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3180. check_expr(c, y, be->right);
  3181. Type *rhs_type = type_deref(y->type);
  3182. if (is_type_bit_set(rhs_type)) {
  3183. Type *elem = base_type(rhs_type)->BitSet.elem;
  3184. check_expr_with_type_hint(c, x, be->left, elem);
  3185. } else if (is_type_map(rhs_type)) {
  3186. Type *key = base_type(rhs_type)->Map.key;
  3187. check_expr_with_type_hint(c, x, be->left, key);
  3188. } else {
  3189. check_expr(c, x, be->left);
  3190. }
  3191. if (x->mode == Addressing_Invalid) {
  3192. return;
  3193. }
  3194. if (y->mode == Addressing_Invalid) {
  3195. x->mode = Addressing_Invalid;
  3196. x->expr = y->expr;
  3197. return;
  3198. }
  3199. if (is_type_map(rhs_type)) {
  3200. Type *yt = base_type(rhs_type);
  3201. if (op.kind == Token_in) {
  3202. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3203. } else {
  3204. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3205. }
  3206. add_map_get_dependencies(c);
  3207. } else if (is_type_bit_set(rhs_type)) {
  3208. Type *yt = base_type(rhs_type);
  3209. if (op.kind == Token_in) {
  3210. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3211. } else {
  3212. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3213. }
  3214. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3215. ExactValue k = exact_value_to_integer(x->value);
  3216. ExactValue v = exact_value_to_integer(y->value);
  3217. GB_ASSERT(k.kind == ExactValue_Integer);
  3218. GB_ASSERT(v.kind == ExactValue_Integer);
  3219. i64 key = big_int_to_i64(&k.value_integer);
  3220. i64 lower = yt->BitSet.lower;
  3221. i64 upper = yt->BitSet.upper;
  3222. if (lower <= key && key <= upper) {
  3223. i64 bit = 1ll<<key;
  3224. i64 bits = big_int_to_i64(&v.value_integer);
  3225. x->mode = Addressing_Constant;
  3226. x->type = t_untyped_bool;
  3227. if (op.kind == Token_in) {
  3228. x->value = exact_value_bool((bit & bits) != 0);
  3229. } else {
  3230. x->value = exact_value_bool((bit & bits) == 0);
  3231. }
  3232. x->expr = node;
  3233. return;
  3234. } else {
  3235. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3236. x->mode = Addressing_Invalid;
  3237. }
  3238. }
  3239. } else {
  3240. gbString t = type_to_string(y->type);
  3241. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3242. gb_string_free(t);
  3243. x->expr = node;
  3244. x->mode = Addressing_Invalid;
  3245. return;
  3246. }
  3247. if (x->mode != Addressing_Invalid) {
  3248. x->mode = Addressing_Value;
  3249. x->type = t_untyped_bool;
  3250. }
  3251. x->expr = node;
  3252. return;
  3253. }
  3254. default:
  3255. if (is_ise_expr(be->left)) {
  3256. // Evalute the right before the left for an '.X' expression
  3257. check_expr_or_type(c, y, be->right, type_hint);
  3258. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3259. check_expr_or_type(c, x, be->left, y->type);
  3260. } else {
  3261. check_expr_with_type_hint(c, x, be->left, type_hint);
  3262. }
  3263. } else {
  3264. check_expr_with_type_hint(c, x, be->left, type_hint);
  3265. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3266. check_expr_with_type_hint(c, y, be->right, x->type);
  3267. } else {
  3268. check_expr_with_type_hint(c, y, be->right, type_hint);
  3269. }
  3270. }
  3271. break;
  3272. }
  3273. if (x->mode == Addressing_Invalid) {
  3274. return;
  3275. }
  3276. if (y->mode == Addressing_Invalid) {
  3277. x->mode = Addressing_Invalid;
  3278. x->expr = y->expr;
  3279. return;
  3280. }
  3281. if (x->mode == Addressing_Builtin) {
  3282. x->mode = Addressing_Invalid;
  3283. error(x->expr, "built-in expression in binary expression");
  3284. return;
  3285. }
  3286. if (y->mode == Addressing_Builtin) {
  3287. x->mode = Addressing_Invalid;
  3288. error(y->expr, "built-in expression in binary expression");
  3289. return;
  3290. }
  3291. if (x->mode == Addressing_ProcGroup) {
  3292. x->mode = Addressing_Invalid;
  3293. if (x->proc_group != nullptr) {
  3294. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3295. } else {
  3296. error(x->expr, "procedure group used in binary expression");
  3297. }
  3298. return;
  3299. }
  3300. if (y->mode == Addressing_ProcGroup) {
  3301. x->mode = Addressing_Invalid;
  3302. if (x->proc_group != nullptr) {
  3303. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3304. } else {
  3305. error(y->expr, "procedure group used in binary expression");
  3306. }
  3307. return;
  3308. }
  3309. if (token_is_shift(op.kind)) {
  3310. check_shift(c, x, y, node, type_hint);
  3311. return;
  3312. }
  3313. switch (op.kind) {
  3314. case Token_Quo:
  3315. case Token_Mod:
  3316. case Token_ModMod:
  3317. case Token_QuoEq:
  3318. case Token_ModEq:
  3319. case Token_ModModEq:
  3320. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3321. is_type_float(x->type) && is_type_untyped(x->type)) {
  3322. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3323. gbString t = type_to_string(y->type);
  3324. if (x->value.kind != ExactValue_Invalid) {
  3325. gbString s = exact_value_to_string(x->value);
  3326. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3327. gb_string_free(s);
  3328. } else {
  3329. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3330. }
  3331. gb_string_free(t);
  3332. }
  3333. break;
  3334. }
  3335. convert_to_typed(c, x, y->type);
  3336. if (x->mode == Addressing_Invalid) {
  3337. return;
  3338. }
  3339. convert_to_typed(c, y, x->type);
  3340. if (y->mode == Addressing_Invalid) {
  3341. x->mode = Addressing_Invalid;
  3342. return;
  3343. }
  3344. if (token_is_comparison(op.kind)) {
  3345. check_comparison(c, node, x, y, op.kind);
  3346. return;
  3347. }
  3348. if (check_binary_array_expr(c, op, x, y)) {
  3349. x->mode = Addressing_Value;
  3350. x->type = x->type;
  3351. return;
  3352. }
  3353. if (check_binary_array_expr(c, op, y, x)) {
  3354. x->mode = Addressing_Value;
  3355. x->type = y->type;
  3356. return;
  3357. }
  3358. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3359. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3360. x->expr = node;
  3361. return;
  3362. }
  3363. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3364. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3365. // NOTE(bill, 2022-06-26)
  3366. // Allow any boolean types within `&&` and `||`
  3367. // This is an exception to all other binary expressions since the result
  3368. // of a comparison will always be an untyped boolean, and allowing
  3369. // any boolean between these two simplifies a lot of expressions
  3370. } else if (!are_types_identical(x->type, y->type)) {
  3371. if (x->type != t_invalid &&
  3372. y->type != t_invalid) {
  3373. gbString xt = type_to_string(x->type);
  3374. gbString yt = type_to_string(y->type);
  3375. gbString expr_str = expr_to_string(node);
  3376. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3377. gb_string_free(expr_str);
  3378. gb_string_free(yt);
  3379. gb_string_free(xt);
  3380. }
  3381. x->mode = Addressing_Invalid;
  3382. return;
  3383. }
  3384. if (!check_binary_op(c, x, op)) {
  3385. x->mode = Addressing_Invalid;
  3386. return;
  3387. }
  3388. switch (op.kind) {
  3389. case Token_Quo:
  3390. case Token_Mod:
  3391. case Token_ModMod:
  3392. case Token_QuoEq:
  3393. case Token_ModEq:
  3394. case Token_ModModEq:
  3395. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3396. y->mode == Addressing_Constant) {
  3397. bool fail = false;
  3398. switch (y->value.kind) {
  3399. case ExactValue_Integer:
  3400. if (big_int_is_zero(&y->value.value_integer)) {
  3401. fail = true;
  3402. }
  3403. break;
  3404. case ExactValue_Float:
  3405. if (y->value.value_float == 0.0) {
  3406. fail = true;
  3407. }
  3408. break;
  3409. }
  3410. if (fail) {
  3411. error(y->expr, "Division by zero not allowed");
  3412. x->mode = Addressing_Invalid;
  3413. return;
  3414. }
  3415. }
  3416. break;
  3417. case Token_CmpAnd:
  3418. case Token_CmpOr:
  3419. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3420. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3421. }
  3422. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3423. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3424. }
  3425. break;
  3426. }
  3427. if (x->mode == Addressing_Constant &&
  3428. y->mode == Addressing_Constant) {
  3429. ExactValue a = x->value;
  3430. ExactValue b = y->value;
  3431. if (!is_type_constant_type(x->type)) {
  3432. x->mode = Addressing_Value;
  3433. return;
  3434. }
  3435. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3436. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3437. }
  3438. if (is_type_bit_set(x->type)) {
  3439. switch (op.kind) {
  3440. case Token_Add: op.kind = Token_Or; break;
  3441. case Token_Sub: op.kind = Token_AndNot; break;
  3442. }
  3443. }
  3444. x->value = exact_binary_operator_value(op.kind, a, b);
  3445. if (is_type_typed(x->type)) {
  3446. if (node != nullptr) {
  3447. x->expr = node;
  3448. }
  3449. check_is_expressible(c, x, x->type);
  3450. }
  3451. return;
  3452. } else if (is_type_string(x->type)) {
  3453. error(node, "String concatenation is only allowed with constant strings");
  3454. x->mode = Addressing_Invalid;
  3455. return;
  3456. }
  3457. bool REQUIRE = true;
  3458. Type *bt = base_type(x->type);
  3459. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3460. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3461. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3462. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3463. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3464. }
  3465. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3466. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3467. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3468. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3469. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3470. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3471. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3472. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3473. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3474. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3475. }
  3476. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3477. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3478. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3479. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3480. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3481. case Basic_u128:
  3482. case Basic_i128:
  3483. if (is_arch_wasm()) {
  3484. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3485. }
  3486. break;
  3487. }
  3488. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3489. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3490. case Basic_u128:
  3491. case Basic_i128:
  3492. if (is_arch_wasm()) {
  3493. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3494. }
  3495. break;
  3496. }
  3497. }
  3498. x->mode = Addressing_Value;
  3499. }
  3500. gb_internal Operand make_operand_from_node(Ast *node) {
  3501. GB_ASSERT(node != nullptr);
  3502. Operand x = {};
  3503. x.expr = node;
  3504. x.mode = node->tav.mode;
  3505. x.type = node->tav.type;
  3506. x.value = node->tav.value;
  3507. return x;
  3508. }
  3509. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3510. GB_ASSERT(e != nullptr);
  3511. ExprInfo *old = check_get_expr_info(c, e);
  3512. if (old == nullptr) {
  3513. if (type != nullptr && type != t_invalid) {
  3514. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3515. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3516. if (e->kind == Ast_TernaryIfExpr) {
  3517. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3518. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3519. }
  3520. }
  3521. }
  3522. return;
  3523. }
  3524. switch (e->kind) {
  3525. case_ast_node(ue, UnaryExpr, e);
  3526. if (old->value.kind != ExactValue_Invalid) {
  3527. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3528. // They don't need to be updated as they will be updated later and
  3529. // checked at the end of general checking stage.
  3530. break;
  3531. }
  3532. update_untyped_expr_type(c, ue->expr, type, final);
  3533. case_end;
  3534. case_ast_node(be, BinaryExpr, e);
  3535. if (old->value.kind != ExactValue_Invalid) {
  3536. // See above note in UnaryExpr case
  3537. break;
  3538. }
  3539. if (token_is_comparison(be->op.kind)) {
  3540. // NOTE(bill): Do nothing as the types are fine
  3541. } else if (token_is_shift(be->op.kind)) {
  3542. update_untyped_expr_type(c, be->left, type, final);
  3543. } else {
  3544. update_untyped_expr_type(c, be->left, type, final);
  3545. update_untyped_expr_type(c, be->right, type, final);
  3546. }
  3547. case_end;
  3548. case_ast_node(te, TernaryIfExpr, e);
  3549. if (old->value.kind != ExactValue_Invalid) {
  3550. // See above note in UnaryExpr case
  3551. break;
  3552. }
  3553. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3554. // having an untyped value
  3555. Operand x = make_operand_from_node(te->x);
  3556. Operand y = make_operand_from_node(te->y);
  3557. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3558. update_untyped_expr_type(c, te->x, type, final);
  3559. }
  3560. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3561. update_untyped_expr_type(c, te->y, type, final);
  3562. }
  3563. case_end;
  3564. case_ast_node(te, TernaryWhenExpr, e);
  3565. if (old->value.kind != ExactValue_Invalid) {
  3566. // See above note in UnaryExpr case
  3567. break;
  3568. }
  3569. update_untyped_expr_type(c, te->x, type, final);
  3570. update_untyped_expr_type(c, te->y, type, final);
  3571. case_end;
  3572. case_ast_node(ore, OrReturnExpr, e);
  3573. if (old->value.kind != ExactValue_Invalid) {
  3574. // See above note in UnaryExpr case
  3575. break;
  3576. }
  3577. update_untyped_expr_type(c, ore->expr, type, final);
  3578. case_end;
  3579. case_ast_node(obe, OrBranchExpr, e);
  3580. if (old->value.kind != ExactValue_Invalid) {
  3581. // See above note in UnaryExpr case
  3582. break;
  3583. }
  3584. update_untyped_expr_type(c, obe->expr, type, final);
  3585. case_end;
  3586. case_ast_node(oee, OrElseExpr, e);
  3587. if (old->value.kind != ExactValue_Invalid) {
  3588. // See above note in UnaryExpr case
  3589. break;
  3590. }
  3591. update_untyped_expr_type(c, oee->x, type, final);
  3592. update_untyped_expr_type(c, oee->y, type, final);
  3593. case_end;
  3594. case_ast_node(pe, ParenExpr, e);
  3595. update_untyped_expr_type(c, pe->expr, type, final);
  3596. case_end;
  3597. }
  3598. if (!final && is_type_untyped(type)) {
  3599. old->type = base_type(type);
  3600. return;
  3601. }
  3602. // We need to remove it and then give it a new one
  3603. check_remove_expr_info(c, e);
  3604. if (old->is_lhs && !is_type_integer(type)) {
  3605. gbString expr_str = expr_to_string(e);
  3606. gbString type_str = type_to_string(type);
  3607. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3608. gb_string_free(type_str);
  3609. gb_string_free(expr_str);
  3610. return;
  3611. }
  3612. add_type_and_value(c, e, old->mode, type, old->value);
  3613. }
  3614. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3615. GB_ASSERT(e != nullptr);
  3616. ExprInfo *found = check_get_expr_info(c, e);
  3617. if (found) {
  3618. found->value = value;
  3619. }
  3620. }
  3621. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3622. gbString expr_str = expr_to_string(operand->expr);
  3623. gbString type_str = type_to_string(target_type);
  3624. gbString from_type_str = type_to_string(operand->type);
  3625. char const *extra_text = "";
  3626. if (operand->mode == Addressing_Constant) {
  3627. if (big_int_is_zero(&operand->value.value_integer)) {
  3628. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3629. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3630. extra_text = " - Did you want 'nil'?";
  3631. }
  3632. }
  3633. }
  3634. if (!ignore_error_block) {
  3635. begin_error_block();
  3636. }
  3637. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3638. if (operand->value.kind == ExactValue_String) {
  3639. String key = operand->value.value_string;
  3640. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3641. Type *et = base_type(target_type);
  3642. check_did_you_mean_type(key, et->Enum.fields, ".");
  3643. }
  3644. }
  3645. gb_string_free(from_type_str);
  3646. gb_string_free(type_str);
  3647. gb_string_free(expr_str);
  3648. operand->mode = Addressing_Invalid;
  3649. if (!ignore_error_block) {
  3650. end_error_block();
  3651. }
  3652. }
  3653. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3654. Type *t = core_type(type);
  3655. if (is_type_boolean(t)) {
  3656. // v = exact_value_to_boolean(v);
  3657. } else if (is_type_float(t)) {
  3658. v = exact_value_to_float(v);
  3659. } else if (is_type_integer(t)) {
  3660. v = exact_value_to_integer(v);
  3661. } else if (is_type_pointer(t)) {
  3662. v = exact_value_to_integer(v);
  3663. } else if (is_type_complex(t)) {
  3664. v = exact_value_to_complex(v);
  3665. } else if (is_type_quaternion(t)) {
  3666. v = exact_value_to_quaternion(v);
  3667. }
  3668. return v;
  3669. }
  3670. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3671. GB_ASSERT_NOT_NULL(target_type);
  3672. if (operand->mode == Addressing_Invalid ||
  3673. operand->mode == Addressing_Type ||
  3674. is_type_typed(operand->type) ||
  3675. target_type == t_invalid) {
  3676. return;
  3677. }
  3678. if (is_type_untyped(target_type)) {
  3679. GB_ASSERT(operand->type->kind == Type_Basic);
  3680. GB_ASSERT(target_type->kind == Type_Basic);
  3681. BasicKind x_kind = operand->type->Basic.kind;
  3682. BasicKind y_kind = target_type->Basic.kind;
  3683. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3684. if (x_kind < y_kind) {
  3685. operand->type = target_type;
  3686. update_untyped_expr_type(c, operand->expr, target_type, false);
  3687. }
  3688. } else if (x_kind != y_kind) {
  3689. operand->mode = Addressing_Invalid;
  3690. convert_untyped_error(c, operand, target_type);
  3691. return;
  3692. }
  3693. return;
  3694. }
  3695. Type *t = base_type(target_type);
  3696. if (c->in_enum_type) {
  3697. t = core_type(target_type);
  3698. }
  3699. switch (t->kind) {
  3700. case Type_Basic:
  3701. if (operand->mode == Addressing_Constant) {
  3702. check_is_expressible(c, operand, t);
  3703. if (operand->mode == Addressing_Invalid) {
  3704. return;
  3705. }
  3706. update_untyped_expr_value(c, operand->expr, operand->value);
  3707. } else {
  3708. switch (operand->type->Basic.kind) {
  3709. case Basic_UntypedBool:
  3710. if (!is_type_boolean(target_type)) {
  3711. operand->mode = Addressing_Invalid;
  3712. convert_untyped_error(c, operand, target_type);
  3713. return;
  3714. }
  3715. break;
  3716. case Basic_UntypedInteger:
  3717. case Basic_UntypedFloat:
  3718. case Basic_UntypedComplex:
  3719. case Basic_UntypedQuaternion:
  3720. case Basic_UntypedRune:
  3721. if (!is_type_numeric(target_type)) {
  3722. operand->mode = Addressing_Invalid;
  3723. convert_untyped_error(c, operand, target_type);
  3724. return;
  3725. }
  3726. break;
  3727. case Basic_UntypedNil:
  3728. if (is_type_any(target_type)) {
  3729. // target_type = t_untyped_nil;
  3730. } else if (is_type_cstring(target_type)) {
  3731. // target_type = t_untyped_nil;
  3732. } else if (!type_has_nil(target_type)) {
  3733. operand->mode = Addressing_Invalid;
  3734. convert_untyped_error(c, operand, target_type);
  3735. return;
  3736. }
  3737. break;
  3738. }
  3739. }
  3740. break;
  3741. case Type_Array: {
  3742. Type *elem = base_array_type(t);
  3743. if (check_is_assignable_to(c, operand, elem)) {
  3744. operand->mode = Addressing_Value;
  3745. } else {
  3746. if (operand->value.kind == ExactValue_String) {
  3747. String s = operand->value.value_string;
  3748. if (is_type_u8_array(t)) {
  3749. if (s.len == t->Array.count) {
  3750. break;
  3751. }
  3752. } else if (is_type_rune_array(t)) {
  3753. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3754. if (rune_count == t->Array.count) {
  3755. break;
  3756. }
  3757. }
  3758. }
  3759. operand->mode = Addressing_Invalid;
  3760. convert_untyped_error(c, operand, target_type);
  3761. return;
  3762. }
  3763. break;
  3764. }
  3765. case Type_Matrix: {
  3766. Type *elem = base_array_type(t);
  3767. if (check_is_assignable_to(c, operand, elem)) {
  3768. if (t->Matrix.row_count != t->Matrix.column_count) {
  3769. operand->mode = Addressing_Invalid;
  3770. ERROR_BLOCK();
  3771. convert_untyped_error(c, operand, target_type, true);
  3772. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3773. return;
  3774. } else {
  3775. operand->mode = Addressing_Value;
  3776. }
  3777. } else {
  3778. operand->mode = Addressing_Invalid;
  3779. convert_untyped_error(c, operand, target_type);
  3780. return;
  3781. }
  3782. break;
  3783. }
  3784. case Type_Union:
  3785. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3786. TEMPORARY_ALLOCATOR_GUARD();
  3787. isize count = t->Union.variants.count;
  3788. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3789. isize valid_count = 0;
  3790. isize first_success_index = -1;
  3791. for_array(i, t->Union.variants) {
  3792. Type *vt = t->Union.variants[i];
  3793. i64 score = 0;
  3794. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3795. valids[valid_count].index = i;
  3796. valids[valid_count].score = score;
  3797. valid_count += 1;
  3798. if (first_success_index < 0) {
  3799. first_success_index = i;
  3800. }
  3801. }
  3802. }
  3803. if (valid_count > 1) {
  3804. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3805. i64 best_score = valids[0].score;
  3806. for (isize i = 1; i < valid_count; i++) {
  3807. auto v = valids[i];
  3808. if (best_score > v.score) {
  3809. valid_count = i;
  3810. break;
  3811. }
  3812. best_score = v.score;
  3813. }
  3814. first_success_index = valids[0].index;
  3815. }
  3816. gbString type_str = type_to_string(target_type);
  3817. defer (gb_string_free(type_str));
  3818. if (valid_count == 1) {
  3819. operand->mode = Addressing_Value;
  3820. operand->type = t->Union.variants[first_success_index];
  3821. target_type = t->Union.variants[first_success_index];
  3822. break;
  3823. } else if (valid_count > 1) {
  3824. ERROR_BLOCK();
  3825. GB_ASSERT(first_success_index >= 0);
  3826. operand->mode = Addressing_Invalid;
  3827. convert_untyped_error(c, operand, target_type, true);
  3828. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3829. i32 j = 0;
  3830. for (i32 i = 0; i < valid_count; i++) {
  3831. ValidIndexAndScore valid = valids[i];
  3832. if (j > 0 && valid_count > 2) error_line(", ");
  3833. if (j == valid_count-1) {
  3834. if (valid_count == 2) error_line(" ");
  3835. error_line("or ");
  3836. }
  3837. gbString str = type_to_string(t->Union.variants[valid.index]);
  3838. error_line("'%s'", str);
  3839. gb_string_free(str);
  3840. j++;
  3841. }
  3842. error_line("\n\n");
  3843. return;
  3844. } else if (is_type_untyped_uninit(operand->type)) {
  3845. target_type = t_untyped_uninit;
  3846. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3847. ERROR_BLOCK();
  3848. operand->mode = Addressing_Invalid;
  3849. convert_untyped_error(c, operand, target_type, true);
  3850. if (count > 0) {
  3851. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3852. error_line("\t");
  3853. for (i32 i = 0; i < count; i++) {
  3854. Type *v = t->Union.variants[i];
  3855. if (i > 0 && count > 2) error_line(", ");
  3856. if (i == count-1) {
  3857. if (count == 2) error_line(" ");
  3858. if (count > 1) {
  3859. error_line("or ");
  3860. }
  3861. }
  3862. gbString str = type_to_string(v);
  3863. error_line("'%s'", str);
  3864. gb_string_free(str);
  3865. }
  3866. error_line("\n\n");
  3867. }
  3868. return;
  3869. }
  3870. }
  3871. /* fallthrough */
  3872. default:
  3873. if (is_type_untyped_uninit(operand->type)) {
  3874. target_type = t_untyped_uninit;
  3875. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3876. target_type = t_untyped_nil;
  3877. } else {
  3878. operand->mode = Addressing_Invalid;
  3879. convert_untyped_error(c, operand, target_type);
  3880. return;
  3881. }
  3882. break;
  3883. }
  3884. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3885. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3886. } else {
  3887. target_type = default_type(operand->type);
  3888. }
  3889. }
  3890. update_untyped_expr_type(c, operand->expr, target_type, true);
  3891. operand->type = target_type;
  3892. }
  3893. 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) {
  3894. Operand operand = {Addressing_Invalid};
  3895. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3896. if (operand.mode == Addressing_Invalid) {
  3897. if (value) *value = 0;
  3898. return false;
  3899. }
  3900. Type *index_type = t_int;
  3901. if (type_hint != nullptr) {
  3902. index_type = type_hint;
  3903. }
  3904. convert_to_typed(c, &operand, index_type);
  3905. if (operand.mode == Addressing_Invalid) {
  3906. if (value) *value = 0;
  3907. return false;
  3908. }
  3909. if (type_hint != nullptr) {
  3910. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3911. gbString expr_str = expr_to_string(operand.expr);
  3912. gbString index_type_str = type_to_string(type_hint);
  3913. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3914. gb_string_free(index_type_str);
  3915. gb_string_free(expr_str);
  3916. if (value) *value = 0;
  3917. return false;
  3918. }
  3919. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3920. gbString expr_str = expr_to_string(operand.expr);
  3921. gbString type_str = type_to_string(operand.type);
  3922. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3923. gb_string_free(type_str);
  3924. gb_string_free(expr_str);
  3925. if (value) *value = 0;
  3926. return false;
  3927. }
  3928. if (operand.mode == Addressing_Constant &&
  3929. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3930. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3931. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3932. TEMPORARY_ALLOCATOR_GUARD();
  3933. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3934. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3935. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3936. if (value) *value = 0;
  3937. return false;
  3938. }
  3939. if (max_count >= 0) {
  3940. if (is_type_enum(index_type)) {
  3941. Type *bt = base_type(index_type);
  3942. GB_ASSERT(bt->kind == Type_Enum);
  3943. ExactValue const &lo = *bt->Enum.min_value;
  3944. ExactValue const &hi = *bt->Enum.max_value;
  3945. String lo_str = {};
  3946. String hi_str = {};
  3947. if (bt->Enum.fields.count > 0) {
  3948. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3949. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3950. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3951. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3952. }
  3953. bool out_of_bounds = false;
  3954. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3955. out_of_bounds = true;
  3956. }
  3957. if (out_of_bounds) {
  3958. gbString expr_str = expr_to_string(operand.expr);
  3959. if (lo_str.len > 0) {
  3960. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3961. } else {
  3962. gbString index_type_str = type_to_string(index_type);
  3963. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3964. gb_string_free(index_type_str);
  3965. }
  3966. gb_string_free(expr_str);
  3967. return false;
  3968. }
  3969. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3970. return true;
  3971. } else { // NOTE(bill): Do array bound checking
  3972. i64 v = -1;
  3973. if (i.used <= 1) {
  3974. v = big_int_to_i64(&i);
  3975. }
  3976. if (value) *value = v;
  3977. bool out_of_bounds = false;
  3978. if (v < 0) {
  3979. out_of_bounds = true;
  3980. } else if (open_range) {
  3981. out_of_bounds = v > max_count;
  3982. } else {
  3983. out_of_bounds = v >= max_count;
  3984. }
  3985. if (out_of_bounds) {
  3986. TEMPORARY_ALLOCATOR_GUARD();
  3987. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3988. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3989. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3990. return false;
  3991. }
  3992. return true;
  3993. }
  3994. } else {
  3995. if (value) *value = exact_value_to_i64(operand.value);
  3996. return true;
  3997. }
  3998. }
  3999. // NOTE(bill): It's alright :D
  4000. if (value) *value = -1;
  4001. return true;
  4002. }
  4003. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4004. if (value.kind == ExactValue_String) {
  4005. GB_ASSERT(0 <= index && index < value.value_string.len);
  4006. u8 val = value.value_string[index];
  4007. if (success_) *success_ = true;
  4008. if (finish_) *finish_ = true;
  4009. return exact_value_u64(val);
  4010. }
  4011. if (value.kind != ExactValue_Compound) {
  4012. if (success_) *success_ = true;
  4013. if (finish_) *finish_ = true;
  4014. return value;
  4015. }
  4016. Ast *node = value.value_compound;
  4017. switch (node->kind) {
  4018. case_ast_node(cl, CompoundLit, node);
  4019. if (cl->elems.count == 0) {
  4020. if (success_) *success_ = true;
  4021. if (finish_) *finish_ = true;
  4022. return empty_exact_value;
  4023. }
  4024. if (cl->elems[0]->kind == Ast_FieldValue) {
  4025. if (is_type_struct(node->tav.type)) {
  4026. bool found = false;
  4027. for (Ast *elem : cl->elems) {
  4028. if (elem->kind != Ast_FieldValue) {
  4029. continue;
  4030. }
  4031. ast_node(fv, FieldValue, elem);
  4032. String name = fv->field->Ident.token.string;
  4033. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4034. defer (array_free(&sub_sel.index));
  4035. if (sub_sel.index.count > 0 &&
  4036. sub_sel.index[0] == index) {
  4037. value = fv->value->tav.value;
  4038. found = true;
  4039. break;
  4040. }
  4041. }
  4042. if (!found) {
  4043. // Use the zero value if it is not found
  4044. value = {};
  4045. }
  4046. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4047. for (Ast *elem : cl->elems) {
  4048. if (elem->kind != Ast_FieldValue) {
  4049. continue;
  4050. }
  4051. ast_node(fv, FieldValue, elem);
  4052. if (is_ast_range(fv->field)) {
  4053. ast_node(ie, BinaryExpr, fv->field);
  4054. TypeAndValue lo_tav = ie->left->tav;
  4055. TypeAndValue hi_tav = ie->right->tav;
  4056. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4057. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4058. TokenKind op = ie->op.kind;
  4059. i64 lo = exact_value_to_i64(lo_tav.value);
  4060. i64 hi = exact_value_to_i64(hi_tav.value);
  4061. i64 corrected_index = index;
  4062. if (is_type_enumerated_array(node->tav.type)) {
  4063. Type *bt = base_type(node->tav.type);
  4064. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4065. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4066. }
  4067. if (op != Token_RangeHalf) {
  4068. if (lo <= corrected_index && corrected_index <= hi) {
  4069. TypeAndValue tav = fv->value->tav;
  4070. if (success_) *success_ = true;
  4071. if (finish_) *finish_ = false;
  4072. return tav.value;
  4073. }
  4074. } else {
  4075. if (lo <= corrected_index && corrected_index < hi) {
  4076. TypeAndValue tav = fv->value->tav;
  4077. if (success_) *success_ = true;
  4078. if (finish_) *finish_ = false;
  4079. return tav.value;
  4080. }
  4081. }
  4082. } else {
  4083. TypeAndValue index_tav = fv->field->tav;
  4084. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4085. ExactValue index_value = index_tav.value;
  4086. if (is_type_enumerated_array(node->tav.type)) {
  4087. Type *bt = base_type(node->tav.type);
  4088. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4089. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4090. }
  4091. i64 field_index = exact_value_to_i64(index_value);
  4092. if (index == field_index) {
  4093. TypeAndValue tav = fv->value->tav;
  4094. if (success_) *success_ = true;
  4095. if (finish_) *finish_ = false;
  4096. return tav.value;;
  4097. }
  4098. }
  4099. }
  4100. }
  4101. } else {
  4102. i32 count = (i32)cl->elems.count;
  4103. if (count < index) {
  4104. if (success_) *success_ = false;
  4105. if (finish_) *finish_ = true;
  4106. return empty_exact_value;
  4107. }
  4108. if (cl->elems.count <= index) {
  4109. if (success_) *success_ = false;
  4110. if (finish_) *finish_ = false;
  4111. return value;
  4112. }
  4113. TypeAndValue tav = cl->elems[index]->tav;
  4114. if (tav.mode == Addressing_Constant) {
  4115. if (success_) *success_ = true;
  4116. if (finish_) *finish_ = false;
  4117. return tav.value;
  4118. } else {
  4119. GB_ASSERT(is_type_untyped_nil(tav.type));
  4120. if (success_) *success_ = true;
  4121. if (finish_) *finish_ = false;
  4122. return tav.value;
  4123. }
  4124. }
  4125. case_end;
  4126. default:
  4127. if (success_) *success_ = true;
  4128. if (finish_) *finish_ = true;
  4129. return empty_exact_value;
  4130. }
  4131. if (finish_) *finish_ = false;
  4132. return value;
  4133. }
  4134. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4135. if (operand->mode != Addressing_Constant) {
  4136. if (success_) *success_ = false;
  4137. return empty_exact_value;
  4138. }
  4139. if (sel.indirect) {
  4140. if (success_) *success_ = false;
  4141. return empty_exact_value;
  4142. }
  4143. if (sel.index.count == 0) {
  4144. if (success_) *success_ = false;
  4145. return empty_exact_value;
  4146. }
  4147. ExactValue value = operand->value;
  4148. if (value.kind == ExactValue_Compound) {
  4149. while (sel.index.count > 0) {
  4150. i32 index = sel.index[0];
  4151. sel = sub_selection(sel, 1);
  4152. bool finish = false;
  4153. value = get_constant_field_single(c, value, index, success_, &finish);
  4154. if (finish) {
  4155. return value;
  4156. }
  4157. }
  4158. if (success_) *success_ = true;
  4159. return value;
  4160. } else if (value.kind == ExactValue_Quaternion) {
  4161. // @QuaternionLayout
  4162. Quaternion256 q = *value.value_quaternion;
  4163. GB_ASSERT(sel.index.count == 1);
  4164. switch (sel.index[0]) {
  4165. case 3: // w
  4166. if (success_) *success_ = true;
  4167. return exact_value_float(q.real);
  4168. case 0: // x
  4169. if (success_) *success_ = true;
  4170. return exact_value_float(q.imag);
  4171. case 1: // y
  4172. if (success_) *success_ = true;
  4173. return exact_value_float(q.jmag);
  4174. case 2: // z
  4175. if (success_) *success_ = true;
  4176. return exact_value_float(q.kmag);
  4177. }
  4178. if (success_) *success_ = false;
  4179. return empty_exact_value;
  4180. } else if (value.kind == ExactValue_Complex) {
  4181. // @QuaternionLayout
  4182. Complex128 c = *value.value_complex;
  4183. GB_ASSERT(sel.index.count == 1);
  4184. switch (sel.index[0]) {
  4185. case 0: // real
  4186. if (success_) *success_ = true;
  4187. return exact_value_float(c.real);
  4188. case 1: // imag
  4189. if (success_) *success_ = true;
  4190. return exact_value_float(c.imag);
  4191. }
  4192. if (success_) *success_ = false;
  4193. return empty_exact_value;
  4194. }
  4195. if (success_) *success_ = true;
  4196. return empty_exact_value;
  4197. }
  4198. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4199. Type *array_type = base_type(type_deref(original_type));
  4200. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4201. if (array_type->kind == Type_SimdVector) {
  4202. Type *elem_type = array_type->SimdVector.elem;
  4203. return alloc_type_simd_vector(new_count, elem_type);
  4204. }
  4205. Type *elem_type = array_type->Array.elem;
  4206. Type *swizzle_array_type = nullptr;
  4207. Type *bth = base_type(type_deref(type_hint));
  4208. if (bth != nullptr && bth->kind == Type_Array &&
  4209. bth->Array.count == new_count &&
  4210. are_types_identical(bth->Array.elem, elem_type)) {
  4211. swizzle_array_type = type_hint;
  4212. } else {
  4213. i64 max_count = array_type->Array.count;
  4214. if (new_count == max_count) {
  4215. swizzle_array_type = original_type;
  4216. } else {
  4217. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4218. }
  4219. }
  4220. return swizzle_array_type;
  4221. }
  4222. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4223. bool is_declared = entity != nullptr;
  4224. if (is_declared) {
  4225. if (entity->kind == Entity_Builtin) {
  4226. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4227. // This means that we should just ignore the found result through it
  4228. *allow_builtin = entity->scope == import_scope ||
  4229. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4230. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4231. is_declared = false;
  4232. }
  4233. }
  4234. return is_declared;
  4235. }
  4236. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4237. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4238. if (node->kind == Ast_Ident) {
  4239. String name = node->Ident.token.string;
  4240. return scope_lookup(c->scope, name);
  4241. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4242. ast_node(se, SelectorExpr, node);
  4243. if (se->token.kind == Token_ArrowRight) {
  4244. return nullptr;
  4245. }
  4246. Ast *op_expr = se->expr;
  4247. Ast *selector = unparen_expr(se->selector);
  4248. if (selector == nullptr) {
  4249. return nullptr;
  4250. }
  4251. if (selector->kind != Ast_Ident) {
  4252. return nullptr;
  4253. }
  4254. Entity *entity = nullptr;
  4255. Entity *expr_entity = nullptr;
  4256. bool check_op_expr = true;
  4257. if (op_expr->kind == Ast_Ident) {
  4258. String op_name = op_expr->Ident.token.string;
  4259. Entity *e = scope_lookup(c->scope, op_name);
  4260. if (e == nullptr) {
  4261. return nullptr;
  4262. }
  4263. add_entity_use(c, op_expr, e);
  4264. expr_entity = e;
  4265. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4266. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4267. // It pretty much needs to be in this order and this way
  4268. // If you can clean this up, please do but be really careful
  4269. String import_name = op_name;
  4270. Scope *import_scope = e->ImportName.scope;
  4271. String entity_name = selector->Ident.token.string;
  4272. check_op_expr = false;
  4273. entity = scope_lookup_current(import_scope, entity_name);
  4274. bool allow_builtin = false;
  4275. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4276. return nullptr;
  4277. }
  4278. check_entity_decl(c, entity, nullptr, nullptr);
  4279. if (entity->kind == Entity_ProcGroup) {
  4280. return entity;
  4281. }
  4282. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4283. }
  4284. }
  4285. Operand operand = {};
  4286. if (check_op_expr) {
  4287. check_expr_base(c, &operand, op_expr, nullptr);
  4288. if (operand.mode == Addressing_Invalid) {
  4289. return nullptr;
  4290. }
  4291. }
  4292. if (entity == nullptr && selector->kind == Ast_Ident) {
  4293. String field_name = selector->Ident.token.string;
  4294. if (is_type_dynamic_array(type_deref(operand.type))) {
  4295. init_mem_allocator(c->checker);
  4296. }
  4297. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4298. entity = sel.entity;
  4299. }
  4300. if (entity != nullptr) {
  4301. return entity;
  4302. }
  4303. }
  4304. return nullptr;
  4305. }
  4306. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4307. ast_node(se, SelectorExpr, node);
  4308. bool check_op_expr = true;
  4309. Entity *expr_entity = nullptr;
  4310. Entity *entity = nullptr;
  4311. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4312. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4313. ERROR_BLOCK();
  4314. error(node, "Illegal use of -> selector shorthand outside of a call");
  4315. gbString x = expr_to_string(se->expr);
  4316. gbString y = expr_to_string(se->selector);
  4317. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4318. gb_string_free(y);
  4319. gb_string_free(x);
  4320. // TODO(bill): Should this terminate here or propagate onwards?
  4321. // operand->mode = Addressing_Invalid;
  4322. // operand->expr = node;
  4323. // return nullptr;
  4324. }
  4325. operand->expr = node;
  4326. Ast *op_expr = se->expr;
  4327. Ast *selector = unparen_expr(se->selector);
  4328. if (selector == nullptr) {
  4329. operand->mode = Addressing_Invalid;
  4330. operand->expr = node;
  4331. return nullptr;
  4332. }
  4333. if (selector->kind != Ast_Ident) {
  4334. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4335. operand->mode = Addressing_Invalid;
  4336. operand->expr = node;
  4337. return nullptr;
  4338. }
  4339. if (op_expr->kind == Ast_Ident) {
  4340. String op_name = op_expr->Ident.token.string;
  4341. Entity *e = scope_lookup(c->scope, op_name);
  4342. add_entity_use(c, op_expr, e);
  4343. expr_entity = e;
  4344. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4345. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4346. // It pretty much needs to be in this order and this way
  4347. // If you can clean this up, please do but be really careful
  4348. String import_name = op_name;
  4349. Scope *import_scope = e->ImportName.scope;
  4350. String entity_name = selector->Ident.token.string;
  4351. check_op_expr = false;
  4352. entity = scope_lookup_current(import_scope, entity_name);
  4353. bool allow_builtin = false;
  4354. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4355. ERROR_BLOCK();
  4356. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4357. operand->mode = Addressing_Invalid;
  4358. operand->expr = node;
  4359. check_did_you_mean_scope(entity_name, import_scope);
  4360. return nullptr;
  4361. }
  4362. check_entity_decl(c, entity, nullptr, nullptr);
  4363. if (entity->kind == Entity_ProcGroup) {
  4364. operand->mode = Addressing_ProcGroup;
  4365. operand->proc_group = entity;
  4366. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4367. return entity;
  4368. }
  4369. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4370. if (!is_entity_exported(entity, allow_builtin)) {
  4371. gbString sel_str = expr_to_string(selector);
  4372. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4373. gb_string_free(sel_str);
  4374. // NOTE(bill): make the state valid still, even if it's "invalid"
  4375. // operand->mode = Addressing_Invalid;
  4376. // operand->expr = node;
  4377. // return nullptr;
  4378. }
  4379. if (entity->kind == Entity_ProcGroup) {
  4380. Array<Entity *> procs = entity->ProcGroup.entities;
  4381. bool skip = false;
  4382. for (Entity *p : procs) {
  4383. Type *t = base_type(p->type);
  4384. if (t == t_invalid) {
  4385. continue;
  4386. }
  4387. Operand x = {};
  4388. x.mode = Addressing_Value;
  4389. x.type = t;
  4390. if (type_hint != nullptr) {
  4391. if (check_is_assignable_to(c, &x, type_hint)) {
  4392. entity = p;
  4393. skip = true;
  4394. break;
  4395. }
  4396. }
  4397. }
  4398. if (!skip) {
  4399. GB_ASSERT(entity != nullptr);
  4400. operand->mode = Addressing_ProcGroup;
  4401. operand->type = t_invalid;
  4402. operand->expr = node;
  4403. operand->proc_group = entity;
  4404. return entity;
  4405. }
  4406. }
  4407. }
  4408. }
  4409. if (check_op_expr) {
  4410. check_expr_base(c, operand, op_expr, nullptr);
  4411. if (operand->mode == Addressing_Invalid) {
  4412. operand->mode = Addressing_Invalid;
  4413. operand->expr = node;
  4414. return nullptr;
  4415. }
  4416. }
  4417. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4418. complete_soa_type(c->checker, type_deref(operand->type), false);
  4419. }
  4420. if (entity == nullptr && selector->kind == Ast_Ident) {
  4421. String field_name = selector->Ident.token.string;
  4422. Type *t = type_deref(operand->type);
  4423. if (t == nullptr) {
  4424. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4425. } else if (is_type_dynamic_array(t)) {
  4426. init_mem_allocator(c->checker);
  4427. }
  4428. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4429. entity = sel.entity;
  4430. // NOTE(bill): Add type info needed for fields like 'names'
  4431. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4432. add_type_info_type(c, operand->type);
  4433. }
  4434. if (is_type_enum(operand->type)) {
  4435. add_type_info_type(c, operand->type);
  4436. }
  4437. }
  4438. if (entity == nullptr && selector->kind == Ast_Ident && (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4439. String field_name = selector->Ident.token.string;
  4440. if (1 < field_name.len && field_name.len <= 4) {
  4441. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4442. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4443. bool found_xyzw = false;
  4444. bool found_rgba = false;
  4445. for (isize i = 0; i < field_name.len; i++) {
  4446. bool valid = false;
  4447. for (isize j = 0; j < 4; j++) {
  4448. if (field_name.text[i] == swizzles_xyzw[j]) {
  4449. found_xyzw = true;
  4450. valid = true;
  4451. break;
  4452. }
  4453. if (field_name.text[i] == swizzles_rgba[j]) {
  4454. found_rgba = true;
  4455. valid = true;
  4456. break;
  4457. }
  4458. }
  4459. if (!valid) {
  4460. goto end_of_array_selector_swizzle;
  4461. }
  4462. }
  4463. u8 *swizzles = nullptr;
  4464. u8 index_count = cast(u8)field_name.len;
  4465. if (found_xyzw && found_rgba) {
  4466. gbString op_str = expr_to_string(op_expr);
  4467. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4468. gb_string_free(op_str);
  4469. operand->mode = Addressing_Invalid;
  4470. operand->expr = node;
  4471. return nullptr;
  4472. }
  4473. u8 indices = 0;
  4474. if (found_xyzw) {
  4475. swizzles = swizzles_xyzw;
  4476. } else if (found_rgba) {
  4477. swizzles = swizzles_rgba;
  4478. }
  4479. for (isize i = 0; i < field_name.len; i++) {
  4480. for (isize j = 0; j < 4; j++) {
  4481. if (field_name.text[i] == swizzles[j]) {
  4482. indices |= cast(u8)(j)<<(i*2);
  4483. break;
  4484. }
  4485. }
  4486. }
  4487. Type *original_type = operand->type;
  4488. Type *array_type = base_type(type_deref(original_type));
  4489. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4490. i64 array_count = get_array_type_count(array_type);
  4491. for (u8 i = 0; i < index_count; i++) {
  4492. u8 idx = indices>>(i*2) & 3;
  4493. if (idx >= array_count) {
  4494. char c = 0;
  4495. if (found_xyzw) {
  4496. c = swizzles_xyzw[idx];
  4497. } else if (found_rgba) {
  4498. c = swizzles_rgba[idx];
  4499. } else {
  4500. GB_PANIC("unknown swizzle kind");
  4501. }
  4502. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4503. break;
  4504. }
  4505. }
  4506. se->swizzle_count = index_count;
  4507. se->swizzle_indices = indices;
  4508. AddressingMode prev_mode = operand->mode;
  4509. operand->mode = Addressing_SwizzleValue;
  4510. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4511. operand->expr = node;
  4512. switch (prev_mode) {
  4513. case Addressing_Variable:
  4514. case Addressing_SoaVariable:
  4515. case Addressing_SwizzleVariable:
  4516. operand->mode = Addressing_SwizzleVariable;
  4517. break;
  4518. }
  4519. if (array_type->kind == Type_SimdVector) {
  4520. operand->mode = Addressing_Value;
  4521. }
  4522. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4523. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4524. return swizzle_entity;
  4525. }
  4526. end_of_array_selector_swizzle:;
  4527. }
  4528. if (entity == nullptr) {
  4529. gbString op_str = expr_to_string(op_expr);
  4530. gbString type_str = type_to_string_shorthand(operand->type);
  4531. gbString sel_str = expr_to_string(selector);
  4532. if (operand->mode == Addressing_Type) {
  4533. if (is_type_polymorphic(operand->type, true)) {
  4534. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4535. } else {
  4536. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4537. }
  4538. } else {
  4539. ERROR_BLOCK();
  4540. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4541. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4542. String const &name = selector->Ident.token.string;
  4543. Type *bt = base_type(operand->type);
  4544. if (operand->type->kind == Type_Named &&
  4545. operand->type->Named.type_name &&
  4546. operand->type->Named.type_name->kind == Entity_TypeName &&
  4547. operand->type->Named.type_name->TypeName.objc_metadata) {
  4548. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4549. } else if (bt->kind == Type_Struct) {
  4550. check_did_you_mean_type(name, bt->Struct.fields);
  4551. } else if (bt->kind == Type_Enum) {
  4552. check_did_you_mean_type(name, bt->Enum.fields);
  4553. }
  4554. }
  4555. }
  4556. gb_string_free(sel_str);
  4557. gb_string_free(type_str);
  4558. gb_string_free(op_str);
  4559. operand->mode = Addressing_Invalid;
  4560. operand->expr = node;
  4561. return nullptr;
  4562. }
  4563. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4564. bool success = false;
  4565. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4566. if (success) {
  4567. operand->mode = Addressing_Constant;
  4568. operand->expr = node;
  4569. operand->value = field_value;
  4570. operand->type = entity->type;
  4571. add_entity_use(c, selector, entity);
  4572. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4573. return entity;
  4574. }
  4575. gbString op_str = expr_to_string(op_expr);
  4576. gbString type_str = type_to_string_shorthand(operand->type);
  4577. gbString sel_str = expr_to_string(selector);
  4578. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4579. gb_string_free(sel_str);
  4580. gb_string_free(type_str);
  4581. gb_string_free(op_str);
  4582. operand->mode = Addressing_Invalid;
  4583. operand->expr = node;
  4584. return nullptr;
  4585. }
  4586. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4587. bool success = false;
  4588. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4589. if (success) {
  4590. operand->mode = Addressing_Constant;
  4591. operand->expr = node;
  4592. operand->value = field_value;
  4593. operand->type = entity->type;
  4594. add_entity_use(c, selector, entity);
  4595. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4596. return entity;
  4597. }
  4598. gbString op_str = expr_to_string(op_expr);
  4599. gbString type_str = type_to_string_shorthand(operand->type);
  4600. gbString sel_str = expr_to_string(selector);
  4601. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4602. gb_string_free(sel_str);
  4603. gb_string_free(type_str);
  4604. gb_string_free(op_str);
  4605. operand->mode = Addressing_Invalid;
  4606. operand->expr = node;
  4607. return nullptr;
  4608. }
  4609. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4610. gbString op_str = expr_to_string(op_expr);
  4611. gbString type_str = type_to_string_shorthand(operand->type);
  4612. gbString sel_str = expr_to_string(selector);
  4613. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4614. gb_string_free(sel_str);
  4615. gb_string_free(type_str);
  4616. gb_string_free(op_str);
  4617. operand->mode = Addressing_Invalid;
  4618. operand->expr = node;
  4619. return nullptr;
  4620. }
  4621. add_entity_use(c, selector, entity);
  4622. operand->type = entity->type;
  4623. operand->expr = node;
  4624. if (entity->flags & EntityFlag_BitFieldField) {
  4625. add_package_dependency(c, "runtime", "__write_bits");
  4626. add_package_dependency(c, "runtime", "__read_bits");
  4627. }
  4628. switch (entity->kind) {
  4629. case Entity_Constant:
  4630. operand->value = entity->Constant.value;
  4631. operand->mode = Addressing_Constant;
  4632. if (operand->value.kind == ExactValue_Procedure) {
  4633. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4634. if (proc != nullptr) {
  4635. operand->mode = Addressing_Value;
  4636. operand->type = proc->type;
  4637. }
  4638. }
  4639. break;
  4640. case Entity_Variable:
  4641. if (sel.is_bit_field) {
  4642. se->is_bit_field = true;
  4643. }
  4644. if (sel.indirect) {
  4645. operand->mode = Addressing_Variable;
  4646. } else if (operand->mode == Addressing_Context) {
  4647. // Do nothing
  4648. } else if (operand->mode == Addressing_MapIndex) {
  4649. operand->mode = Addressing_Value;
  4650. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4651. operand->mode = Addressing_SoaVariable;
  4652. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4653. operand->mode = Addressing_Value;
  4654. } else if (operand->mode == Addressing_SoaVariable) {
  4655. operand->mode = Addressing_Variable;
  4656. } else if (operand->mode != Addressing_Value) {
  4657. operand->mode = Addressing_Variable;
  4658. } else {
  4659. operand->mode = Addressing_Value;
  4660. }
  4661. break;
  4662. case Entity_TypeName:
  4663. operand->mode = Addressing_Type;
  4664. break;
  4665. case Entity_Procedure:
  4666. operand->mode = Addressing_Value;
  4667. operand->value = exact_value_procedure(node);
  4668. break;
  4669. case Entity_Builtin:
  4670. operand->mode = Addressing_Builtin;
  4671. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4672. break;
  4673. case Entity_ProcGroup:
  4674. operand->mode = Addressing_ProcGroup;
  4675. operand->proc_group = entity;
  4676. break;
  4677. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4678. case Entity_Nil:
  4679. operand->mode = Addressing_Value;
  4680. break;
  4681. }
  4682. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4683. return entity;
  4684. }
  4685. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4686. ptr = base_type(ptr);
  4687. if (is_type_pointer(ptr)) {
  4688. if (is_type_rawptr(ptr)) {
  4689. return false;
  4690. }
  4691. if (elem) *elem = ptr->Pointer.elem;
  4692. return true;
  4693. }
  4694. return false;
  4695. }
  4696. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4697. elem = core_type(elem);
  4698. if (is_type_internally_pointer_like(elem)) {
  4699. return true;
  4700. }
  4701. if (elem->kind == Type_BitSet) {
  4702. elem = bit_set_to_int(elem);
  4703. }
  4704. if (elem->kind != Type_Basic) {
  4705. return false;
  4706. }
  4707. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4708. }
  4709. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4710. switch (node->kind) {
  4711. case_ast_node(i, Ident, node);
  4712. String name = i->token.string;
  4713. if (nested) {
  4714. Entity *e = scope_lookup_current(s, name);
  4715. if (e != nullptr) {
  4716. if (out_scope) *out_scope = e->scope;
  4717. return true;
  4718. }
  4719. } else {
  4720. Entity *e = scope_lookup(s, name);
  4721. if (e != nullptr) {
  4722. if (out_scope) *out_scope = e->scope;
  4723. return true;
  4724. }
  4725. }
  4726. case_end;
  4727. case_ast_node(se, SelectorExpr, node);
  4728. Ast *lhs = se->expr;
  4729. Ast *rhs = se->selector;
  4730. Scope *lhs_scope = nullptr;
  4731. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4732. return check_identifier_exists(lhs_scope, rhs, true);
  4733. }
  4734. case_end;
  4735. }
  4736. return false;
  4737. }
  4738. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4739. if (o.type && is_type_no_copy(o.type)) {
  4740. Ast *expr = unparen_expr(o.expr);
  4741. if (expr && o.mode != Addressing_Constant) {
  4742. if (expr->kind == Ast_CallExpr) {
  4743. // Okay
  4744. } else {
  4745. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4746. return true;
  4747. }
  4748. }
  4749. }
  4750. return false;
  4751. }
  4752. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4753. bool optional_ok = false;
  4754. isize tuple_index = 0;
  4755. for (Ast *rhs_expr : rhs) {
  4756. CheckerContext c_ = *ctx;
  4757. CheckerContext *c = &c_;
  4758. Operand o = {};
  4759. Type *type_hint = nullptr;
  4760. if (tuple_index < lhs.count) {
  4761. type_hint = lhs[tuple_index].type;
  4762. }
  4763. check_expr_base(c, &o, rhs_expr, type_hint);
  4764. if (o.mode == Addressing_NoValue) {
  4765. error_operand_no_value(&o);
  4766. o.mode = Addressing_Invalid;
  4767. }
  4768. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4769. if (lhs.count == 2 && rhs.count == 1 &&
  4770. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4771. Ast *expr = unparen_expr(o.expr);
  4772. Operand val0 = o;
  4773. Operand val1 = o;
  4774. val0.mode = Addressing_Value;
  4775. val1.mode = Addressing_Value;
  4776. val1.type = t_untyped_bool;
  4777. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4778. if (expr->kind == Ast_TypeAssertion &&
  4779. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4780. // NOTE(bill): Used only for optimizations in the backend
  4781. if (is_blank_ident(lhs[0].expr)) {
  4782. expr->TypeAssertion.ignores[0] = true;
  4783. }
  4784. if (is_blank_ident(lhs[1].expr)) {
  4785. expr->TypeAssertion.ignores[1] = true;
  4786. }
  4787. }
  4788. array_add(operands, val0);
  4789. array_add(operands, val1);
  4790. optional_ok = true;
  4791. tuple_index += 2;
  4792. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4793. Type *tuple = o.type;
  4794. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4795. Ast *expr = unparen_expr(o.expr);
  4796. if (expr->kind == Ast_CallExpr) {
  4797. expr->CallExpr.optional_ok_one = true;
  4798. }
  4799. Operand val = o;
  4800. val.type = tuple->Tuple.variables[0]->type;
  4801. val.mode = Addressing_Value;
  4802. array_add(operands, val);
  4803. tuple_index += tuple->Tuple.variables.count;
  4804. } else {
  4805. array_add(operands, o);
  4806. tuple_index += 1;
  4807. }
  4808. } else {
  4809. TypeTuple *tuple = &o.type->Tuple;
  4810. for (Entity *e : tuple->variables) {
  4811. o.type = e->type;
  4812. array_add(operands, o);
  4813. check_no_copy_assignment(o, str_lit("assignment"));
  4814. }
  4815. tuple_index += tuple->variables.count;
  4816. }
  4817. }
  4818. return optional_ok;
  4819. }
  4820. typedef u32 UnpackFlags;
  4821. enum UnpackFlag : u32 {
  4822. UnpackFlag_None = 0,
  4823. UnpackFlag_AllowOk = 1<<0,
  4824. UnpackFlag_IsVariadic = 1<<1,
  4825. UnpackFlag_AllowUndef = 1<<2,
  4826. };
  4827. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4828. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4829. if (lhs == nullptr || c->decl == nullptr) {
  4830. return tuple_count;
  4831. }
  4832. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4833. Entity *e = lhs[tuple_index + j];
  4834. if (e == nullptr) {
  4835. continue;
  4836. }
  4837. DeclInfo *decl = decl_info_of_entity(e);
  4838. if (decl == nullptr) {
  4839. continue;
  4840. }
  4841. rw_mutex_shared_lock(&decl->deps_mutex);
  4842. rw_mutex_lock(&c->decl->deps_mutex);
  4843. for (Entity *dep : decl->deps) {
  4844. ptr_set_add(&c->decl->deps, dep);
  4845. }
  4846. rw_mutex_unlock(&c->decl->deps_mutex);
  4847. rw_mutex_shared_unlock(&decl->deps_mutex);
  4848. }
  4849. return tuple_count;
  4850. };
  4851. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4852. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4853. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4854. bool optional_ok = false;
  4855. isize tuple_index = 0;
  4856. for (Ast *rhs : rhs_arguments) {
  4857. if (rhs->kind == Ast_FieldValue) {
  4858. error(rhs, "Invalid use of 'field = value'");
  4859. rhs = rhs->FieldValue.value;
  4860. }
  4861. CheckerContext c_ = *ctx;
  4862. CheckerContext *c = &c_;
  4863. Operand o = {};
  4864. Type *type_hint = nullptr;
  4865. if (lhs != nullptr && tuple_index < lhs_count) {
  4866. // NOTE(bill): override DeclInfo for dependency
  4867. Entity *e = lhs[tuple_index];
  4868. if (e != nullptr) {
  4869. type_hint = e->type;
  4870. if (e->flags & EntityFlag_Ellipsis) {
  4871. GB_ASSERT(is_type_slice(e->type));
  4872. GB_ASSERT(e->type->kind == Type_Slice);
  4873. type_hint = e->type->Slice.elem;
  4874. }
  4875. }
  4876. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4877. // NOTE(bill): override DeclInfo for dependency
  4878. Entity *e = lhs[lhs_count-1];
  4879. if (e != nullptr) {
  4880. type_hint = e->type;
  4881. if (e->flags & EntityFlag_Ellipsis) {
  4882. GB_ASSERT(is_type_slice(e->type));
  4883. GB_ASSERT(e->type->kind == Type_Slice);
  4884. type_hint = e->type->Slice.elem;
  4885. }
  4886. }
  4887. }
  4888. Ast *rhs_expr = unparen_expr(rhs);
  4889. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4890. // NOTE(bill): Just handle this very specific logic here
  4891. o.type = t_untyped_uninit;
  4892. o.mode = Addressing_Value;
  4893. o.expr = rhs;
  4894. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4895. } else {
  4896. check_expr_base(c, &o, rhs, type_hint);
  4897. }
  4898. if (o.mode == Addressing_NoValue) {
  4899. error_operand_no_value(&o);
  4900. o.mode = Addressing_Invalid;
  4901. }
  4902. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4903. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4904. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4905. Ast *expr = unparen_expr(o.expr);
  4906. Operand val0 = o;
  4907. Operand val1 = o;
  4908. val0.mode = Addressing_Value;
  4909. val1.mode = Addressing_Value;
  4910. val1.type = t_untyped_bool;
  4911. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4912. if (expr->kind == Ast_TypeAssertion &&
  4913. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4914. // NOTE(bill): Used only for optimizations in the backend
  4915. if (is_blank_ident(lhs[0]->token)) {
  4916. expr->TypeAssertion.ignores[0] = true;
  4917. }
  4918. if (is_blank_ident(lhs[1]->token)) {
  4919. expr->TypeAssertion.ignores[1] = true;
  4920. }
  4921. }
  4922. array_add(operands, val0);
  4923. array_add(operands, val1);
  4924. optional_ok = true;
  4925. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4926. } else {
  4927. array_add(operands, o);
  4928. tuple_index += 1;
  4929. }
  4930. } else {
  4931. TypeTuple *tuple = &o.type->Tuple;
  4932. for (Entity *e : tuple->variables) {
  4933. o.type = e->type;
  4934. array_add(operands, o);
  4935. }
  4936. isize count = tuple->variables.count;
  4937. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4938. }
  4939. }
  4940. return optional_ok;
  4941. }
  4942. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4943. GB_ASSERT(pt != nullptr);
  4944. GB_ASSERT(pt->kind == Type_Proc);
  4945. isize param_count = 0;
  4946. isize param_count_excluding_defaults = 0;
  4947. bool variadic = pt->Proc.variadic;
  4948. TypeTuple *param_tuple = nullptr;
  4949. if (pt->Proc.params != nullptr) {
  4950. param_tuple = &pt->Proc.params->Tuple;
  4951. param_count = param_tuple->variables.count;
  4952. if (variadic) {
  4953. for (isize i = param_count-1; i >= 0; i--) {
  4954. Entity *e = param_tuple->variables[i];
  4955. if (e->kind == Entity_TypeName) {
  4956. break;
  4957. }
  4958. if (e->kind == Entity_Variable) {
  4959. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4960. param_count--;
  4961. continue;
  4962. }
  4963. }
  4964. break;
  4965. }
  4966. param_count--;
  4967. }
  4968. }
  4969. param_count_excluding_defaults = param_count;
  4970. if (param_tuple != nullptr) {
  4971. for (isize i = param_count-1; i >= 0; i--) {
  4972. Entity *e = param_tuple->variables[i];
  4973. if (e->kind == Entity_TypeName) {
  4974. break;
  4975. }
  4976. if (e->kind == Entity_Variable) {
  4977. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4978. param_count_excluding_defaults--;
  4979. continue;
  4980. }
  4981. }
  4982. break;
  4983. }
  4984. }
  4985. if (param_count_) *param_count_ = param_count;
  4986. return param_count_excluding_defaults;
  4987. }
  4988. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4989. isize param_count = pt->param_count;
  4990. for (isize i = 0; i < param_count; i++) {
  4991. Entity *e = pt->params->Tuple.variables[i];
  4992. String name = e->token.string;
  4993. if (is_blank_ident(name)) {
  4994. continue;
  4995. }
  4996. if (name == parameter_name) {
  4997. return i;
  4998. }
  4999. }
  5000. return -1;
  5001. }
  5002. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5003. type = base_type(type);
  5004. GB_ASSERT(type->kind == Type_Proc);
  5005. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5006. }
  5007. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5008. Entity *entity, Type *proc_type,
  5009. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5010. CallArgumentErrorMode show_error_mode,
  5011. CallArgumentData *data) {
  5012. TEMPORARY_ALLOCATOR_GUARD();
  5013. CallArgumentError err = CallArgumentError_None;
  5014. ast_node(ce, CallExpr, call);
  5015. GB_ASSERT(is_type_proc(proc_type));
  5016. proc_type = base_type(proc_type);
  5017. TypeProc *pt = &proc_type->Proc;
  5018. isize param_count = 0;
  5019. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5020. bool variadic = pt->variadic;
  5021. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5022. i64 score = 0;
  5023. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5024. Type *final_proc_type = proc_type;
  5025. Entity *gen_entity = nullptr;
  5026. if (vari_expand && !variadic) {
  5027. if (show_error) {
  5028. error(ce->ellipsis,
  5029. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5030. LIT(ce->proc->Ident.token.string));
  5031. }
  5032. err = CallArgumentError_NonVariadicExpand;
  5033. } else if (vari_expand && pt->c_vararg) {
  5034. if (show_error) {
  5035. error(ce->ellipsis,
  5036. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5037. LIT(ce->proc->Ident.token.string));
  5038. }
  5039. err = CallArgumentError_NonVariadicExpand;
  5040. }
  5041. GB_ASSERT(ce->split_args);
  5042. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5043. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5044. defer ({
  5045. for (Operand const &o : ordered_operands) {
  5046. if (o.expr != nullptr) {
  5047. call->viral_state_flags |= o.expr->viral_state_flags;
  5048. }
  5049. }
  5050. });
  5051. isize positional_operand_count = positional_operands.count;
  5052. if (variadic) {
  5053. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5054. } else if (positional_operand_count > pt->param_count) {
  5055. err = CallArgumentError_TooManyArguments;
  5056. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5057. if (show_error) {
  5058. gbString proc_str = expr_to_string(ce->proc);
  5059. defer (gb_string_free(proc_str));
  5060. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5061. }
  5062. return err;
  5063. }
  5064. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5065. for (isize i = 0; i < positional_operand_count; i++) {
  5066. ordered_operands[i] = positional_operands[i];
  5067. visited[i] = true;
  5068. }
  5069. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5070. bool named_variadic_param = false;
  5071. if (named_operands.count != 0) {
  5072. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5073. for_array(i, ce->split_args->named) {
  5074. Ast *arg = ce->split_args->named[i];
  5075. Operand operand = named_operands[i];
  5076. ast_node(fv, FieldValue, arg);
  5077. if (fv->field->kind != Ast_Ident) {
  5078. if (show_error) {
  5079. gbString expr_str = expr_to_string(fv->field);
  5080. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5081. gb_string_free(expr_str);
  5082. }
  5083. err = CallArgumentError_InvalidFieldValue;
  5084. continue;
  5085. }
  5086. String name = fv->field->Ident.token.string;
  5087. isize param_index = lookup_procedure_parameter(pt, name);
  5088. if (param_index < 0) {
  5089. if (show_error) {
  5090. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5091. }
  5092. err = CallArgumentError_ParameterNotFound;
  5093. continue;
  5094. }
  5095. if (pt->variadic && param_index == pt->variadic_index) {
  5096. named_variadic_param = true;
  5097. }
  5098. if (visited[param_index]) {
  5099. if (show_error) {
  5100. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5101. }
  5102. err = CallArgumentError_DuplicateParameter;
  5103. continue;
  5104. }
  5105. visited[param_index] = true;
  5106. ordered_operands[param_index] = operand;
  5107. }
  5108. }
  5109. isize dummy_argument_count = 0;
  5110. bool actually_variadic = false;
  5111. if (variadic) {
  5112. if (visited[pt->variadic_index] &&
  5113. positional_operand_count < positional_operands.count) {
  5114. if (show_error) {
  5115. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5116. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5117. }
  5118. err = CallArgumentError_DuplicateParameter;
  5119. } else if (!visited[pt->variadic_index]) {
  5120. visited[pt->variadic_index] = true;
  5121. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5122. if (vari_expand) {
  5123. if (variadic_operands.count == 0) {
  5124. error(call, "'..' in the wrong position");
  5125. } else {
  5126. GB_ASSERT(variadic_operands.count != 0);
  5127. *variadic_operand = variadic_operands[0];
  5128. variadic_operand->type = default_type(variadic_operand->type);
  5129. actually_variadic = true;
  5130. }
  5131. } else {
  5132. AstFile *f = call->file();
  5133. // HACK(bill): this is an awful hack
  5134. Operand o = {};
  5135. o.mode = Addressing_Value;
  5136. o.expr = ast_ident(f, make_token_ident("nil"));
  5137. o.expr->Ident.token.pos = ast_token(call).pos;
  5138. if (variadic_operands.count != 0) {
  5139. actually_variadic = true;
  5140. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5141. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5142. o.type = vt->type;
  5143. } else {
  5144. dummy_argument_count += 1;
  5145. o.type = t_untyped_nil;
  5146. }
  5147. *variadic_operand = o;
  5148. }
  5149. }
  5150. }
  5151. for (Operand const &o : ordered_operands) {
  5152. if (o.mode != Addressing_Invalid) {
  5153. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5154. }
  5155. }
  5156. for (isize i = 0; i < pt->param_count; i++) {
  5157. if (!visited[i]) {
  5158. Entity *e = pt->params->Tuple.variables[i];
  5159. if (e->kind == Entity_Variable) {
  5160. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5161. ordered_operands[i].mode = Addressing_Value;
  5162. ordered_operands[i].type = e->type;
  5163. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5164. dummy_argument_count += 1;
  5165. score += assign_score_function(1);
  5166. continue;
  5167. }
  5168. }
  5169. if (show_error) {
  5170. if (e->kind == Entity_TypeName) {
  5171. error(call, "Type parameter '%.*s' is missing in procedure call",
  5172. LIT(e->token.string));
  5173. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5174. // Ignore
  5175. } else {
  5176. gbString str = type_to_string(e->type);
  5177. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5178. LIT(e->token.string), str);
  5179. gb_string_free(str);
  5180. }
  5181. }
  5182. err = CallArgumentError_ParameterMissing;
  5183. }
  5184. }
  5185. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5186. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5187. i64 s = 0;
  5188. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5189. bool ok = false;
  5190. if (e && (e->flags & EntityFlag_AnyInt)) {
  5191. if (is_type_integer(param_type)) {
  5192. ok = check_is_castable_to(c, o, param_type);
  5193. }
  5194. }
  5195. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5196. if (show_error) {
  5197. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5198. }
  5199. }
  5200. if (ok) {
  5201. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5202. } else {
  5203. if (show_error) {
  5204. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5205. }
  5206. err = CallArgumentError_WrongTypes;
  5207. }
  5208. } else if (show_error) {
  5209. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5210. }
  5211. if (e && e->flags & EntityFlag_ConstInput) {
  5212. if (o->mode != Addressing_Constant) {
  5213. if (show_error) {
  5214. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5215. }
  5216. err = CallArgumentError_NoneConstantParameter;
  5217. }
  5218. }
  5219. if (!err && is_type_any(param_type)) {
  5220. add_type_info_type(c, o->type);
  5221. }
  5222. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5223. add_type_info_type(c, o->type);
  5224. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5225. } else if (show_error && is_type_untyped(o->type)) {
  5226. update_untyped_expr_type(c, o->expr, param_type, true);
  5227. }
  5228. return s;
  5229. };
  5230. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5231. err = CallArgumentError_None;
  5232. if (variadic) {
  5233. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5234. Type *t = pt->params->Tuple.variables[0]->type;
  5235. if (is_type_polymorphic(t)) {
  5236. if (show_error) {
  5237. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5238. }
  5239. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5240. }
  5241. }
  5242. } else {
  5243. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5244. PolyProcData poly_proc_data = {};
  5245. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5246. gen_entity = poly_proc_data.gen_entity;
  5247. Type *gept = base_type(gen_entity->type);
  5248. GB_ASSERT(is_type_proc(gept));
  5249. final_proc_type = gen_entity->type;
  5250. pt = &gept->Proc;
  5251. } else {
  5252. err = CallArgumentError_WrongTypes;
  5253. }
  5254. }
  5255. for (isize i = 0; i < pt->param_count; i++) {
  5256. Operand *o = &ordered_operands[i];
  5257. if (o->mode == Addressing_Invalid) {
  5258. continue;
  5259. }
  5260. Entity *e = pt->params->Tuple.variables[i];
  5261. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5262. if (e->kind == Entity_TypeName) {
  5263. GB_ASSERT(pt->is_polymorphic);
  5264. if (o->mode != Addressing_Type) {
  5265. if (show_error) {
  5266. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5267. }
  5268. err = CallArgumentError_WrongTypes;
  5269. }
  5270. if (are_types_identical(e->type, o->type)) {
  5271. score += assign_score_function(1);
  5272. } else {
  5273. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5274. }
  5275. continue;
  5276. }
  5277. if (param_is_variadic) {
  5278. continue;
  5279. }
  5280. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5281. }
  5282. }
  5283. if (variadic) {
  5284. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5285. Type *slice = var_entity->type;
  5286. GB_ASSERT(is_type_slice(slice));
  5287. Type *elem = base_type(slice)->Slice.elem;
  5288. Type *t = elem;
  5289. if (is_type_polymorphic(t)) {
  5290. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5291. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5292. }
  5293. for_array(operand_index, variadic_operands) {
  5294. Operand *o = &variadic_operands[operand_index];
  5295. if (vari_expand) {
  5296. t = slice;
  5297. if (operand_index > 0) {
  5298. if (show_error) {
  5299. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5300. }
  5301. if (data) {
  5302. data->score = score;
  5303. data->result_type = final_proc_type->Proc.results;
  5304. data->gen_entity = gen_entity;
  5305. }
  5306. return CallArgumentError_MultipleVariadicExpand;
  5307. }
  5308. }
  5309. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5310. }
  5311. }
  5312. if (data) {
  5313. data->score = score;
  5314. data->result_type = final_proc_type->Proc.results;
  5315. data->gen_entity = gen_entity;
  5316. Ast *proc_lit = nullptr;
  5317. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5318. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5319. if (vp && vp->kind == Ast_ProcLit) {
  5320. proc_lit = vp;
  5321. }
  5322. }
  5323. if (proc_lit == nullptr) {
  5324. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5325. }
  5326. }
  5327. return err;
  5328. }
  5329. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5330. GB_ASSERT(ce != nullptr);
  5331. if (ce->args.count == 0) {
  5332. return false;
  5333. }
  5334. return ce->args[0]->kind == Ast_FieldValue;
  5335. }
  5336. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5337. Entity **lhs = nullptr;
  5338. isize lhs_count = -1;
  5339. if (proc_type == nullptr) {
  5340. return nullptr;
  5341. }
  5342. GB_ASSERT(is_type_proc(proc_type));
  5343. TypeProc *pt = &base_type(proc_type)->Proc;
  5344. *is_variadic = pt->variadic;
  5345. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5346. if (pt->params != nullptr) {
  5347. lhs = pt->params->Tuple.variables.data;
  5348. lhs_count = pt->params->Tuple.variables.count;
  5349. }
  5350. } else {
  5351. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5352. if (pt->params == nullptr) {
  5353. lhs_count = 0;
  5354. } else {
  5355. lhs_count = pt->params->Tuple.variables.count;
  5356. }
  5357. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5358. for (isize i = 0; i < lhs_count; i++) {
  5359. Entity *e = pt->params->Tuple.variables[i];
  5360. if (!is_type_polymorphic(e->type)) {
  5361. lhs[i] = e;
  5362. }
  5363. }
  5364. }
  5365. if (lhs_count_) *lhs_count_ = lhs_count;
  5366. return lhs;
  5367. }
  5368. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5369. if (clauses != nullptr) {
  5370. for (Ast *clause : *clauses) {
  5371. Operand o = {};
  5372. check_expr(ctx, &o, clause);
  5373. if (o.mode != Addressing_Constant) {
  5374. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5375. if (print_err && call_expr) error(call_expr, "at caller location");
  5376. return false;
  5377. } else if (o.value.kind != ExactValue_Bool) {
  5378. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5379. if (print_err && call_expr) error(call_expr, "at caller location");
  5380. return false;
  5381. } else if (!o.value.value_bool) {
  5382. if (print_err) {
  5383. ERROR_BLOCK();
  5384. gbString str = expr_to_string(clause);
  5385. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5386. gb_string_free(str);
  5387. if (scope != nullptr) {
  5388. isize print_count = 0;
  5389. for (auto const &entry : scope->elements) {
  5390. Entity *e = entry.value;
  5391. switch (e->kind) {
  5392. case Entity_TypeName: {
  5393. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5394. gbString str = type_to_string(e->type);
  5395. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5396. gb_string_free(str);
  5397. print_count += 1;
  5398. break;
  5399. }
  5400. case Entity_Constant: {
  5401. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5402. gbString str = exact_value_to_string(e->Constant.value);
  5403. if (is_type_untyped(e->type)) {
  5404. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5405. } else {
  5406. gbString t = type_to_string(e->type);
  5407. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5408. gb_string_free(t);
  5409. }
  5410. gb_string_free(str);
  5411. print_count += 1;
  5412. break;
  5413. }
  5414. }
  5415. }
  5416. }
  5417. if (call_expr) {
  5418. TokenPos pos = ast_token(call_expr).pos;
  5419. error_line("%s at caller location\n", token_pos_to_string(pos));
  5420. }
  5421. }
  5422. return false;
  5423. }
  5424. }
  5425. }
  5426. return true;
  5427. }
  5428. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5429. bool success = true;
  5430. type = base_type(type);
  5431. if (named_args.count > 0) {
  5432. TypeProc *pt = nullptr;
  5433. if (is_type_proc(type)) {
  5434. pt = &type->Proc;
  5435. }
  5436. for_array(i, named_args) {
  5437. Ast *arg = named_args[i];
  5438. if (arg->kind != Ast_FieldValue) {
  5439. if (show_error) {
  5440. error(arg, "Expected a 'field = value'");
  5441. }
  5442. return false;
  5443. }
  5444. ast_node(fv, FieldValue, arg);
  5445. if (fv->field->kind != Ast_Ident) {
  5446. if (show_error) {
  5447. gbString expr_str = expr_to_string(fv->field);
  5448. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5449. gb_string_free(expr_str);
  5450. }
  5451. success = false;
  5452. continue;
  5453. }
  5454. String key = fv->field->Ident.token.string;
  5455. Ast *value = fv->value;
  5456. Type *type_hint = nullptr;
  5457. if (pt) {
  5458. isize param_index = lookup_procedure_parameter(pt, key);
  5459. if (param_index < 0) {
  5460. if (show_error) {
  5461. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5462. }
  5463. success = false;
  5464. continue;
  5465. }
  5466. Entity *e = pt->params->Tuple.variables[param_index];
  5467. if (!is_type_polymorphic(e->type)) {
  5468. type_hint = e->type;
  5469. }
  5470. }
  5471. Operand o = {};
  5472. check_expr_with_type_hint(c, &o, value, type_hint);
  5473. if (o.mode == Addressing_Invalid) {
  5474. success = false;
  5475. }
  5476. array_add(named_operands, o);
  5477. }
  5478. }
  5479. return success;
  5480. }
  5481. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5482. Entity *e, Type *proc_type,
  5483. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5484. CallArgumentErrorMode show_error_mode,
  5485. CallArgumentData *data) {
  5486. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5487. Ast *ident = operand->expr;
  5488. while (ident->kind == Ast_SelectorExpr) {
  5489. Ast *s = ident->SelectorExpr.selector;
  5490. ident = s;
  5491. }
  5492. if (e == nullptr) {
  5493. e = entity_of_node(ident);
  5494. if (e != nullptr) {
  5495. proc_type = e->type;
  5496. }
  5497. }
  5498. GB_ASSERT(proc_type != nullptr);
  5499. proc_type = base_type(proc_type);
  5500. GB_ASSERT(proc_type->kind == Type_Proc);
  5501. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5502. if (return_on_failure && err != CallArgumentError_None) {
  5503. return false;
  5504. }
  5505. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5506. if (!return_on_failure && entity_to_use != nullptr) {
  5507. add_entity_use(c, ident, entity_to_use);
  5508. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5509. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5510. }
  5511. if (data->gen_entity != nullptr) {
  5512. Entity *e = data->gen_entity;
  5513. DeclInfo *decl = data->gen_entity->decl_info;
  5514. CheckerContext ctx = *c;
  5515. ctx.scope = decl->scope;
  5516. ctx.decl = decl;
  5517. ctx.proc_name = e->token.string;
  5518. ctx.curr_proc_decl = decl;
  5519. ctx.curr_proc_sig = e->type;
  5520. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5521. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5522. if (return_on_failure) {
  5523. if (!ok) {
  5524. return false;
  5525. }
  5526. } else {
  5527. decl->where_clauses_evaluated = true;
  5528. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5529. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5530. }
  5531. if (is_type_proc(data->gen_entity->type)) {
  5532. Type *t = base_type(entity_to_use->type);
  5533. data->result_type = t->Proc.results;
  5534. }
  5535. }
  5536. }
  5537. return true;
  5538. }
  5539. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5540. ast_node(ce, CallExpr, call);
  5541. GB_ASSERT(ce->split_args != nullptr);
  5542. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5543. Slice<Ast *> const &named_args = ce->split_args->named;
  5544. CallArgumentData data = {};
  5545. data.result_type = t_invalid;
  5546. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5547. auto procs = proc_group_entities_cloned(c, *operand);
  5548. if (procs.count > 1) {
  5549. isize max_arg_count = positional_args.count + named_args.count;
  5550. for (Ast *arg : positional_args) {
  5551. // NOTE(bill): The only thing that may have multiple values
  5552. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5553. arg = strip_or_return_expr(arg);
  5554. if (arg && arg->kind == Ast_CallExpr) {
  5555. max_arg_count = ISIZE_MAX;
  5556. break;
  5557. }
  5558. }
  5559. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5560. // NOTE(bill): The only thing that may have multiple values
  5561. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5562. if (arg->kind == Ast_FieldValue) {
  5563. arg = strip_or_return_expr(arg->FieldValue.value);
  5564. if (arg && arg->kind == Ast_CallExpr) {
  5565. max_arg_count = ISIZE_MAX;
  5566. break;
  5567. }
  5568. }
  5569. }
  5570. // ignore named arguments first
  5571. for (Ast *arg : named_args) {
  5572. if (arg->kind != Ast_FieldValue) {
  5573. continue;
  5574. }
  5575. ast_node(fv, FieldValue, arg);
  5576. if (fv->field->kind != Ast_Ident) {
  5577. continue;
  5578. }
  5579. String key = fv->field->Ident.token.string;
  5580. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5581. Type *t = procs[proc_index]->type;
  5582. if (is_type_proc(t)) {
  5583. isize param_index = lookup_procedure_parameter(t, key);
  5584. if (param_index < 0) {
  5585. array_unordered_remove(&procs, proc_index);
  5586. }
  5587. }
  5588. }
  5589. }
  5590. if (procs.count == 0) {
  5591. // if any of the named arguments are wrong, the `procs` will be empty
  5592. // just start from scratch
  5593. array_free(&procs);
  5594. procs = proc_group_entities_cloned(c, *operand);
  5595. }
  5596. // filter by positional argument length
  5597. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5598. Entity *proc = procs[proc_index];
  5599. Type *pt = base_type(proc->type);
  5600. if (!(pt != nullptr && is_type_proc(pt))) {
  5601. proc_index++;
  5602. continue;
  5603. }
  5604. isize param_count = 0;
  5605. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5606. if (param_count_excluding_defaults > max_arg_count) {
  5607. array_unordered_remove(&procs, proc_index);
  5608. continue;
  5609. }
  5610. proc_index++;
  5611. }
  5612. }
  5613. Entity **lhs = nullptr;
  5614. isize lhs_count = -1;
  5615. bool is_variadic = false;
  5616. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5617. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5618. defer (array_free(&positional_operands));
  5619. defer (array_free(&named_operands));
  5620. if (procs.count == 1) {
  5621. Entity *e = procs[0];
  5622. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5623. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5624. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5625. check_call_arguments_single(c, call, operand,
  5626. e, e->type,
  5627. positional_operands, named_operands,
  5628. CallArgumentErrorMode::ShowErrors,
  5629. &data);
  5630. }
  5631. return data;
  5632. }
  5633. {
  5634. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5635. // where the same positional parameter has the same type value (and ellipsis)
  5636. isize proc_arg_count = -1;
  5637. for (Entity *p : procs) {
  5638. Type *pt = base_type(p->type);
  5639. if (pt != nullptr && is_type_proc(pt)) {
  5640. if (proc_arg_count < 0) {
  5641. proc_arg_count = pt->Proc.param_count;
  5642. } else {
  5643. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5644. }
  5645. }
  5646. }
  5647. if (proc_arg_count >= 0) {
  5648. lhs_count = proc_arg_count;
  5649. if (lhs_count > 0) {
  5650. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5651. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5652. Entity *e = nullptr;
  5653. for (Entity *p : procs) {
  5654. Type *pt = base_type(p->type);
  5655. if (!(pt != nullptr && is_type_proc(pt))) {
  5656. continue;
  5657. }
  5658. if (e == nullptr) {
  5659. e = pt->Proc.params->Tuple.variables[param_index];
  5660. } else {
  5661. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5662. if (e == f) {
  5663. continue;
  5664. }
  5665. if (are_types_identical(e->type, f->type)) {
  5666. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5667. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5668. if (ee == fe) {
  5669. continue;
  5670. }
  5671. }
  5672. // NOTE(bill): Entities are not close enough to be used
  5673. e = nullptr;
  5674. break;
  5675. }
  5676. }
  5677. lhs[param_index] = e;
  5678. }
  5679. }
  5680. }
  5681. }
  5682. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5683. for_array(i, named_args) {
  5684. Ast *arg = named_args[i];
  5685. if (arg->kind != Ast_FieldValue) {
  5686. error(arg, "Expected a 'field = value'");
  5687. return data;
  5688. }
  5689. ast_node(fv, FieldValue, arg);
  5690. if (fv->field->kind != Ast_Ident) {
  5691. gbString expr_str = expr_to_string(fv->field);
  5692. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5693. gb_string_free(expr_str);
  5694. return data;
  5695. }
  5696. String key = fv->field->Ident.token.string;
  5697. Ast *value = fv->value;
  5698. Type *type_hint = nullptr;
  5699. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5700. Entity *e = lhs[lhs_idx];
  5701. if (e != nullptr && e->token.string == key &&
  5702. !is_type_polymorphic(e->type)) {
  5703. type_hint = e->type;
  5704. break;
  5705. }
  5706. }
  5707. Operand o = {};
  5708. check_expr_with_type_hint(c, &o, value, type_hint);
  5709. array_add(&named_operands, o);
  5710. }
  5711. gb_free(heap_allocator(), lhs);
  5712. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5713. defer (array_free(&valids));
  5714. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5715. defer (array_free(&proc_entities));
  5716. for (Entity *proc : procs) {
  5717. array_add(&proc_entities, proc);
  5718. }
  5719. gbString expr_name = expr_to_string(operand->expr);
  5720. defer (gb_string_free(expr_name));
  5721. for_array(i, procs) {
  5722. Entity *p = procs[i];
  5723. Type *pt = base_type(p->type);
  5724. if (pt != nullptr && is_type_proc(pt)) {
  5725. CallArgumentData data = {};
  5726. CheckerContext ctx = *c;
  5727. ctx.no_polymorphic_errors = true;
  5728. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5729. ctx.hide_polymorphic_errors = true;
  5730. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5731. p, pt,
  5732. positional_operands, named_operands,
  5733. CallArgumentErrorMode::NoErrors,
  5734. &data);
  5735. if (!is_a_candidate) {
  5736. continue;
  5737. }
  5738. isize index = i;
  5739. ValidIndexAndScore item = {};
  5740. item.score = data.score;
  5741. if (data.gen_entity != nullptr) {
  5742. array_add(&proc_entities, data.gen_entity);
  5743. index = proc_entities.count-1;
  5744. // prefer non-polymorphic procedures over polymorphic
  5745. item.score += assign_score_function(1);
  5746. }
  5747. item.index = index;
  5748. array_add(&valids, item);
  5749. }
  5750. }
  5751. if (valids.count > 1) {
  5752. array_sort(valids, valid_index_and_score_cmp);
  5753. i64 best_score = valids[0].score;
  5754. Entity *best_entity = proc_entities[valids[0].index];
  5755. GB_ASSERT(best_entity != nullptr);
  5756. for (isize i = 1; i < valids.count; i++) {
  5757. if (best_score > valids[i].score) {
  5758. valids.count = i;
  5759. break;
  5760. }
  5761. if (best_entity == proc_entities[valids[i].index]) {
  5762. valids.count = i;
  5763. break;
  5764. }
  5765. }
  5766. }
  5767. auto print_argument_types = [&]() {
  5768. error_line("\tGiven argument types: (");
  5769. isize i = 0;
  5770. for (Operand const &o : positional_operands) {
  5771. if (i++ > 0) error_line(", ");
  5772. gbString type = type_to_string(o.type);
  5773. defer (gb_string_free(type));
  5774. error_line("%s", type);
  5775. }
  5776. for (Operand const &o : named_operands) {
  5777. if (i++ > 0) error_line(", ");
  5778. gbString type = type_to_string(o.type);
  5779. defer (gb_string_free(type));
  5780. if (i < ce->split_args->named.count) {
  5781. Ast *named_field = ce->split_args->named[i];
  5782. ast_node(fv, FieldValue, named_field);
  5783. gbString field = expr_to_string(fv->field);
  5784. defer (gb_string_free(field));
  5785. error_line("%s = %s", field, type);
  5786. } else {
  5787. error_line("%s", type);
  5788. }
  5789. }
  5790. error_line(")\n");
  5791. };
  5792. if (valids.count == 0) {
  5793. ERROR_BLOCK();
  5794. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5795. if (positional_operands.count == 0 && named_operands.count == 0) {
  5796. error_line("\tNo given arguments\n");
  5797. } else {
  5798. print_argument_types();
  5799. }
  5800. if (procs.count == 0) {
  5801. procs = proc_group_entities_cloned(c, *operand);
  5802. }
  5803. if (procs.count > 0) {
  5804. error_line("Did you mean to use one of the following:\n");
  5805. }
  5806. isize max_name_length = 0;
  5807. isize max_type_length = 0;
  5808. for (Entity *proc : procs) {
  5809. Type *t = base_type(proc->type);
  5810. if (t == t_invalid) continue;
  5811. String prefix = {};
  5812. String prefix_sep = {};
  5813. if (proc->pkg) {
  5814. prefix = proc->pkg->name;
  5815. prefix_sep = str_lit(".");
  5816. }
  5817. String name = proc->token.string;
  5818. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5819. gbString pt;
  5820. if (t->Proc.node != nullptr) {
  5821. pt = expr_to_string(t->Proc.node);
  5822. } else {
  5823. pt = type_to_string(t);
  5824. }
  5825. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5826. gb_string_free(pt);
  5827. }
  5828. isize max_spaces = gb_max(max_name_length, max_type_length);
  5829. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5830. for (isize i = 0; i < max_spaces; i++) {
  5831. spaces[i] = ' ';
  5832. }
  5833. spaces[max_spaces] = 0;
  5834. for (Entity *proc : procs) {
  5835. TokenPos pos = proc->token.pos;
  5836. Type *t = base_type(proc->type);
  5837. if (t == t_invalid) continue;
  5838. GB_ASSERT(t->kind == Type_Proc);
  5839. gbString pt;
  5840. defer (gb_string_free(pt));
  5841. if (t->Proc.node != nullptr) {
  5842. pt = expr_to_string(t->Proc.node);
  5843. } else {
  5844. pt = type_to_string(t);
  5845. }
  5846. String prefix = {};
  5847. String prefix_sep = {};
  5848. if (proc->pkg) {
  5849. prefix = proc->pkg->name;
  5850. prefix_sep = str_lit(".");
  5851. }
  5852. String name = proc->token.string;
  5853. isize len = prefix.len + prefix_sep.len + name.len;
  5854. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5855. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5856. char const *sep = "::";
  5857. if (proc->kind == Entity_Variable) {
  5858. sep = ":=";
  5859. }
  5860. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5861. LIT(prefix), LIT(prefix_sep), LIT(name),
  5862. name_padding, spaces,
  5863. sep,
  5864. pt,
  5865. type_padding, spaces,
  5866. token_pos_to_string(pos)
  5867. );
  5868. }
  5869. if (procs.count > 0) {
  5870. error_line("\n");
  5871. }
  5872. data.result_type = t_invalid;
  5873. } else if (valids.count > 1) {
  5874. ERROR_BLOCK();
  5875. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5876. print_argument_types();
  5877. for (auto const &valid : valids) {
  5878. Entity *proc = proc_entities[valid.index];
  5879. GB_ASSERT(proc != nullptr);
  5880. TokenPos pos = proc->token.pos;
  5881. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5882. gbString pt = nullptr;
  5883. defer (gb_string_free(pt));
  5884. if (t->Proc.node != nullptr) {
  5885. pt = expr_to_string(t->Proc.node);
  5886. } else {
  5887. pt = type_to_string(t);
  5888. }
  5889. String name = proc->token.string;
  5890. char const *sep = "::";
  5891. if (proc->kind == Entity_Variable) {
  5892. sep = ":=";
  5893. }
  5894. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5895. if (proc->decl_info->proc_lit != nullptr) {
  5896. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5897. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5898. if (pl->where_token.kind != Token_Invalid) {
  5899. error_line("\n\t\twhere ");
  5900. for_array(j, pl->where_clauses) {
  5901. Ast *clause = pl->where_clauses[j];
  5902. if (j != 0) {
  5903. error_line("\t\t ");
  5904. }
  5905. gbString str = expr_to_string(clause);
  5906. error_line("%s", str);
  5907. gb_string_free(str);
  5908. if (j != pl->where_clauses.count-1) {
  5909. error_line(",");
  5910. }
  5911. }
  5912. error_line("\n\t");
  5913. }
  5914. }
  5915. error_line("at %s\n", token_pos_to_string(pos));
  5916. }
  5917. data.result_type = t_invalid;
  5918. } else {
  5919. GB_ASSERT(valids.count == 1);
  5920. Ast *ident = operand->expr;
  5921. while (ident->kind == Ast_SelectorExpr) {
  5922. Ast *s = ident->SelectorExpr.selector;
  5923. ident = s;
  5924. }
  5925. Entity *e = proc_entities[valids[0].index];
  5926. GB_ASSERT(e != nullptr);
  5927. Array<Operand> named_operands = {};
  5928. check_call_arguments_single(c, call, operand,
  5929. e, e->type,
  5930. positional_operands, named_operands,
  5931. CallArgumentErrorMode::ShowErrors,
  5932. &data);
  5933. return data;
  5934. }
  5935. return data;
  5936. }
  5937. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5938. Type *proc_type = nullptr;
  5939. CallArgumentData data = {};
  5940. data.result_type = t_invalid;
  5941. proc_type = base_type(operand->type);
  5942. TypeProc *pt = nullptr;
  5943. if (proc_type) {
  5944. pt = &proc_type->Proc;
  5945. }
  5946. TEMPORARY_ALLOCATOR_GUARD();
  5947. ast_node(ce, CallExpr, call);
  5948. bool any_failure = false;
  5949. // Split positional and named args into separate arrays/slices
  5950. Slice<Ast *> positional_args = {};
  5951. Slice<Ast *> named_args = {};
  5952. if (ce->split_args == nullptr) {
  5953. positional_args = ce->args;
  5954. for (isize i = 0; i < ce->args.count; i++) {
  5955. Ast *arg = ce->args.data[i];
  5956. if (arg->kind == Ast_FieldValue) {
  5957. positional_args.count = i;
  5958. break;
  5959. }
  5960. }
  5961. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5962. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5963. split_args->positional = positional_args;
  5964. split_args->named = named_args;
  5965. ce->split_args = split_args;
  5966. } else {
  5967. positional_args = ce->split_args->positional;
  5968. named_args = ce->split_args->named;
  5969. }
  5970. if (operand->mode == Addressing_ProcGroup) {
  5971. return check_call_arguments_proc_group(c, operand, call);
  5972. }
  5973. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5974. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5975. defer (array_free(&positional_operands));
  5976. defer (array_free(&named_operands));
  5977. if (positional_args.count > 0) {
  5978. isize lhs_count = -1;
  5979. bool is_variadic = false;
  5980. Entity **lhs = nullptr;
  5981. if (pt != nullptr) {
  5982. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5983. }
  5984. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5985. }
  5986. if (named_args.count > 0) {
  5987. for_array(i, named_args) {
  5988. Ast *arg = named_args[i];
  5989. if (arg->kind != Ast_FieldValue) {
  5990. error(arg, "Expected a 'field = value'");
  5991. return data;
  5992. }
  5993. ast_node(fv, FieldValue, arg);
  5994. if (fv->field->kind != Ast_Ident) {
  5995. gbString expr_str = expr_to_string(fv->field);
  5996. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5997. any_failure = true;
  5998. gb_string_free(expr_str);
  5999. continue;
  6000. }
  6001. String key = fv->field->Ident.token.string;
  6002. Ast *value = fv->value;
  6003. isize param_index = lookup_procedure_parameter(pt, key);
  6004. Type *type_hint = nullptr;
  6005. if (param_index >= 0) {
  6006. Entity *e = pt->params->Tuple.variables[param_index];
  6007. type_hint = e->type;
  6008. }
  6009. Operand o = {};
  6010. check_expr_with_type_hint(c, &o, value, type_hint);
  6011. if (o.mode == Addressing_Invalid) {
  6012. any_failure = true;
  6013. }
  6014. array_add(&named_operands, o);
  6015. }
  6016. }
  6017. if (!any_failure) {
  6018. check_call_arguments_single(c, call, operand,
  6019. nullptr, proc_type,
  6020. positional_operands, named_operands,
  6021. CallArgumentErrorMode::ShowErrors,
  6022. &data);
  6023. } else if (pt) {
  6024. data.result_type = pt->results;
  6025. }
  6026. return data;
  6027. }
  6028. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6029. if (!is_type_polymorphic_record(t)) {
  6030. return -1;
  6031. }
  6032. TypeTuple *params = get_record_polymorphic_params(t);
  6033. if (params == nullptr) {
  6034. return -1;
  6035. }
  6036. for_array(i, params->variables) {
  6037. Entity *e = params->variables[i];
  6038. String name = e->token.string;
  6039. if (is_blank_ident(name)) {
  6040. continue;
  6041. }
  6042. if (name == parameter_name) {
  6043. return i;
  6044. }
  6045. }
  6046. return -1;
  6047. }
  6048. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6049. ast_node(ce, CallExpr, call);
  6050. Type *original_type = operand->type;
  6051. GB_ASSERT(is_type_polymorphic_record(original_type));
  6052. bool show_error = true;
  6053. Array<Operand> operands = {};
  6054. defer (array_free(&operands));
  6055. bool named_fields = false;
  6056. {
  6057. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6058. auto prev_type_path = c->type_path;
  6059. c->type_path = new_checker_type_path();
  6060. defer ({
  6061. destroy_checker_type_path(c->type_path);
  6062. c->type_path = prev_type_path;
  6063. });
  6064. if (is_call_expr_field_value(ce)) {
  6065. named_fields = true;
  6066. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6067. for_array(i, ce->args) {
  6068. Ast *arg = ce->args[i];
  6069. ast_node(fv, FieldValue, arg);
  6070. if (fv->field->kind == Ast_Ident) {
  6071. String name = fv->field->Ident.token.string;
  6072. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6073. if (index >= 0) {
  6074. TypeTuple *params = get_record_polymorphic_params(original_type);
  6075. Entity *e = params->variables[index];
  6076. if (e->kind == Entity_Constant) {
  6077. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6078. continue;
  6079. }
  6080. }
  6081. }
  6082. check_expr_or_type(c, &operands[i], fv->value);
  6083. }
  6084. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6085. if (vari_expand) {
  6086. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6087. }
  6088. } else {
  6089. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6090. Entity **lhs = nullptr;
  6091. isize lhs_count = -1;
  6092. TypeTuple *params = get_record_polymorphic_params(original_type);
  6093. if (params != nullptr) {
  6094. lhs = params->variables.data;
  6095. lhs_count = params->variables.count;
  6096. }
  6097. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6098. }
  6099. }
  6100. CallArgumentError err = CallArgumentError_None;
  6101. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6102. isize param_count = tuple->variables.count;
  6103. isize minimum_param_count = param_count;
  6104. for (; minimum_param_count > 0; minimum_param_count--) {
  6105. Entity *e = tuple->variables[minimum_param_count-1];
  6106. if (e->kind != Entity_Constant) {
  6107. break;
  6108. }
  6109. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6110. break;
  6111. }
  6112. }
  6113. Array<Operand> ordered_operands = operands;
  6114. if (!named_fields) {
  6115. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6116. array_copy(&ordered_operands, operands, 0);
  6117. } else {
  6118. TEMPORARY_ALLOCATOR_GUARD();
  6119. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6120. // LEAK(bill)
  6121. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6122. for_array(i, ce->args) {
  6123. Ast *arg = ce->args[i];
  6124. ast_node(fv, FieldValue, arg);
  6125. if (fv->field->kind != Ast_Ident) {
  6126. if (show_error) {
  6127. gbString expr_str = expr_to_string(fv->field);
  6128. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6129. gb_string_free(expr_str);
  6130. }
  6131. err = CallArgumentError_InvalidFieldValue;
  6132. continue;
  6133. }
  6134. String name = fv->field->Ident.token.string;
  6135. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6136. if (index < 0) {
  6137. if (show_error) {
  6138. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6139. }
  6140. err = CallArgumentError_ParameterNotFound;
  6141. continue;
  6142. }
  6143. if (visited[index]) {
  6144. if (show_error) {
  6145. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6146. }
  6147. err = CallArgumentError_DuplicateParameter;
  6148. continue;
  6149. }
  6150. visited[index] = true;
  6151. ordered_operands[index] = operands[i];
  6152. }
  6153. for (isize i = 0; i < param_count; i++) {
  6154. if (!visited[i]) {
  6155. Entity *e = tuple->variables[i];
  6156. if (is_blank_ident(e->token)) {
  6157. continue;
  6158. }
  6159. if (show_error) {
  6160. if (e->kind == Entity_TypeName) {
  6161. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6162. LIT(e->token.string));
  6163. } else {
  6164. gbString str = type_to_string(e->type);
  6165. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6166. LIT(e->token.string), str);
  6167. gb_string_free(str);
  6168. }
  6169. }
  6170. err = CallArgumentError_ParameterMissing;
  6171. }
  6172. }
  6173. }
  6174. if (err != 0) {
  6175. operand->mode = Addressing_Invalid;
  6176. return err;
  6177. }
  6178. while (ordered_operands.count > 0) {
  6179. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6180. break;
  6181. }
  6182. array_pop(&ordered_operands);
  6183. }
  6184. if (minimum_param_count != param_count) {
  6185. if (param_count < ordered_operands.count) {
  6186. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6187. err = CallArgumentError_TooManyArguments;
  6188. } else if (minimum_param_count > ordered_operands.count) {
  6189. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6190. err = CallArgumentError_TooFewArguments;
  6191. }
  6192. } else {
  6193. if (param_count < ordered_operands.count) {
  6194. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6195. err = CallArgumentError_TooManyArguments;
  6196. } else if (param_count > ordered_operands.count) {
  6197. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6198. err = CallArgumentError_TooFewArguments;
  6199. }
  6200. }
  6201. if (err != 0) {
  6202. return err;
  6203. }
  6204. if (minimum_param_count != param_count) {
  6205. array_resize(&ordered_operands, param_count);
  6206. isize missing_count = 0;
  6207. // NOTE(bill): Replace missing operands with the default values (if possible)
  6208. for_array(i, ordered_operands) {
  6209. Operand *o = &ordered_operands[i];
  6210. if (o->expr == nullptr) {
  6211. Entity *e = tuple->variables[i];
  6212. if (e->kind == Entity_Constant) {
  6213. missing_count += 1;
  6214. o->mode = Addressing_Constant;
  6215. o->type = default_type(e->type);
  6216. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6217. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6218. o->value = e->Constant.param_value.value;
  6219. }
  6220. } else if (e->kind == Entity_TypeName) {
  6221. missing_count += 1;
  6222. o->mode = Addressing_Type;
  6223. o->type = e->type;
  6224. o->expr = e->identifier;
  6225. }
  6226. }
  6227. }
  6228. }
  6229. isize oo_count = gb_min(param_count, ordered_operands.count);
  6230. i64 score = 0;
  6231. for (isize i = 0; i < oo_count; i++) {
  6232. Entity *e = tuple->variables[i];
  6233. Operand *o = &ordered_operands[i];
  6234. if (o->mode == Addressing_Invalid) {
  6235. continue;
  6236. }
  6237. if (e->kind == Entity_TypeName) {
  6238. if (o->mode != Addressing_Type) {
  6239. if (show_error) {
  6240. gbString expr = expr_to_string(o->expr);
  6241. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6242. gb_string_free(expr);
  6243. }
  6244. err = CallArgumentError_WrongTypes;
  6245. }
  6246. if (are_types_identical(e->type, o->type)) {
  6247. score += assign_score_function(1);
  6248. } else {
  6249. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6250. }
  6251. } else {
  6252. i64 s = 0;
  6253. if (o->type->kind == Type_Generic) {
  6254. // Polymorphic name!
  6255. score += assign_score_function(1);
  6256. continue;
  6257. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6258. if (show_error) {
  6259. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6260. }
  6261. err = CallArgumentError_WrongTypes;
  6262. }
  6263. o->type = e->type;
  6264. if (o->mode != Addressing_Constant) {
  6265. bool valid = false;
  6266. if (is_type_proc(o->type)) {
  6267. Entity *proc_entity = entity_from_expr(o->expr);
  6268. valid = proc_entity != nullptr;
  6269. }
  6270. if (!valid) {
  6271. if (show_error) {
  6272. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6273. }
  6274. err = CallArgumentError_NoneConstantParameter;
  6275. }
  6276. }
  6277. score += s;
  6278. }
  6279. // NOTE(bill): Add type info the parameters
  6280. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6281. // add_type_info_type(c, o->type);
  6282. }
  6283. if (show_error && err) {
  6284. return err;
  6285. }
  6286. {
  6287. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6288. mutex_lock(&found_gen_types->mutex);
  6289. defer (mutex_unlock(&found_gen_types->mutex));
  6290. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6291. if (found_entity) {
  6292. operand->mode = Addressing_Type;
  6293. operand->type = found_entity->type;
  6294. return err;
  6295. }
  6296. CheckerContext ctx = *c;
  6297. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6298. ctx.scope = polymorphic_record_parent_scope(original_type);
  6299. GB_ASSERT(ctx.scope != nullptr);
  6300. Type *bt = base_type(original_type);
  6301. String generated_name = make_string_c(expr_to_string(call));
  6302. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6303. if (bt->kind == Type_Struct) {
  6304. Ast *node = clone_ast(bt->Struct.node);
  6305. Type *struct_type = alloc_type_struct();
  6306. struct_type->Struct.node = node;
  6307. struct_type->Struct.polymorphic_parent = original_type;
  6308. set_base_type(named_type, struct_type);
  6309. check_open_scope(&ctx, node);
  6310. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6311. check_close_scope(&ctx);
  6312. } else if (bt->kind == Type_Union) {
  6313. Ast *node = clone_ast(bt->Union.node);
  6314. Type *union_type = alloc_type_union();
  6315. union_type->Union.node = node;
  6316. union_type->Union.polymorphic_parent = original_type;
  6317. set_base_type(named_type, union_type);
  6318. check_open_scope(&ctx, node);
  6319. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6320. check_close_scope(&ctx);
  6321. } else {
  6322. GB_PANIC("Unsupported parametric polymorphic record type");
  6323. }
  6324. bt = base_type(named_type);
  6325. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6326. GB_ASSERT(original_type->kind == Type_Named);
  6327. Entity *e = original_type->Named.type_name;
  6328. GB_ASSERT(e->kind == Entity_TypeName);
  6329. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6330. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6331. Type *params = nullptr;
  6332. switch (bt->kind) {
  6333. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6334. case Type_Union: params = bt->Union.polymorphic_params; break;
  6335. }
  6336. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6337. Entity *v = params->Tuple.variables[i];
  6338. String name = v->token.string;
  6339. if (i > 0) {
  6340. s = gb_string_append_fmt(s, ", ");
  6341. }
  6342. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6343. if (v->kind == Entity_TypeName) {
  6344. if (v->type->kind != Type_Generic) {
  6345. s = gb_string_append_fmt(s, "=");
  6346. s = write_type_to_string(s, v->type, false);
  6347. }
  6348. } else if (v->kind == Entity_Constant) {
  6349. s = gb_string_append_fmt(s, "=");
  6350. s = write_exact_value_to_string(s, v->Constant.value);
  6351. }
  6352. }
  6353. s = gb_string_append_fmt(s, ")");
  6354. String new_name = make_string_c(s);
  6355. named_type->Named.name = new_name;
  6356. if (named_type->Named.type_name) {
  6357. named_type->Named.type_name->token.string = new_name;
  6358. }
  6359. }
  6360. operand->mode = Addressing_Type;
  6361. operand->type = named_type;
  6362. }
  6363. return err;
  6364. }
  6365. // returns true on success
  6366. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6367. bool success = true;
  6368. if (args.count > 0) {
  6369. if (allow_mixed) {
  6370. bool was_named = false;
  6371. for (Ast *arg : args) {
  6372. if (was_named && arg->kind != Ast_FieldValue) {
  6373. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6374. success = false;
  6375. break;
  6376. }
  6377. was_named = was_named || arg->kind == Ast_FieldValue;
  6378. }
  6379. } else {
  6380. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6381. for (Ast *arg : args) {
  6382. bool mix = false;
  6383. if (first_is_field_value) {
  6384. mix = arg->kind != Ast_FieldValue;
  6385. } else {
  6386. mix = arg->kind == Ast_FieldValue;
  6387. }
  6388. if (mix) {
  6389. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6390. success = false;
  6391. }
  6392. }
  6393. }
  6394. }
  6395. return success;
  6396. }
  6397. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6398. operand->mode = Addressing_Invalid; \
  6399. operand->expr = call; \
  6400. return Expr_Stmt; \
  6401. }
  6402. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6403. if (proc != nullptr &&
  6404. proc->kind == Ast_BasicDirective) {
  6405. ast_node(bd, BasicDirective, proc);
  6406. String name = bd->name.string;
  6407. if (
  6408. name == "location" ||
  6409. name == "assert" ||
  6410. name == "panic" ||
  6411. name == "defined" ||
  6412. name == "config" ||
  6413. name == "load" ||
  6414. name == "load_directory" ||
  6415. name == "load_hash"
  6416. ) {
  6417. operand->mode = Addressing_Builtin;
  6418. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6419. operand->expr = proc;
  6420. operand->type = t_invalid;
  6421. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6422. } else {
  6423. error(proc, "Unknown directive: #%.*s", LIT(name));
  6424. operand->expr = proc;
  6425. operand->type = t_invalid;
  6426. operand->mode = Addressing_Invalid;
  6427. return Expr_Expr;
  6428. }
  6429. if (inlining != ProcInlining_none) {
  6430. error(call, "Inlining operators are not allowed on built-in procedures");
  6431. }
  6432. } else {
  6433. if (proc != nullptr) {
  6434. check_expr_or_type(c, operand, proc);
  6435. } else {
  6436. GB_ASSERT(operand->expr != nullptr);
  6437. }
  6438. }
  6439. if (operand->mode == Addressing_Invalid) {
  6440. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6441. for (Ast *arg : args) {
  6442. if (arg->kind == Ast_FieldValue) {
  6443. arg = arg->FieldValue.value;
  6444. }
  6445. check_expr_base(c, operand, arg, nullptr);
  6446. }
  6447. operand->mode = Addressing_Invalid;
  6448. operand->expr = call;
  6449. return Expr_Stmt;
  6450. }
  6451. if (operand->mode == Addressing_Type) {
  6452. Type *t = operand->type;
  6453. if (is_type_polymorphic_record(t)) {
  6454. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6455. if (!is_type_named(t)) {
  6456. gbString s = expr_to_string(operand->expr);
  6457. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6458. gb_string_free(s);
  6459. operand->mode = Addressing_Invalid;
  6460. operand->type = t_invalid;;
  6461. return Expr_Expr;
  6462. }
  6463. auto err = check_polymorphic_record_type(c, operand, call);
  6464. if (err == 0) {
  6465. Ast *ident = operand->expr;
  6466. while (ident->kind == Ast_SelectorExpr) {
  6467. Ast *s = ident->SelectorExpr.selector;
  6468. ident = s;
  6469. }
  6470. Type *ot = operand->type;
  6471. GB_ASSERT(ot->kind == Type_Named);
  6472. Entity *e = ot->Named.type_name;
  6473. add_entity_use(c, ident, e);
  6474. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6475. } else {
  6476. operand->mode = Addressing_Invalid;
  6477. operand->type = t_invalid;
  6478. }
  6479. } else {
  6480. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6481. operand->mode = Addressing_Invalid;
  6482. isize arg_count = args.count;
  6483. switch (arg_count) {
  6484. case 0:
  6485. {
  6486. gbString str = type_to_string(t);
  6487. error(call, "Missing argument in conversion to '%s'", str);
  6488. gb_string_free(str);
  6489. } break;
  6490. default:
  6491. {
  6492. gbString str = type_to_string(t);
  6493. error(call, "Too many arguments in conversion to '%s'", str);
  6494. gb_string_free(str);
  6495. } break;
  6496. case 1: {
  6497. Ast *arg = args[0];
  6498. if (arg->kind == Ast_FieldValue) {
  6499. error(call, "'field = value' cannot be used in a type conversion");
  6500. arg = arg->FieldValue.value;
  6501. // NOTE(bill): Carry on the cast regardless
  6502. }
  6503. check_expr_with_type_hint(c, operand, arg, t);
  6504. if (operand->mode != Addressing_Invalid) {
  6505. if (is_type_polymorphic(t)) {
  6506. error(call, "A polymorphic type cannot be used in a type conversion");
  6507. } else {
  6508. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6509. // as it assumes it is determining the type
  6510. check_cast(c, operand, t);
  6511. }
  6512. }
  6513. operand->type = t;
  6514. operand->expr = call;
  6515. if (operand->mode != Addressing_Invalid) {
  6516. update_untyped_expr_type(c, arg, t, false);
  6517. }
  6518. break;
  6519. }
  6520. }
  6521. }
  6522. return Expr_Expr;
  6523. }
  6524. if (operand->mode == Addressing_Builtin) {
  6525. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6526. i32 id = operand->builtin_id;
  6527. Entity *e = entity_of_node(operand->expr);
  6528. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6529. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6530. }
  6531. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6532. operand->mode = Addressing_Invalid;
  6533. operand->type = t_invalid;
  6534. }
  6535. operand->expr = call;
  6536. return builtin_procs[id].kind;
  6537. }
  6538. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6539. Entity *initial_entity = entity_of_node(operand->expr);
  6540. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6541. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6542. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6543. if (c->decl) {
  6544. c->decl->defer_used += 1;
  6545. }
  6546. }
  6547. add_entity_use(c, operand->expr, initial_entity);
  6548. if (initial_entity->Procedure.entry_point_only) {
  6549. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6550. // Okay
  6551. } else {
  6552. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6553. }
  6554. }
  6555. }
  6556. if (operand->mode != Addressing_ProcGroup) {
  6557. Type *proc_type = base_type(operand->type);
  6558. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6559. bool valid_mode = is_operand_value(*operand);
  6560. if (!valid_type || !valid_mode) {
  6561. Ast *e = operand->expr;
  6562. gbString str = expr_to_string(e);
  6563. gbString type_str = type_to_string(operand->type);
  6564. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6565. gb_string_free(type_str);
  6566. gb_string_free(str);
  6567. operand->mode = Addressing_Invalid;
  6568. operand->expr = call;
  6569. return Expr_Stmt;
  6570. }
  6571. }
  6572. CallArgumentData data = check_call_arguments(c, operand, call);
  6573. Type *result_type = data.result_type;
  6574. gb_zero_item(operand);
  6575. operand->expr = call;
  6576. if (result_type == t_invalid) {
  6577. operand->mode = Addressing_Invalid;
  6578. operand->type = t_invalid;
  6579. return Expr_Stmt;
  6580. }
  6581. Type *pt = base_type(operand->type);
  6582. if (pt == nullptr) {
  6583. pt = t_invalid;
  6584. }
  6585. if (pt == t_invalid) {
  6586. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6587. pt = type_of_expr(operand->expr->CallExpr.proc);
  6588. }
  6589. if (pt == t_invalid && data.gen_entity) {
  6590. pt = data.gen_entity->type;
  6591. }
  6592. }
  6593. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6594. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6595. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6596. }
  6597. }
  6598. if (result_type == nullptr) {
  6599. operand->mode = Addressing_NoValue;
  6600. } else {
  6601. GB_ASSERT(is_type_tuple(result_type));
  6602. isize count = result_type->Tuple.variables.count;
  6603. switch (count) {
  6604. case 0:
  6605. operand->mode = Addressing_NoValue;
  6606. break;
  6607. case 1:
  6608. operand->mode = Addressing_Value;
  6609. operand->type = result_type->Tuple.variables[0]->type;
  6610. break;
  6611. default:
  6612. operand->mode = Addressing_Value;
  6613. operand->type = result_type;
  6614. break;
  6615. }
  6616. }
  6617. switch (inlining) {
  6618. case ProcInlining_inline:
  6619. if (proc != nullptr) {
  6620. Entity *e = entity_from_expr(proc);
  6621. if (e != nullptr && e->kind == Entity_Procedure) {
  6622. DeclInfo *decl = e->decl_info;
  6623. if (decl->proc_lit) {
  6624. ast_node(pl, ProcLit, decl->proc_lit);
  6625. if (pl->inlining == ProcInlining_no_inline) {
  6626. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6627. }
  6628. }
  6629. }
  6630. }
  6631. break;
  6632. case ProcInlining_no_inline:
  6633. break;
  6634. }
  6635. operand->expr = call;
  6636. {
  6637. Type *type = nullptr;
  6638. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6639. type = type_of_expr(operand->expr->CallExpr.proc);
  6640. }
  6641. if (type == nullptr) {
  6642. type = pt;
  6643. }
  6644. type = base_type(type);
  6645. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6646. operand->mode = Addressing_OptionalOk;
  6647. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6648. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6649. operand->expr->CallExpr.optional_ok_one = true;
  6650. }
  6651. }
  6652. }
  6653. return Expr_Expr;
  6654. }
  6655. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6656. check_expr_base(c, o, e, t);
  6657. check_not_tuple(c, o);
  6658. char const *err_str = nullptr;
  6659. switch (o->mode) {
  6660. case Addressing_NoValue:
  6661. err_str = "used as a value";
  6662. break;
  6663. case Addressing_Type:
  6664. if (t == nullptr || !is_type_typeid(t)) {
  6665. err_str = "is not an expression but a type, in this context it is ambiguous";
  6666. }
  6667. break;
  6668. case Addressing_Builtin:
  6669. err_str = "must be called";
  6670. break;
  6671. }
  6672. if (err_str != nullptr) {
  6673. gbString str = expr_to_string(e);
  6674. error(e, "'%s' %s", str, err_str);
  6675. gb_string_free(str);
  6676. o->mode = Addressing_Invalid;
  6677. }
  6678. }
  6679. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6680. switch (t->kind) {
  6681. case Type_Basic:
  6682. if (t->Basic.kind == Basic_string) {
  6683. if (o->mode == Addressing_Constant) {
  6684. *max_count = o->value.value_string.len;
  6685. }
  6686. if (o->mode != Addressing_Constant) {
  6687. o->mode = Addressing_Value;
  6688. }
  6689. o->type = t_u8;
  6690. return true;
  6691. } else if (t->Basic.kind == Basic_UntypedString) {
  6692. if (o->mode == Addressing_Constant) {
  6693. *max_count = o->value.value_string.len;
  6694. o->type = t_u8;
  6695. return true;
  6696. }
  6697. return false;
  6698. }
  6699. break;
  6700. case Type_MultiPointer:
  6701. o->type = t->MultiPointer.elem;
  6702. if (o->mode != Addressing_Constant) {
  6703. o->mode = Addressing_Variable;
  6704. }
  6705. return true;
  6706. case Type_Array:
  6707. *max_count = t->Array.count;
  6708. if (indirection) {
  6709. o->mode = Addressing_Variable;
  6710. } else if (o->mode != Addressing_Variable &&
  6711. o->mode != Addressing_Constant) {
  6712. o->mode = Addressing_Value;
  6713. }
  6714. o->type = t->Array.elem;
  6715. return true;
  6716. case Type_EnumeratedArray:
  6717. *max_count = t->EnumeratedArray.count;
  6718. if (indirection) {
  6719. o->mode = Addressing_Variable;
  6720. } else if (o->mode != Addressing_Variable &&
  6721. o->mode != Addressing_Constant) {
  6722. o->mode = Addressing_Value;
  6723. }
  6724. o->type = t->EnumeratedArray.elem;
  6725. return true;
  6726. case Type_Matrix:
  6727. *max_count = t->Matrix.column_count;
  6728. if (indirection) {
  6729. o->mode = Addressing_Variable;
  6730. } else if (o->mode != Addressing_Variable) {
  6731. o->mode = Addressing_Value;
  6732. }
  6733. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6734. return true;
  6735. case Type_Slice:
  6736. o->type = t->Slice.elem;
  6737. if (o->mode != Addressing_Constant) {
  6738. o->mode = Addressing_Variable;
  6739. }
  6740. return true;
  6741. case Type_RelativeMultiPointer:
  6742. {
  6743. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6744. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6745. o->type = pointer_type->MultiPointer.elem;
  6746. if (o->mode != Addressing_Constant) {
  6747. o->mode = Addressing_Variable;
  6748. }
  6749. }
  6750. return true;
  6751. case Type_DynamicArray:
  6752. o->type = t->DynamicArray.elem;
  6753. if (o->mode != Addressing_Constant) {
  6754. o->mode = Addressing_Variable;
  6755. }
  6756. return true;
  6757. case Type_Struct:
  6758. if (t->Struct.soa_kind != StructSoa_None) {
  6759. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6760. *max_count = t->Struct.soa_count;
  6761. }
  6762. o->type = t->Struct.soa_elem;
  6763. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  6764. o->mode = Addressing_SoaVariable;
  6765. } else {
  6766. o->mode = Addressing_Value;
  6767. }
  6768. return true;
  6769. }
  6770. return false;
  6771. }
  6772. if (is_type_pointer(original_type) && indirection) {
  6773. Type *ptr = base_type(original_type);
  6774. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6775. o->type = ptr->Pointer.elem;
  6776. o->mode = Addressing_Value;
  6777. return true;
  6778. }
  6779. }
  6780. return false;
  6781. }
  6782. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6783. if (is_type_untyped_uninit(x)) {
  6784. return true;
  6785. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6786. return true;
  6787. } else if (is_type_untyped_uninit(y)) {
  6788. return true;
  6789. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6790. return true;
  6791. }
  6792. return are_types_identical(x, y);
  6793. }
  6794. 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) {
  6795. if (!is_ast_range(node)) {
  6796. return false;
  6797. }
  6798. ast_node(ie, BinaryExpr, node);
  6799. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6800. if (x->mode == Addressing_Invalid) {
  6801. return false;
  6802. }
  6803. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6804. if (y->mode == Addressing_Invalid) {
  6805. return false;
  6806. }
  6807. convert_to_typed(c, x, y->type);
  6808. if (x->mode == Addressing_Invalid) {
  6809. return false;
  6810. }
  6811. convert_to_typed(c, y, x->type);
  6812. if (y->mode == Addressing_Invalid) {
  6813. return false;
  6814. }
  6815. convert_to_typed(c, x, default_type(y->type));
  6816. if (x->mode == Addressing_Invalid) {
  6817. return false;
  6818. }
  6819. convert_to_typed(c, y, default_type(x->type));
  6820. if (y->mode == Addressing_Invalid) {
  6821. return false;
  6822. }
  6823. if (!are_types_identical(x->type, y->type)) {
  6824. if (x->type != t_invalid &&
  6825. y->type != t_invalid) {
  6826. gbString xt = type_to_string(x->type);
  6827. gbString yt = type_to_string(y->type);
  6828. gbString expr_str = expr_to_string(x->expr);
  6829. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6830. gb_string_free(expr_str);
  6831. gb_string_free(yt);
  6832. gb_string_free(xt);
  6833. }
  6834. return false;
  6835. }
  6836. Type *type = x->type;
  6837. if (is_for_loop) {
  6838. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6839. error(ie->op, "Only numerical types are allowed within interval expressions");
  6840. return false;
  6841. }
  6842. } else {
  6843. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6844. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6845. return false;
  6846. }
  6847. }
  6848. if (x->mode == Addressing_Constant &&
  6849. y->mode == Addressing_Constant) {
  6850. ExactValue a = x->value;
  6851. ExactValue b = y->value;
  6852. GB_ASSERT(are_types_identical(x->type, y->type));
  6853. TokenKind op = Token_Lt;
  6854. switch (ie->op.kind) {
  6855. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6856. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6857. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6858. default: error(ie->op, "Invalid range operator"); break;
  6859. }
  6860. bool ok = compare_exact_values(op, a, b);
  6861. if (!ok) {
  6862. // TODO(bill): Better error message
  6863. error(ie->op, "Invalid interval range");
  6864. return false;
  6865. }
  6866. ExactValue inline_for_depth = exact_value_sub(b, a);
  6867. if (ie->op.kind != Token_RangeHalf) {
  6868. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6869. }
  6870. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6871. } else if (inline_for_depth_ != nullptr) {
  6872. error(ie->op, "Interval expressions must be constant");
  6873. return false;
  6874. }
  6875. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6876. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6877. return true;
  6878. }
  6879. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6880. if (is_operand_nil(*o)) {
  6881. return true;
  6882. }
  6883. Ast *expr = unparen_expr(o->expr);
  6884. if (expr != nullptr) {
  6885. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6886. if (e != nullptr && e->kind == Entity_Procedure) {
  6887. return true;
  6888. }
  6889. if (expr->kind == Ast_ProcLit) {
  6890. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6891. return true;
  6892. }
  6893. }
  6894. return o->mode == Addressing_Constant;
  6895. }
  6896. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6897. if (is_type_enum(th)) {
  6898. Type *enum_type = base_type(th);
  6899. GB_ASSERT(enum_type->kind == Type_Enum);
  6900. String name = ise->selector->Ident.token.string;
  6901. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6902. if (e == nullptr) {
  6903. return false;
  6904. }
  6905. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6906. GB_ASSERT(e->kind == Entity_Constant);
  6907. o->value = e->Constant.value;
  6908. o->mode = Addressing_Constant;
  6909. o->type = e->type;
  6910. return true;
  6911. }
  6912. if (is_type_union(th)) {
  6913. TEMPORARY_ALLOCATOR_GUARD();
  6914. Type *union_type = base_type(th);
  6915. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6916. for (Type *vt : union_type->Union.variants) {
  6917. Operand x = {};
  6918. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6919. array_add(&operands, x);
  6920. }
  6921. }
  6922. if (operands.count == 1) {
  6923. *o = operands[0];
  6924. return true;
  6925. }
  6926. }
  6927. return false;
  6928. }
  6929. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6930. ast_node(ise, ImplicitSelectorExpr, node);
  6931. o->type = t_invalid;
  6932. o->expr = node;
  6933. o->mode = Addressing_Invalid;
  6934. Type *th = type_hint;
  6935. if (th == nullptr) {
  6936. gbString str = expr_to_string(node);
  6937. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6938. gb_string_free(str);
  6939. return Expr_Expr;
  6940. }
  6941. o->type = th;
  6942. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6943. if (!ok) {
  6944. String name = ise->selector->Ident.token.string;
  6945. if (is_type_enum(th)) {
  6946. ERROR_BLOCK();
  6947. Type *bt = base_type(th);
  6948. GB_ASSERT(bt->kind == Type_Enum);
  6949. gbString typ = type_to_string(th);
  6950. defer (gb_string_free(typ));
  6951. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6952. check_did_you_mean_type(name, bt->Enum.fields);
  6953. } else {
  6954. gbString typ = type_to_string(th);
  6955. gbString str = expr_to_string(node);
  6956. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6957. gb_string_free(str);
  6958. gb_string_free(typ);
  6959. }
  6960. }
  6961. o->expr = node;
  6962. return Expr_Expr;
  6963. }
  6964. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  6965. switch (x->mode) {
  6966. case Addressing_MapIndex:
  6967. case Addressing_OptionalOk:
  6968. case Addressing_OptionalOkPtr:
  6969. if (val_type_) *val_type_ = x->type;
  6970. break;
  6971. default:
  6972. if (ok_type_) *ok_type_ = x->type;
  6973. return;
  6974. }
  6975. Ast *expr = unparen_expr(x->expr);
  6976. if (expr->kind == Ast_CallExpr) {
  6977. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6978. if (is_type_proc(pt)) {
  6979. Type *tuple = pt->Proc.results;
  6980. if (pt->Proc.result_count >= 2) {
  6981. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6982. }
  6983. if (change_operand) {
  6984. expr->CallExpr.optional_ok_one = false;
  6985. x->type = tuple;
  6986. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6987. }
  6988. return;
  6989. }
  6990. }
  6991. Type *tuple = make_optional_ok_type(x->type);
  6992. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6993. if (change_operand) {
  6994. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6995. x->type = tuple;
  6996. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6997. }
  6998. }
  6999. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7000. ast_node(ie, MatrixIndexExpr, node);
  7001. check_expr(c, o, ie->expr);
  7002. node->viral_state_flags |= ie->expr->viral_state_flags;
  7003. if (o->mode == Addressing_Invalid) {
  7004. o->expr = node;
  7005. return;
  7006. }
  7007. Type *t = base_type(type_deref(o->type));
  7008. bool is_ptr = is_type_pointer(o->type);
  7009. bool is_const = o->mode == Addressing_Constant;
  7010. if (t->kind != Type_Matrix) {
  7011. gbString str = expr_to_string(o->expr);
  7012. gbString type_str = type_to_string(o->type);
  7013. defer (gb_string_free(str));
  7014. defer (gb_string_free(type_str));
  7015. if (is_const) {
  7016. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7017. } else {
  7018. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7019. }
  7020. o->mode = Addressing_Invalid;
  7021. o->expr = node;
  7022. return;
  7023. }
  7024. o->type = t->Matrix.elem;
  7025. if (is_ptr) {
  7026. o->mode = Addressing_Variable;
  7027. } else if (o->mode != Addressing_Variable) {
  7028. o->mode = Addressing_Value;
  7029. }
  7030. if (ie->row_index == nullptr) {
  7031. gbString str = expr_to_string(o->expr);
  7032. error(o->expr, "Missing row index for '%s'", str);
  7033. gb_string_free(str);
  7034. o->mode = Addressing_Invalid;
  7035. o->expr = node;
  7036. return;
  7037. }
  7038. if (ie->column_index == nullptr) {
  7039. gbString str = expr_to_string(o->expr);
  7040. error(o->expr, "Missing column index for '%s'", str);
  7041. gb_string_free(str);
  7042. o->mode = Addressing_Invalid;
  7043. o->expr = node;
  7044. return;
  7045. }
  7046. i64 row_count = t->Matrix.row_count;
  7047. i64 column_count = t->Matrix.column_count;
  7048. i64 row_index = 0;
  7049. i64 column_index = 0;
  7050. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7051. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7052. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7053. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7054. }
  7055. gb_unused(row_ok);
  7056. gb_unused(column_ok);
  7057. }
  7058. struct TypeAndToken {
  7059. Type *type;
  7060. Token token;
  7061. };
  7062. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7063. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7064. if (operand.mode != Addressing_Constant) {
  7065. return;
  7066. }
  7067. if (operand.value.kind == ExactValue_Invalid) {
  7068. return;
  7069. }
  7070. uintptr key = hash_exact_value(operand.value);
  7071. TypeAndToken *found = map_get(seen, key);
  7072. if (found != nullptr) {
  7073. TEMPORARY_ALLOCATOR_GUARD();
  7074. isize count = multi_map_count(seen, key);
  7075. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7076. multi_map_get_all(seen, key, taps);
  7077. for (isize i = 0; i < count; i++) {
  7078. TypeAndToken tap = taps[i];
  7079. Operand to = {};
  7080. to.mode = Addressing_Value;
  7081. to.type = tap.type;
  7082. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7083. continue;
  7084. }
  7085. TokenPos pos = tap.token.pos;
  7086. if (use_expr) {
  7087. gbString expr_str = expr_to_string(operand.expr);
  7088. error(operand.expr,
  7089. "Duplicate case '%s'\n"
  7090. "\tprevious case at %s",
  7091. expr_str,
  7092. token_pos_to_string(pos));
  7093. gb_string_free(expr_str);
  7094. } else {
  7095. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7096. }
  7097. return;
  7098. }
  7099. }
  7100. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7101. multi_map_insert(seen, key, tap);
  7102. }
  7103. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7104. if (is_type_enum(x.type)) {
  7105. // TODO(bill): Fix this logic so it's fast!!!
  7106. i64 v0 = exact_value_to_i64(lhs.value);
  7107. i64 v1 = exact_value_to_i64(rhs.value);
  7108. Operand v = {};
  7109. v.mode = Addressing_Constant;
  7110. v.type = x.type;
  7111. v.expr = x.expr;
  7112. Type *bt = base_type(x.type);
  7113. GB_ASSERT(bt->kind == Type_Enum);
  7114. for (i64 vi = v0; vi <= v1; vi++) {
  7115. if (upper_op != Token_LtEq && vi == v1) {
  7116. break;
  7117. }
  7118. v.value = exact_value_i64(vi);
  7119. add_constant_switch_case(ctx, seen, v);
  7120. }
  7121. } else {
  7122. add_constant_switch_case(ctx, seen, lhs);
  7123. if (upper_op == Token_LtEq) {
  7124. add_constant_switch_case(ctx, seen, rhs);
  7125. }
  7126. }
  7127. }
  7128. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7129. add_constant_switch_case(ctx, seen, x);
  7130. }
  7131. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7132. ast_node(bd, BasicDirective, node);
  7133. ExprKind kind = Expr_Expr;
  7134. o->mode = Addressing_Constant;
  7135. String name = bd->name.string;
  7136. if (name == "file") {
  7137. String file = get_file_path_string(bd->token.pos.file_id);
  7138. if (build_context.obfuscate_source_code_locations) {
  7139. file = obfuscate_string(file, "F");
  7140. }
  7141. o->type = t_untyped_string;
  7142. o->value = exact_value_string(file);
  7143. } else if (name == "line") {
  7144. i32 line = bd->token.pos.line;
  7145. if (build_context.obfuscate_source_code_locations) {
  7146. line = obfuscate_i32(line);
  7147. }
  7148. o->type = t_untyped_integer;
  7149. o->value = exact_value_i64(line);
  7150. } else if (name == "procedure") {
  7151. if (c->curr_proc_decl == nullptr) {
  7152. error(node, "#procedure may only be used within procedures");
  7153. o->type = t_untyped_string;
  7154. o->value = exact_value_string(str_lit(""));
  7155. } else {
  7156. String p = c->proc_name;
  7157. if (build_context.obfuscate_source_code_locations) {
  7158. p = obfuscate_string(p, "P");
  7159. }
  7160. o->type = t_untyped_string;
  7161. o->value = exact_value_string(p);
  7162. }
  7163. } else if (name == "caller_location") {
  7164. init_core_source_code_location(c->checker);
  7165. error(node, "#caller_location may only be used as a default argument parameter");
  7166. o->type = t_source_code_location;
  7167. o->mode = Addressing_Value;
  7168. } else {
  7169. if (name == "location") {
  7170. init_core_source_code_location(c->checker);
  7171. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7172. o->type = t_source_code_location;
  7173. o->mode = Addressing_Value;
  7174. } else if (
  7175. name == "assert" ||
  7176. name == "defined" ||
  7177. name == "config" ||
  7178. name == "load" ||
  7179. name == "load_hash" ||
  7180. name == "load_directory" ||
  7181. name == "load_or"
  7182. ) {
  7183. error(node, "'#%.*s' must be used as a call", LIT(name));
  7184. o->type = t_invalid;
  7185. o->mode = Addressing_Invalid;
  7186. } else {
  7187. error(node, "Unknown directive: #%.*s", LIT(name));
  7188. o->type = t_invalid;
  7189. o->mode = Addressing_Invalid;
  7190. }
  7191. }
  7192. return kind;
  7193. }
  7194. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7195. ExprKind kind = Expr_Expr;
  7196. Operand cond = {Addressing_Invalid};
  7197. ast_node(te, TernaryIfExpr, node);
  7198. check_expr(c, &cond, te->cond);
  7199. node->viral_state_flags |= te->cond->viral_state_flags;
  7200. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7201. error(te->cond, "Non-boolean condition in ternary if expression");
  7202. }
  7203. Operand x = {Addressing_Invalid};
  7204. Operand y = {Addressing_Invalid};
  7205. check_expr_or_type(c, &x, te->x, type_hint);
  7206. node->viral_state_flags |= te->x->viral_state_flags;
  7207. if (te->y != nullptr) {
  7208. Type *th = type_hint;
  7209. if (type_hint == nullptr && is_type_typed(x.type)) {
  7210. th = x.type;
  7211. }
  7212. check_expr_or_type(c, &y, te->y, th);
  7213. node->viral_state_flags |= te->y->viral_state_flags;
  7214. } else {
  7215. error(node, "A ternary expression must have an else clause");
  7216. return kind;
  7217. }
  7218. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7219. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7220. gbString type_string = expr_to_string(type_expr);
  7221. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7222. gb_string_free(type_string);
  7223. return kind;
  7224. }
  7225. if (x.type == nullptr || x.type == t_invalid ||
  7226. y.type == nullptr || y.type == t_invalid) {
  7227. return kind;
  7228. }
  7229. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7230. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7231. if (x.mode == Addressing_Invalid) {
  7232. return kind;
  7233. }
  7234. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7235. if (y.mode == Addressing_Invalid) {
  7236. x.mode = Addressing_Invalid;
  7237. return kind;
  7238. }
  7239. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7240. // x: union{f32} = f32(123) if cond else nil
  7241. if (type_hint && !is_type_any(type_hint)) {
  7242. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7243. check_cast(c, &x, type_hint);
  7244. check_cast(c, &y, type_hint);
  7245. }
  7246. }
  7247. if (!ternary_compare_types(x.type, y.type)) {
  7248. gbString its = type_to_string(x.type);
  7249. gbString ets = type_to_string(y.type);
  7250. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7251. gb_string_free(ets);
  7252. gb_string_free(its);
  7253. return kind;
  7254. }
  7255. o->type = x.type;
  7256. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7257. o->type = y.type;
  7258. }
  7259. o->mode = Addressing_Value;
  7260. o->expr = node;
  7261. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7262. if (check_cast_internal(c, &x, type_hint) &&
  7263. check_cast_internal(c, &y, type_hint)) {
  7264. convert_to_typed(c, o, type_hint);
  7265. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7266. o->type = type_hint;
  7267. }
  7268. }
  7269. return kind;
  7270. }
  7271. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7272. ExprKind kind = Expr_Expr;
  7273. Operand cond = {};
  7274. ast_node(te, TernaryWhenExpr, node);
  7275. check_expr(c, &cond, te->cond);
  7276. node->viral_state_flags |= te->cond->viral_state_flags;
  7277. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7278. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7279. return kind;
  7280. }
  7281. if (cond.value.value_bool) {
  7282. check_expr_or_type(c, o, te->x, type_hint);
  7283. node->viral_state_flags |= te->x->viral_state_flags;
  7284. } else {
  7285. if (te->y != nullptr) {
  7286. check_expr_or_type(c, o, te->y, type_hint);
  7287. node->viral_state_flags |= te->y->viral_state_flags;
  7288. } else {
  7289. error(node, "A ternary when expression must have an else clause");
  7290. return kind;
  7291. }
  7292. }
  7293. return kind;
  7294. }
  7295. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7296. ast_node(oe, OrElseExpr, node);
  7297. String name = oe->token.string;
  7298. Ast *arg = oe->x;
  7299. Ast *default_value = oe->y;
  7300. Operand x = {};
  7301. Operand y = {};
  7302. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7303. if (is_load_directive_call(arg)) {
  7304. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7305. // Allow for chaining of '#load(path) or_else #load(path)'
  7306. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7307. bool y_is_diverging = false;
  7308. check_expr_base(c, &y, default_value, x.type);
  7309. switch (y.mode) {
  7310. case Addressing_NoValue:
  7311. if (is_diverging_expr(y.expr)) {
  7312. // Allow
  7313. y.mode = Addressing_Value;
  7314. y_is_diverging = true;
  7315. } else {
  7316. error_operand_no_value(&y);
  7317. y.mode = Addressing_Invalid;
  7318. }
  7319. break;
  7320. case Addressing_Type:
  7321. error_operand_not_expression(&y);
  7322. y.mode = Addressing_Invalid;
  7323. break;
  7324. }
  7325. if (y.mode == Addressing_Invalid) {
  7326. o->mode = Addressing_Value;
  7327. o->type = t_invalid;
  7328. o->expr = node;
  7329. return Expr_Expr;
  7330. }
  7331. if (!y_is_diverging) {
  7332. check_assignment(c, &y, x.type, name);
  7333. if (y.mode != Addressing_Constant) {
  7334. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7335. }
  7336. }
  7337. }
  7338. if (res == LoadDirective_Success) {
  7339. *o = x;
  7340. } else {
  7341. *o = y;
  7342. }
  7343. o->expr = node;
  7344. return Expr_Expr;
  7345. }
  7346. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7347. if (x.mode == Addressing_Invalid) {
  7348. o->mode = Addressing_Value;
  7349. o->type = t_invalid;
  7350. o->expr = node;
  7351. return Expr_Expr;
  7352. }
  7353. bool y_is_diverging = false;
  7354. check_expr_base(c, &y, default_value, x.type);
  7355. switch (y.mode) {
  7356. case Addressing_NoValue:
  7357. if (is_diverging_expr(y.expr)) {
  7358. // Allow
  7359. y.mode = Addressing_Value;
  7360. y_is_diverging = true;
  7361. } else {
  7362. error_operand_no_value(&y);
  7363. y.mode = Addressing_Invalid;
  7364. }
  7365. break;
  7366. case Addressing_Type:
  7367. error_operand_not_expression(&y);
  7368. y.mode = Addressing_Invalid;
  7369. break;
  7370. }
  7371. if (y.mode == Addressing_Invalid) {
  7372. o->mode = Addressing_Value;
  7373. o->type = t_invalid;
  7374. o->expr = node;
  7375. return Expr_Expr;
  7376. }
  7377. Type *left_type = nullptr;
  7378. Type *right_type = nullptr;
  7379. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7380. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7381. if (left_type != nullptr) {
  7382. if (!y_is_diverging) {
  7383. check_assignment(c, &y, left_type, name);
  7384. }
  7385. } else {
  7386. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7387. }
  7388. if (left_type == nullptr) {
  7389. left_type = t_invalid;
  7390. }
  7391. o->mode = Addressing_Value;
  7392. o->type = left_type;
  7393. o->expr = node;
  7394. return Expr_Expr;
  7395. }
  7396. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7397. ast_node(re, OrReturnExpr, node);
  7398. String name = re->token.string;
  7399. Operand x = {};
  7400. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7401. if (x.mode == Addressing_Invalid) {
  7402. o->mode = Addressing_Value;
  7403. o->type = t_invalid;
  7404. o->expr = node;
  7405. return Expr_Expr;
  7406. }
  7407. Type *left_type = nullptr;
  7408. Type *right_type = nullptr;
  7409. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7410. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7411. if (right_type == nullptr) {
  7412. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7413. } else {
  7414. Type *proc_type = base_type(c->curr_proc_sig);
  7415. GB_ASSERT(proc_type->kind == Type_Proc);
  7416. Type *result_type = proc_type->Proc.results;
  7417. if (result_type == nullptr) {
  7418. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7419. } else {
  7420. GB_ASSERT(result_type->kind == Type_Tuple);
  7421. auto const &vars = result_type->Tuple.variables;
  7422. Type *end_type = vars[vars.count-1]->type;
  7423. if (vars.count > 1) {
  7424. if (!proc_type->Proc.has_named_results) {
  7425. 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));
  7426. }
  7427. }
  7428. Operand rhs = {};
  7429. rhs.type = right_type;
  7430. rhs.mode = Addressing_Value;
  7431. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7432. // NOTE(bill): allow implicit conversion between boolean types
  7433. // within 'or_return' to improve the experience using third-party code
  7434. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7435. ERROR_BLOCK();
  7436. // TODO(bill): better error message
  7437. gbString a = type_to_string(right_type);
  7438. gbString b = type_to_string(end_type);
  7439. gbString ret_type = type_to_string(result_type);
  7440. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7441. if (vars.count == 1) {
  7442. error_line("\tProcedure return value type: %s\n", ret_type);
  7443. } else {
  7444. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7445. }
  7446. gb_string_free(ret_type);
  7447. gb_string_free(b);
  7448. gb_string_free(a);
  7449. }
  7450. }
  7451. }
  7452. o->expr = node;
  7453. o->type = left_type;
  7454. if (left_type != nullptr) {
  7455. o->mode = Addressing_Value;
  7456. } else {
  7457. o->mode = Addressing_NoValue;
  7458. }
  7459. if (c->curr_proc_sig == nullptr) {
  7460. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7461. }
  7462. if (c->in_defer) {
  7463. error(node, "'or_return' cannot be used within a defer statement");
  7464. }
  7465. return Expr_Expr;
  7466. }
  7467. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7468. ast_node(be, OrBranchExpr, node);
  7469. String name = be->token.string;
  7470. Operand x = {};
  7471. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7472. if (x.mode == Addressing_Invalid) {
  7473. o->mode = Addressing_Value;
  7474. o->type = t_invalid;
  7475. o->expr = node;
  7476. return Expr_Expr;
  7477. }
  7478. Type *left_type = nullptr;
  7479. Type *right_type = nullptr;
  7480. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7481. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7482. if (right_type == nullptr) {
  7483. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7484. } else {
  7485. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7486. // okay
  7487. } else {
  7488. gbString s = type_to_string(right_type);
  7489. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7490. gb_string_free(s);
  7491. }
  7492. }
  7493. o->expr = node;
  7494. o->type = left_type;
  7495. if (left_type != nullptr) {
  7496. o->mode = Addressing_Value;
  7497. } else {
  7498. o->mode = Addressing_NoValue;
  7499. }
  7500. if (c->curr_proc_sig == nullptr) {
  7501. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7502. }
  7503. Ast *label = be->label;
  7504. switch (be->token.kind) {
  7505. case Token_or_break:
  7506. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  7507. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7508. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7509. }
  7510. break;
  7511. case Token_or_continue:
  7512. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7513. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7514. }
  7515. break;
  7516. }
  7517. if (label != nullptr) {
  7518. if (label->kind != Ast_Ident) {
  7519. error(label, "A branch statement's label name must be an identifier");
  7520. return Expr_Expr;
  7521. }
  7522. Ast *ident = label;
  7523. String name = ident->Ident.token.string;
  7524. Operand o = {};
  7525. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7526. if (e == nullptr) {
  7527. error(ident, "Undeclared label name: %.*s", LIT(name));
  7528. return Expr_Expr;
  7529. }
  7530. add_entity_use(c, ident, e);
  7531. if (e->kind != Entity_Label) {
  7532. error(ident, "'%.*s' is not a label", LIT(name));
  7533. return Expr_Expr;
  7534. }
  7535. Ast *parent = e->Label.parent;
  7536. GB_ASSERT(parent != nullptr);
  7537. switch (parent->kind) {
  7538. case Ast_BlockStmt:
  7539. case Ast_IfStmt:
  7540. case Ast_SwitchStmt:
  7541. if (be->token.kind != Token_or_break) {
  7542. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7543. }
  7544. break;
  7545. case Ast_RangeStmt:
  7546. case Ast_ForStmt:
  7547. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7548. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7549. }
  7550. break;
  7551. }
  7552. }
  7553. return Expr_Expr;
  7554. }
  7555. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7556. Type *bt = base_type(type);
  7557. StringSet fields_visited = {};
  7558. defer (string_set_destroy(&fields_visited));
  7559. StringMap<String> fields_visited_through_raw_union = {};
  7560. defer (string_map_destroy(&fields_visited_through_raw_union));
  7561. String assignment_str = str_lit("structure literal");
  7562. if (bt->kind == Type_BitField) {
  7563. assignment_str = str_lit("bit_field literal");
  7564. }
  7565. for (Ast *elem : elems) {
  7566. if (elem->kind != Ast_FieldValue) {
  7567. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7568. continue;
  7569. }
  7570. ast_node(fv, FieldValue, elem);
  7571. Ast *ident = fv->field;
  7572. if (ident->kind == Ast_ImplicitSelectorExpr) {
  7573. gbString expr_str = expr_to_string(ident);
  7574. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  7575. gb_string_free(expr_str);
  7576. ident = ident->ImplicitSelectorExpr.selector;
  7577. }
  7578. if (ident->kind != Ast_Ident) {
  7579. gbString expr_str = expr_to_string(ident);
  7580. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7581. gb_string_free(expr_str);
  7582. continue;
  7583. }
  7584. String name = ident->Ident.token.string;
  7585. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7586. bool is_unknown = sel.entity == nullptr;
  7587. if (is_unknown) {
  7588. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  7589. continue;
  7590. }
  7591. Entity *field = nullptr;
  7592. if (bt->kind == Type_Struct) {
  7593. field = bt->Struct.fields[sel.index[0]];
  7594. } else if (bt->kind == Type_BitField) {
  7595. field = bt->BitField.fields[sel.index[0]];
  7596. } else {
  7597. GB_PANIC("Unknown type");
  7598. }
  7599. add_entity_use(c, ident, field);
  7600. if (string_set_update(&fields_visited, name)) {
  7601. if (sel.index.count > 1) {
  7602. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7603. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7604. } else {
  7605. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  7606. }
  7607. } else {
  7608. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  7609. }
  7610. continue;
  7611. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7612. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7613. continue;
  7614. }
  7615. if (sel.indirect) {
  7616. 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));
  7617. continue;
  7618. }
  7619. if (sel.index.count > 1) {
  7620. GB_ASSERT(bt->kind == Type_Struct);
  7621. if (is_constant) {
  7622. Type *ft = type;
  7623. for (i32 index : sel.index) {
  7624. Type *bt = base_type(ft);
  7625. switch (bt->kind) {
  7626. case Type_Struct:
  7627. if (bt->Struct.is_raw_union) {
  7628. is_constant = false;
  7629. break;
  7630. }
  7631. ft = bt->Struct.fields[index]->type;
  7632. break;
  7633. case Type_Array:
  7634. ft = bt->Array.elem;
  7635. break;
  7636. default:
  7637. GB_PANIC("invalid type: %s", type_to_string(ft));
  7638. break;
  7639. }
  7640. }
  7641. if (is_constant &&
  7642. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7643. is_constant = false;
  7644. }
  7645. }
  7646. Type *nested_ft = bt;
  7647. for (i32 index : sel.index) {
  7648. Type *bt = base_type(nested_ft);
  7649. switch (bt->kind) {
  7650. case Type_Struct:
  7651. if (bt->Struct.is_raw_union) {
  7652. for (Entity *re : bt->Struct.fields) {
  7653. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7654. }
  7655. }
  7656. nested_ft = bt->Struct.fields[index]->type;
  7657. break;
  7658. case Type_Array:
  7659. nested_ft = bt->Array.elem;
  7660. break;
  7661. default:
  7662. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7663. break;
  7664. }
  7665. }
  7666. field = sel.entity;
  7667. }
  7668. Operand o = {};
  7669. check_expr_or_type(c, &o, fv->value, field->type);
  7670. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7671. is_constant = false;
  7672. }
  7673. if (is_constant) {
  7674. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7675. }
  7676. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  7677. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  7678. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  7679. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  7680. }
  7681. check_assignment(c, &o, field->type, assignment_str);
  7682. c->bit_field_bit_size = prev_bit_field_bit_size;
  7683. }
  7684. }
  7685. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  7686. type_expr = unparen_expr(type_expr);
  7687. if (type_expr == nullptr) {
  7688. return false;
  7689. }
  7690. // [?]Type
  7691. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7692. Ast *count = type_expr->ArrayType.count;
  7693. if (count->kind == Ast_UnaryExpr &&
  7694. count->UnaryExpr.op.kind == Token_Question) {
  7695. return true;
  7696. }
  7697. }
  7698. return false;
  7699. }
  7700. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7701. ExprKind kind = Expr_Expr;
  7702. ast_node(cl, CompoundLit, node);
  7703. Type *type = type_hint;
  7704. if (type != nullptr && is_type_untyped(type)) {
  7705. type = nullptr;
  7706. }
  7707. bool is_to_be_determined_array_count = false;
  7708. bool is_constant = true;
  7709. Ast *type_expr = cl->type;
  7710. bool used_type_hint_expr = false;
  7711. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  7712. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  7713. type_expr = clone_ast(c->type_hint_expr);
  7714. used_type_hint_expr = true;
  7715. }
  7716. }
  7717. if (type_expr != nullptr) {
  7718. type = nullptr;
  7719. // [?]Type
  7720. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7721. Ast *count = type_expr->ArrayType.count;
  7722. if (count->kind == Ast_UnaryExpr &&
  7723. count->UnaryExpr.op.kind == Token_Question) {
  7724. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  7725. is_to_be_determined_array_count = true;
  7726. }
  7727. if (cl->elems.count > 0) {
  7728. if (type_expr->ArrayType.tag != nullptr) {
  7729. Ast *tag = type_expr->ArrayType.tag;
  7730. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7731. String name = tag->BasicDirective.name.string;
  7732. if (name == "soa") {
  7733. error(node, "#soa arrays are not supported for compound literals");
  7734. return kind;
  7735. }
  7736. }
  7737. }
  7738. }
  7739. if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  7740. if (cl->elems.count > 0) {
  7741. Ast *tag = type_expr->DynamicArrayType.tag;
  7742. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7743. String name = tag->BasicDirective.name.string;
  7744. if (name == "soa") {
  7745. error(node, "#soa arrays are not supported for compound literals");
  7746. return kind;
  7747. }
  7748. }
  7749. }
  7750. if (type == nullptr) {
  7751. type = check_type(c, type_expr);
  7752. }
  7753. }
  7754. if (type == nullptr) {
  7755. error(node, "Missing type in compound literal");
  7756. return kind;
  7757. }
  7758. Type *t = base_type(type);
  7759. if (is_type_polymorphic(t)) {
  7760. gbString str = type_to_string(type);
  7761. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7762. o->expr = node;
  7763. o->type = type;
  7764. gb_string_free(str);
  7765. return kind;
  7766. }
  7767. switch (t->kind) {
  7768. case Type_Struct: {
  7769. if (cl->elems.count == 0) {
  7770. break; // NOTE(bill): No need to init
  7771. }
  7772. if (t->Struct.is_raw_union) {
  7773. if (cl->elems.count > 0) {
  7774. // NOTE: unions cannot be constant
  7775. is_constant = false;
  7776. if (cl->elems[0]->kind != Ast_FieldValue) {
  7777. gbString type_str = type_to_string(type);
  7778. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7779. gb_string_free(type_str);
  7780. } else {
  7781. if (cl->elems.count != 1) {
  7782. gbString type_str = type_to_string(type);
  7783. 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);
  7784. gb_string_free(type_str);
  7785. } else {
  7786. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7787. }
  7788. }
  7789. }
  7790. break;
  7791. }
  7792. wait_signal_until_available(&t->Struct.fields_wait_signal);
  7793. isize field_count = t->Struct.fields.count;
  7794. isize min_field_count = t->Struct.fields.count;
  7795. for (isize i = min_field_count-1; i >= 0; i--) {
  7796. Entity *e = t->Struct.fields[i];
  7797. GB_ASSERT(e->kind == Entity_Variable);
  7798. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7799. min_field_count--;
  7800. } else {
  7801. break;
  7802. }
  7803. }
  7804. if (cl->elems[0]->kind == Ast_FieldValue) {
  7805. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7806. } else {
  7807. bool seen_field_value = false;
  7808. for_array(index, cl->elems) {
  7809. Entity *field = nullptr;
  7810. Ast *elem = cl->elems[index];
  7811. if (elem->kind == Ast_FieldValue) {
  7812. seen_field_value = true;
  7813. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7814. continue;
  7815. } else if (seen_field_value) {
  7816. error(elem, "Value elements cannot be used after a 'field = value'");
  7817. continue;
  7818. }
  7819. if (index >= field_count) {
  7820. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7821. break;
  7822. }
  7823. if (field == nullptr) {
  7824. field = t->Struct.fields[index];
  7825. }
  7826. Operand o = {};
  7827. check_expr_or_type(c, &o, elem, field->type);
  7828. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7829. is_constant = false;
  7830. }
  7831. if (is_constant) {
  7832. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7833. }
  7834. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7835. }
  7836. if (cl->elems.count < field_count) {
  7837. if (min_field_count < field_count) {
  7838. if (cl->elems.count < min_field_count) {
  7839. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7840. }
  7841. } else {
  7842. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7843. }
  7844. }
  7845. }
  7846. break;
  7847. }
  7848. case Type_Slice:
  7849. case Type_Array:
  7850. case Type_DynamicArray:
  7851. case Type_SimdVector:
  7852. case Type_Matrix:
  7853. {
  7854. Type *elem_type = nullptr;
  7855. String context_name = {};
  7856. i64 max_type_count = -1;
  7857. if (t->kind == Type_Slice) {
  7858. elem_type = t->Slice.elem;
  7859. context_name = str_lit("slice literal");
  7860. } else if (t->kind == Type_Array) {
  7861. elem_type = t->Array.elem;
  7862. context_name = str_lit("array literal");
  7863. if (!is_to_be_determined_array_count) {
  7864. max_type_count = t->Array.count;
  7865. }
  7866. } else if (t->kind == Type_DynamicArray) {
  7867. elem_type = t->DynamicArray.elem;
  7868. context_name = str_lit("dynamic array literal");
  7869. is_constant = false;
  7870. if (!build_context.no_dynamic_literals) {
  7871. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7872. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7873. }
  7874. } else if (t->kind == Type_SimdVector) {
  7875. elem_type = t->SimdVector.elem;
  7876. context_name = str_lit("simd vector literal");
  7877. max_type_count = t->SimdVector.count;
  7878. } else if (t->kind == Type_Matrix) {
  7879. elem_type = t->Matrix.elem;
  7880. context_name = str_lit("matrix literal");
  7881. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7882. } else {
  7883. GB_PANIC("unreachable");
  7884. }
  7885. i64 max = 0;
  7886. Type *bet = base_type(elem_type);
  7887. if (!elem_type_can_be_constant(bet)) {
  7888. is_constant = false;
  7889. }
  7890. if (bet == t_invalid) {
  7891. break;
  7892. }
  7893. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7894. RangeCache rc = range_cache_make(heap_allocator());
  7895. defer (range_cache_destroy(&rc));
  7896. for (Ast *elem : cl->elems) {
  7897. if (elem->kind != Ast_FieldValue) {
  7898. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7899. continue;
  7900. }
  7901. ast_node(fv, FieldValue, elem);
  7902. if (is_ast_range(fv->field)) {
  7903. Token op = fv->field->BinaryExpr.op;
  7904. Operand x = {};
  7905. Operand y = {};
  7906. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7907. if (!ok) {
  7908. continue;
  7909. }
  7910. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7911. error(x.expr, "Expected a constant integer as an array field");
  7912. continue;
  7913. }
  7914. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7915. error(y.expr, "Expected a constant integer as an array field");
  7916. continue;
  7917. }
  7918. i64 lo = exact_value_to_i64(x.value);
  7919. i64 hi = exact_value_to_i64(y.value);
  7920. i64 max_index = hi;
  7921. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7922. hi -= 1;
  7923. } else { // .. (inclusive)
  7924. max_index += 1;
  7925. }
  7926. bool new_range = range_cache_add_range(&rc, lo, hi);
  7927. if (!new_range) {
  7928. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7929. continue;
  7930. }
  7931. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7932. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7933. continue;
  7934. }
  7935. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7936. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7937. continue;
  7938. }
  7939. if (max < hi) {
  7940. max = max_index;
  7941. }
  7942. Operand operand = {};
  7943. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7944. check_assignment(c, &operand, elem_type, context_name);
  7945. is_constant = is_constant && operand.mode == Addressing_Constant;
  7946. } else {
  7947. Operand op_index = {};
  7948. check_expr(c, &op_index, fv->field);
  7949. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7950. error(elem, "Expected a constant integer as an array field");
  7951. continue;
  7952. }
  7953. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7954. i64 index = exact_value_to_i64(op_index.value);
  7955. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7956. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7957. continue;
  7958. }
  7959. bool new_index = range_cache_add_index(&rc, index);
  7960. if (!new_index) {
  7961. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7962. continue;
  7963. }
  7964. if (max < index+1) {
  7965. max = index+1;
  7966. }
  7967. Operand operand = {};
  7968. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7969. check_assignment(c, &operand, elem_type, context_name);
  7970. is_constant = is_constant && operand.mode == Addressing_Constant;
  7971. }
  7972. }
  7973. cl->max_count = max;
  7974. } else {
  7975. isize index = 0;
  7976. for (; index < cl->elems.count; index++) {
  7977. Ast *e = cl->elems[index];
  7978. if (e == nullptr) {
  7979. error(node, "Invalid literal element");
  7980. continue;
  7981. }
  7982. if (e->kind == Ast_FieldValue) {
  7983. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7984. continue;
  7985. }
  7986. if (0 <= max_type_count && max_type_count <= index) {
  7987. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7988. }
  7989. Operand operand = {};
  7990. check_expr_with_type_hint(c, &operand, e, elem_type);
  7991. check_assignment(c, &operand, elem_type, context_name);
  7992. is_constant = is_constant && operand.mode == Addressing_Constant;
  7993. }
  7994. if (max < index) {
  7995. max = index;
  7996. }
  7997. }
  7998. if (t->kind == Type_Array) {
  7999. if (is_to_be_determined_array_count) {
  8000. t->Array.count = max;
  8001. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8002. if (0 < max && max < t->Array.count) {
  8003. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8004. }
  8005. }
  8006. }
  8007. if (t->kind == Type_SimdVector) {
  8008. if (!is_constant) {
  8009. // error(node, "Expected all constant elements for a simd vector");
  8010. }
  8011. }
  8012. if (t->kind == Type_DynamicArray) {
  8013. if (build_context.no_dynamic_literals && cl->elems.count) {
  8014. error(node, "Compound literals of dynamic types have been disabled");
  8015. }
  8016. }
  8017. if (t->kind == Type_Matrix) {
  8018. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8019. if (0 < max && max < max_type_count) {
  8020. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8021. }
  8022. }
  8023. }
  8024. break;
  8025. }
  8026. case Type_EnumeratedArray:
  8027. {
  8028. Type *elem_type = t->EnumeratedArray.elem;
  8029. Type *index_type = t->EnumeratedArray.index;
  8030. String context_name = str_lit("enumerated array literal");
  8031. i64 max_type_count = t->EnumeratedArray.count;
  8032. gbString index_type_str = type_to_string(index_type);
  8033. defer (gb_string_free(index_type_str));
  8034. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8035. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8036. String total_lo_string = {};
  8037. String total_hi_string = {};
  8038. GB_ASSERT(is_type_enum(index_type));
  8039. {
  8040. Type *bt = base_type(index_type);
  8041. GB_ASSERT(bt->kind == Type_Enum);
  8042. for (Entity *f : bt->Enum.fields) {
  8043. if (f->kind != Entity_Constant) {
  8044. continue;
  8045. }
  8046. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8047. total_lo_string = f->token.string;
  8048. }
  8049. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8050. total_hi_string = f->token.string;
  8051. }
  8052. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8053. break;
  8054. }
  8055. }
  8056. }
  8057. i64 max = 0;
  8058. Type *bet = base_type(elem_type);
  8059. if (!elem_type_can_be_constant(bet)) {
  8060. is_constant = false;
  8061. }
  8062. if (bet == t_invalid) {
  8063. break;
  8064. }
  8065. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8066. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8067. defer (map_destroy(&seen));
  8068. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8069. RangeCache rc = range_cache_make(heap_allocator());
  8070. defer (range_cache_destroy(&rc));
  8071. for (Ast *elem : cl->elems) {
  8072. if (elem->kind != Ast_FieldValue) {
  8073. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8074. continue;
  8075. }
  8076. ast_node(fv, FieldValue, elem);
  8077. if (is_ast_range(fv->field)) {
  8078. Token op = fv->field->BinaryExpr.op;
  8079. Operand x = {};
  8080. Operand y = {};
  8081. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8082. if (!ok) {
  8083. continue;
  8084. }
  8085. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8086. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8087. continue;
  8088. }
  8089. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8090. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8091. continue;
  8092. }
  8093. i64 lo = exact_value_to_i64(x.value);
  8094. i64 hi = exact_value_to_i64(y.value);
  8095. i64 max_index = hi;
  8096. if (op.kind == Token_RangeHalf) {
  8097. hi -= 1;
  8098. }
  8099. bool new_range = range_cache_add_range(&rc, lo, hi);
  8100. if (!new_range) {
  8101. gbString lo_str = expr_to_string(x.expr);
  8102. gbString hi_str = expr_to_string(y.expr);
  8103. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8104. gb_string_free(hi_str);
  8105. gb_string_free(lo_str);
  8106. continue;
  8107. }
  8108. // NOTE(bill): These are sanity checks for invalid enum values
  8109. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8110. gbString lo_str = expr_to_string(x.expr);
  8111. 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));
  8112. gb_string_free(lo_str);
  8113. continue;
  8114. }
  8115. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8116. gbString hi_str = expr_to_string(y.expr);
  8117. 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));
  8118. gb_string_free(hi_str);
  8119. continue;
  8120. }
  8121. if (max < hi) {
  8122. max = max_index;
  8123. }
  8124. Operand operand = {};
  8125. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8126. check_assignment(c, &operand, elem_type, context_name);
  8127. is_constant = is_constant && operand.mode == Addressing_Constant;
  8128. TokenKind upper_op = Token_LtEq;
  8129. if (op.kind == Token_RangeHalf) {
  8130. upper_op = Token_Lt;
  8131. }
  8132. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8133. } else {
  8134. Operand op_index = {};
  8135. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8136. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8137. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8138. continue;
  8139. }
  8140. i64 index = exact_value_to_i64(op_index.value);
  8141. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8142. gbString idx_str = expr_to_string(op_index.expr);
  8143. 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));
  8144. gb_string_free(idx_str);
  8145. continue;
  8146. }
  8147. bool new_index = range_cache_add_index(&rc, index);
  8148. if (!new_index) {
  8149. gbString idx_str = expr_to_string(op_index.expr);
  8150. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8151. gb_string_free(idx_str);
  8152. continue;
  8153. }
  8154. if (max < index+1) {
  8155. max = index+1;
  8156. }
  8157. Operand operand = {};
  8158. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8159. check_assignment(c, &operand, elem_type, context_name);
  8160. is_constant = is_constant && operand.mode == Addressing_Constant;
  8161. add_to_seen_map(c, &seen, op_index);
  8162. }
  8163. }
  8164. cl->max_count = max;
  8165. } else {
  8166. isize index = 0;
  8167. for (; index < cl->elems.count; index++) {
  8168. Ast *e = cl->elems[index];
  8169. if (e == nullptr) {
  8170. error(node, "Invalid literal element");
  8171. continue;
  8172. }
  8173. if (e->kind == Ast_FieldValue) {
  8174. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8175. continue;
  8176. }
  8177. if (0 <= max_type_count && max_type_count <= index) {
  8178. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8179. }
  8180. Operand operand = {};
  8181. check_expr_with_type_hint(c, &operand, e, elem_type);
  8182. check_assignment(c, &operand, elem_type, context_name);
  8183. is_constant = is_constant && operand.mode == Addressing_Constant;
  8184. }
  8185. if (max < index) {
  8186. max = index;
  8187. }
  8188. }
  8189. bool was_error = false;
  8190. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8191. if (0 < max && max < t->EnumeratedArray.count) {
  8192. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8193. was_error = true;
  8194. } else {
  8195. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8196. was_error = true;
  8197. }
  8198. }
  8199. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8200. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8201. TEMPORARY_ALLOCATOR_GUARD();
  8202. Type *et = base_type(index_type);
  8203. GB_ASSERT(et->kind == Type_Enum);
  8204. auto fields = et->Enum.fields;
  8205. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8206. for (Entity *f : fields) {
  8207. if (f->kind != Entity_Constant) {
  8208. continue;
  8209. }
  8210. ExactValue v = f->Constant.value;
  8211. auto found = map_get(&seen, hash_exact_value(v));
  8212. if (!found) {
  8213. array_add(&unhandled, f);
  8214. }
  8215. }
  8216. if (unhandled.count > 0) {
  8217. ERROR_BLOCK();
  8218. if (unhandled.count == 1) {
  8219. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8220. } else {
  8221. error(node, "Unhandled enumerated array cases:");
  8222. for_array(i, unhandled) {
  8223. Entity *f = unhandled[i];
  8224. error_line("\t%.*s\n", LIT(f->token.string));
  8225. }
  8226. }
  8227. if (!build_context.terse_errors) {
  8228. error_line("\n");
  8229. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8230. }
  8231. }
  8232. }
  8233. break;
  8234. }
  8235. case Type_Basic: {
  8236. if (!is_type_any(t)) {
  8237. if (cl->elems.count != 0) {
  8238. gbString s = type_to_string(t);
  8239. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8240. gb_string_free(s);
  8241. is_constant = false;
  8242. }
  8243. break;
  8244. }
  8245. if (cl->elems.count == 0) {
  8246. break; // NOTE(bill): No need to init
  8247. }
  8248. { // Checker values
  8249. Type *field_types[2] = {t_rawptr, t_typeid};
  8250. isize field_count = 2;
  8251. if (cl->elems[0]->kind == Ast_FieldValue) {
  8252. bool fields_visited[2] = {};
  8253. for_array(i, cl->elems) {
  8254. Ast *elem = cl->elems[i];
  8255. if (elem->kind != Ast_FieldValue) {
  8256. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8257. continue;
  8258. }
  8259. ast_node(fv, FieldValue, elem);
  8260. if (fv->field->kind != Ast_Ident) {
  8261. gbString expr_str = expr_to_string(fv->field);
  8262. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8263. gb_string_free(expr_str);
  8264. continue;
  8265. }
  8266. String name = fv->field->Ident.token.string;
  8267. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8268. if (sel.entity == nullptr) {
  8269. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8270. continue;
  8271. }
  8272. isize index = sel.index[0];
  8273. if (fields_visited[index]) {
  8274. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8275. continue;
  8276. }
  8277. fields_visited[index] = true;
  8278. check_expr(c, o, fv->value);
  8279. // NOTE(bill): 'any' literals can never be constant
  8280. is_constant = false;
  8281. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8282. }
  8283. } else {
  8284. for_array(index, cl->elems) {
  8285. Ast *elem = cl->elems[index];
  8286. if (elem->kind == Ast_FieldValue) {
  8287. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8288. continue;
  8289. }
  8290. check_expr(c, o, elem);
  8291. if (index >= field_count) {
  8292. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8293. break;
  8294. }
  8295. // NOTE(bill): 'any' literals can never be constant
  8296. is_constant = false;
  8297. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8298. }
  8299. if (cl->elems.count < field_count) {
  8300. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8301. }
  8302. }
  8303. }
  8304. break;
  8305. }
  8306. case Type_Map: {
  8307. if (cl->elems.count == 0) {
  8308. break;
  8309. }
  8310. is_constant = false;
  8311. { // Checker values
  8312. bool key_is_typeid = is_type_typeid(t->Map.key);
  8313. bool value_is_typeid = is_type_typeid(t->Map.value);
  8314. for (Ast *elem : cl->elems) {
  8315. if (elem->kind != Ast_FieldValue) {
  8316. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8317. continue;
  8318. }
  8319. ast_node(fv, FieldValue, elem);
  8320. if (key_is_typeid) {
  8321. check_expr_or_type(c, o, fv->field, t->Map.key);
  8322. } else {
  8323. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8324. }
  8325. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8326. if (o->mode == Addressing_Invalid) {
  8327. continue;
  8328. }
  8329. if (value_is_typeid) {
  8330. check_expr_or_type(c, o, fv->value, t->Map.value);
  8331. } else {
  8332. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8333. }
  8334. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8335. }
  8336. }
  8337. if (build_context.no_dynamic_literals && cl->elems.count) {
  8338. error(node, "Compound literals of dynamic types have been disabled");
  8339. } else {
  8340. add_map_reserve_dependencies(c);
  8341. add_map_set_dependencies(c);
  8342. }
  8343. break;
  8344. }
  8345. case Type_BitSet: {
  8346. if (cl->elems.count == 0) {
  8347. break; // NOTE(bill): No need to init
  8348. }
  8349. Type *et = base_type(t->BitSet.elem);
  8350. isize field_count = 0;
  8351. if (et->kind == Type_Enum) {
  8352. field_count = et->Enum.fields.count;
  8353. }
  8354. if (cl->elems[0]->kind == Ast_FieldValue) {
  8355. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8356. is_constant = false;
  8357. } else {
  8358. for (Ast *elem : cl->elems) {
  8359. if (elem->kind == Ast_FieldValue) {
  8360. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8361. continue;
  8362. }
  8363. check_expr_with_type_hint(c, o, elem, et);
  8364. if (is_constant) {
  8365. is_constant = o->mode == Addressing_Constant;
  8366. }
  8367. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8368. if (o->mode == Addressing_Constant) {
  8369. i64 lower = t->BitSet.lower;
  8370. i64 upper = t->BitSet.upper;
  8371. i64 v = exact_value_to_i64(o->value);
  8372. if (lower <= v && v <= upper) {
  8373. // okay
  8374. } else {
  8375. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8376. continue;
  8377. }
  8378. }
  8379. }
  8380. }
  8381. break;
  8382. }
  8383. case Type_BitField: {
  8384. if (cl->elems.count == 0) {
  8385. break; // NOTE(bill): No need to init
  8386. }
  8387. is_constant = false;
  8388. if (cl->elems[0]->kind != Ast_FieldValue) {
  8389. gbString type_str = type_to_string(type);
  8390. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8391. gb_string_free(type_str);
  8392. } else {
  8393. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8394. }
  8395. break;
  8396. }
  8397. default: {
  8398. if (cl->elems.count == 0) {
  8399. break; // NOTE(bill): No need to init
  8400. }
  8401. gbString str = type_to_string(type);
  8402. error(node, "Invalid compound literal type '%s'", str);
  8403. gb_string_free(str);
  8404. return kind;
  8405. }
  8406. }
  8407. if (is_constant) {
  8408. o->mode = Addressing_Constant;
  8409. if (is_type_bit_set(type)) {
  8410. // NOTE(bill): Encode as an integer
  8411. Type *bt = base_type(type);
  8412. BigInt bits = {};
  8413. BigInt one = {};
  8414. big_int_from_u64(&one, 1);
  8415. for (Ast *e : cl->elems) {
  8416. GB_ASSERT(e->kind != Ast_FieldValue);
  8417. TypeAndValue tav = e->tav;
  8418. if (tav.mode != Addressing_Constant) {
  8419. continue;
  8420. }
  8421. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8422. i64 v = big_int_to_i64(&tav.value.value_integer);
  8423. i64 lower = bt->BitSet.lower;
  8424. u64 index = cast(u64)(v-lower);
  8425. BigInt bit = {};
  8426. big_int_from_u64(&bit, index);
  8427. big_int_shl(&bit, &one, &bit);
  8428. big_int_or(&bits, &bits, &bit);
  8429. }
  8430. o->value.kind = ExactValue_Integer;
  8431. o->value.value_integer = bits;
  8432. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8433. ExactValue value = exact_value_compound(node);
  8434. Type *bt = core_type(type);
  8435. if (bt->kind == Type_Basic) {
  8436. if (bt->Basic.flags & BasicFlag_Boolean) {
  8437. value = exact_value_bool(false);
  8438. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8439. value = exact_value_i64(0);
  8440. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8441. value = exact_value_i64(0);
  8442. } else if (bt->Basic.flags & BasicFlag_Float) {
  8443. value = exact_value_float(0);
  8444. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8445. value = exact_value_complex(0, 0);
  8446. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8447. value = exact_value_quaternion(0, 0, 0, 0);
  8448. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8449. value = exact_value_pointer(0);
  8450. } else if (bt->Basic.flags & BasicFlag_String) {
  8451. String empty_string = {};
  8452. value = exact_value_string(empty_string);
  8453. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8454. value = exact_value_i64(0);
  8455. }
  8456. }
  8457. o->value = value;
  8458. } else {
  8459. o->value = exact_value_compound(node);
  8460. }
  8461. } else {
  8462. o->mode = Addressing_Value;
  8463. }
  8464. o->type = type;
  8465. return kind;
  8466. }
  8467. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8468. ExprKind kind = Expr_Expr;
  8469. ast_node(ta, TypeAssertion, node);
  8470. check_expr(c, o, ta->expr);
  8471. node->viral_state_flags |= ta->expr->viral_state_flags;
  8472. if (o->mode == Addressing_Invalid) {
  8473. o->expr = node;
  8474. return kind;
  8475. }
  8476. if (o->mode == Addressing_Constant) {
  8477. gbString expr_str = expr_to_string(o->expr);
  8478. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8479. gb_string_free(expr_str);
  8480. o->mode = Addressing_Invalid;
  8481. o->expr = node;
  8482. return kind;
  8483. }
  8484. if (is_type_untyped(o->type)) {
  8485. gbString expr_str = expr_to_string(o->expr);
  8486. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8487. gb_string_free(expr_str);
  8488. o->mode = Addressing_Invalid;
  8489. o->expr = node;
  8490. return kind;
  8491. }
  8492. Type *src = type_deref(o->type);
  8493. Type *bsrc = base_type(src);
  8494. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8495. if (!is_type_union(src)) {
  8496. gbString str = type_to_string(o->type);
  8497. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8498. gb_string_free(str);
  8499. o->mode = Addressing_Invalid;
  8500. o->expr = node;
  8501. return kind;
  8502. }
  8503. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8504. bool allowed = false;
  8505. for (Type *vt : bsrc->Union.variants) {
  8506. if (are_types_identical(vt, type_hint)) {
  8507. allowed = true;
  8508. add_type_info_type(c, vt);
  8509. break;
  8510. }
  8511. }
  8512. if (allowed) {
  8513. add_type_info_type(c, o->type);
  8514. o->type = type_hint;
  8515. o->mode = Addressing_OptionalOk;
  8516. return kind;
  8517. }
  8518. }
  8519. if (bsrc->Union.variants.count != 1) {
  8520. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8521. o->mode = Addressing_Invalid;
  8522. o->expr = node;
  8523. return kind;
  8524. }
  8525. add_type_info_type(c, o->type);
  8526. add_type_info_type(c, bsrc->Union.variants[0]);
  8527. o->type = bsrc->Union.variants[0];
  8528. o->mode = Addressing_OptionalOk;
  8529. } else {
  8530. Type *t = check_type(c, ta->type);
  8531. Type *dst = t;
  8532. if (is_type_union(src)) {
  8533. bool ok = false;
  8534. for (Type *vt : bsrc->Union.variants) {
  8535. if (are_types_identical(vt, dst)) {
  8536. ok = true;
  8537. break;
  8538. }
  8539. }
  8540. if (!ok) {
  8541. gbString expr_str = expr_to_string(o->expr);
  8542. gbString dst_type_str = type_to_string(t);
  8543. defer (gb_string_free(expr_str));
  8544. defer (gb_string_free(dst_type_str));
  8545. if (bsrc->Union.variants.count == 0) {
  8546. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8547. } else {
  8548. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8549. }
  8550. o->mode = Addressing_Invalid;
  8551. o->expr = node;
  8552. return kind;
  8553. }
  8554. add_type_info_type(c, o->type);
  8555. add_type_info_type(c, t);
  8556. o->type = t;
  8557. o->mode = Addressing_OptionalOk;
  8558. } else if (is_type_any(src)) {
  8559. o->type = t;
  8560. o->mode = Addressing_OptionalOk;
  8561. add_type_info_type(c, o->type);
  8562. add_type_info_type(c, t);
  8563. } else {
  8564. gbString str = type_to_string(o->type);
  8565. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8566. gb_string_free(str);
  8567. o->mode = Addressing_Invalid;
  8568. o->expr = node;
  8569. return kind;
  8570. }
  8571. }
  8572. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8573. add_package_dependency(c, "runtime", "type_assertion_check");
  8574. add_package_dependency(c, "runtime", "type_assertion_check2");
  8575. }
  8576. return kind;
  8577. }
  8578. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8579. ast_node(se, SelectorCallExpr, node);
  8580. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8581. // COM APIs is a great example of where this kind of thing is extremely useful
  8582. // General idea:
  8583. //
  8584. // x->y(123) == x.y(x, 123)
  8585. //
  8586. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8587. // Just regenerating a new AST aids things
  8588. //
  8589. // TODO(bill): Is this a good hack or not?
  8590. //
  8591. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8592. if (se->modified_call) {
  8593. // Prevent double evaluation
  8594. o->expr = node;
  8595. o->type = node->tav.type;
  8596. o->value = node->tav.value;
  8597. o->mode = node->tav.mode;
  8598. return Expr_Expr;
  8599. }
  8600. bool allow_arrow_right_selector_expr;
  8601. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8602. c->allow_arrow_right_selector_expr = true;
  8603. Operand x = {};
  8604. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8605. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8606. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8607. o->mode = Addressing_Invalid;
  8608. o->type = t_invalid;
  8609. o->expr = node;
  8610. return kind;
  8611. }
  8612. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8613. gbString type_str = type_to_string(x.type);
  8614. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8615. gb_string_free(type_str);
  8616. o->mode = Addressing_Invalid;
  8617. o->type = t_invalid;
  8618. o->expr = node;
  8619. return Expr_Stmt;
  8620. }
  8621. ast_node(ce, CallExpr, se->call);
  8622. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8623. Ast *first_arg = x.expr->SelectorExpr.expr;
  8624. GB_ASSERT(first_arg != nullptr);
  8625. Entity *e = entity_of_node(se->expr);
  8626. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8627. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8628. }
  8629. if (e->kind != Entity_ProcGroup) {
  8630. Type *pt = base_type(x.type);
  8631. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8632. Type *first_type = nullptr;
  8633. String first_arg_name = {};
  8634. if (pt->Proc.param_count > 0) {
  8635. Entity *f = pt->Proc.params->Tuple.variables[0];
  8636. first_type = f->type;
  8637. first_arg_name = f->token.string;
  8638. }
  8639. if (first_arg_name.len == 0) {
  8640. first_arg_name = str_lit("_");
  8641. }
  8642. if (first_type == nullptr) {
  8643. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8644. o->mode = Addressing_Invalid;
  8645. o->type = t_invalid;
  8646. o->expr = node;
  8647. return Expr_Stmt;
  8648. }
  8649. Operand y = {};
  8650. y.mode = first_arg->tav.mode;
  8651. y.type = first_arg->tav.type;
  8652. y.value = first_arg->tav.value;
  8653. if (check_is_assignable_to(c, &y, first_type)) {
  8654. // Do nothing, it's valid
  8655. } else {
  8656. Operand z = y;
  8657. z.type = type_deref(y.type);
  8658. if (check_is_assignable_to(c, &z, first_type)) {
  8659. // NOTE(bill): AST GENERATION HACK!
  8660. Token op = {Token_Pointer};
  8661. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8662. } else if (y.mode == Addressing_Variable) {
  8663. Operand w = y;
  8664. w.type = alloc_type_pointer(y.type);
  8665. if (check_is_assignable_to(c, &w, first_type)) {
  8666. // NOTE(bill): AST GENERATION HACK!
  8667. Token op = {Token_And};
  8668. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8669. }
  8670. }
  8671. }
  8672. if (ce->args.count > 0) {
  8673. bool fail = false;
  8674. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8675. for (Ast *arg : ce->args) {
  8676. bool mix = false;
  8677. if (first_is_field_value) {
  8678. mix = arg->kind != Ast_FieldValue;
  8679. } else {
  8680. mix = arg->kind == Ast_FieldValue;
  8681. }
  8682. if (mix) {
  8683. fail = true;
  8684. break;
  8685. }
  8686. }
  8687. if (!fail && first_is_field_value) {
  8688. Token op = {Token_Eq};
  8689. AstFile *f = first_arg->file();
  8690. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8691. }
  8692. }
  8693. }
  8694. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8695. modified_args[0] = first_arg;
  8696. slice_copy(&modified_args, ce->args, 1);
  8697. ce->args = modified_args;
  8698. se->modified_call = true;
  8699. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8700. c->allow_arrow_right_selector_expr = true;
  8701. check_expr_base(c, o, se->call, type_hint);
  8702. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8703. o->expr = node;
  8704. return Expr_Expr;
  8705. }
  8706. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8707. ExprKind kind = Expr_Expr;
  8708. ast_node(ie, IndexExpr, node);
  8709. check_expr(c, o, ie->expr);
  8710. node->viral_state_flags |= ie->expr->viral_state_flags;
  8711. if (o->mode == Addressing_Invalid) {
  8712. o->expr = node;
  8713. return kind;
  8714. }
  8715. Type *t = base_type(type_deref(o->type));
  8716. bool is_ptr = is_type_pointer(o->type);
  8717. bool is_const = o->mode == Addressing_Constant;
  8718. if (is_type_map(t)) {
  8719. Operand key = {};
  8720. if (is_type_typeid(t->Map.key)) {
  8721. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8722. } else {
  8723. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8724. }
  8725. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8726. if (key.mode == Addressing_Invalid) {
  8727. o->mode = Addressing_Invalid;
  8728. o->expr = node;
  8729. return kind;
  8730. }
  8731. o->mode = Addressing_MapIndex;
  8732. o->type = t->Map.value;
  8733. o->expr = node;
  8734. add_map_get_dependencies(c);
  8735. add_map_set_dependencies(c);
  8736. return Expr_Expr;
  8737. }
  8738. i64 max_count = -1;
  8739. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8740. if (is_const) {
  8741. if (is_type_array(t)) {
  8742. // Okay
  8743. } else if (is_type_slice(t)) {
  8744. // Okay
  8745. } else if (is_type_enumerated_array(t)) {
  8746. // Okay
  8747. } else if (is_type_string(t)) {
  8748. // Okay
  8749. } else if (is_type_relative_multi_pointer(t)) {
  8750. // Okay
  8751. } else if (is_type_matrix(t)) {
  8752. // Okay
  8753. } else {
  8754. valid = false;
  8755. }
  8756. }
  8757. if (!valid) {
  8758. gbString str = expr_to_string(o->expr);
  8759. gbString type_str = type_to_string(o->type);
  8760. defer (gb_string_free(str));
  8761. defer (gb_string_free(type_str));
  8762. if (is_const) {
  8763. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8764. } else {
  8765. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8766. }
  8767. o->mode = Addressing_Invalid;
  8768. o->expr = node;
  8769. return kind;
  8770. }
  8771. if (ie->index == nullptr) {
  8772. gbString str = expr_to_string(o->expr);
  8773. error(o->expr, "Missing index for '%s'", str);
  8774. gb_string_free(str);
  8775. o->mode = Addressing_Invalid;
  8776. o->expr = node;
  8777. return kind;
  8778. }
  8779. Type *index_type_hint = nullptr;
  8780. if (is_type_enumerated_array(t)) {
  8781. Type *bt = base_type(t);
  8782. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8783. index_type_hint = bt->EnumeratedArray.index;
  8784. }
  8785. i64 index = 0;
  8786. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8787. if (is_const) {
  8788. if (index < 0) {
  8789. ERROR_BLOCK();
  8790. gbString str = expr_to_string(o->expr);
  8791. error(o->expr, "Cannot index a constant '%s'", str);
  8792. if (!build_context.terse_errors) {
  8793. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8794. }
  8795. gb_string_free(str);
  8796. o->mode = Addressing_Invalid;
  8797. o->expr = node;
  8798. return kind;
  8799. } else if (ok) {
  8800. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8801. o->mode = Addressing_Constant;
  8802. bool success = false;
  8803. bool finish = false;
  8804. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8805. if (!success) {
  8806. ERROR_BLOCK();
  8807. gbString str = expr_to_string(o->expr);
  8808. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8809. if (!build_context.terse_errors) {
  8810. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8811. }
  8812. gb_string_free(str);
  8813. o->mode = Addressing_Invalid;
  8814. o->expr = node;
  8815. return kind;
  8816. }
  8817. }
  8818. }
  8819. if (type_hint != nullptr && is_type_matrix(t)) {
  8820. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8821. // if a type hint exists
  8822. }
  8823. return kind;
  8824. }
  8825. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8826. ExprKind kind = Expr_Stmt;
  8827. ast_node(se, SliceExpr, node);
  8828. check_expr(c, o, se->expr);
  8829. node->viral_state_flags |= se->expr->viral_state_flags;
  8830. if (o->mode == Addressing_Invalid) {
  8831. o->mode = Addressing_Invalid;
  8832. o->expr = node;
  8833. return kind;
  8834. }
  8835. bool valid = false;
  8836. i64 max_count = -1;
  8837. Type *t = base_type(type_deref(o->type));
  8838. switch (t->kind) {
  8839. case Type_Basic:
  8840. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8841. valid = true;
  8842. if (o->mode == Addressing_Constant) {
  8843. max_count = o->value.value_string.len;
  8844. }
  8845. o->type = type_deref(o->type);
  8846. }
  8847. break;
  8848. case Type_Array:
  8849. valid = true;
  8850. max_count = t->Array.count;
  8851. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8852. gbString str = expr_to_string(node);
  8853. error(node, "Cannot slice array '%s', value is not addressable", str);
  8854. gb_string_free(str);
  8855. o->mode = Addressing_Invalid;
  8856. o->expr = node;
  8857. return kind;
  8858. }
  8859. o->type = alloc_type_slice(t->Array.elem);
  8860. break;
  8861. case Type_MultiPointer:
  8862. valid = true;
  8863. o->type = type_deref(o->type);
  8864. break;
  8865. case Type_Slice:
  8866. valid = true;
  8867. o->type = type_deref(o->type);
  8868. break;
  8869. case Type_DynamicArray:
  8870. valid = true;
  8871. o->type = alloc_type_slice(t->DynamicArray.elem);
  8872. break;
  8873. case Type_Struct:
  8874. if (is_type_soa_struct(t)) {
  8875. valid = true;
  8876. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8877. }
  8878. break;
  8879. case Type_RelativeMultiPointer:
  8880. valid = true;
  8881. o->type = type_deref(o->type);
  8882. break;
  8883. case Type_EnumeratedArray:
  8884. {
  8885. gbString str = expr_to_string(o->expr);
  8886. gbString type_str = type_to_string(o->type);
  8887. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8888. gb_string_free(type_str);
  8889. gb_string_free(str);
  8890. o->mode = Addressing_Invalid;
  8891. o->expr = node;
  8892. return kind;
  8893. }
  8894. break;
  8895. }
  8896. if (!valid) {
  8897. gbString str = expr_to_string(o->expr);
  8898. gbString type_str = type_to_string(o->type);
  8899. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8900. gb_string_free(type_str);
  8901. gb_string_free(str);
  8902. o->mode = Addressing_Invalid;
  8903. o->expr = node;
  8904. return kind;
  8905. }
  8906. if (se->low == nullptr && se->high != nullptr) {
  8907. // It is okay to continue as it will assume the 1st index is zero
  8908. }
  8909. i64 indices[2] = {};
  8910. Ast *nodes[2] = {se->low, se->high};
  8911. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8912. i64 index = max_count;
  8913. if (nodes[i] != nullptr) {
  8914. i64 capacity = -1;
  8915. if (max_count >= 0) {
  8916. capacity = max_count;
  8917. }
  8918. i64 j = 0;
  8919. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8920. index = j;
  8921. }
  8922. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8923. } else if (i == 0) {
  8924. index = 0;
  8925. }
  8926. indices[i] = index;
  8927. }
  8928. for (isize i = 0; i < gb_count_of(indices); i++) {
  8929. i64 a = indices[i];
  8930. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8931. i64 b = indices[j];
  8932. if (a > b && b >= 0) {
  8933. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8934. }
  8935. }
  8936. }
  8937. if (max_count < 0) {
  8938. if (o->mode == Addressing_Constant) {
  8939. gbString s = expr_to_string(se->expr);
  8940. error(se->expr, "Cannot slice constant value '%s'", s);
  8941. gb_string_free(s);
  8942. }
  8943. }
  8944. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8945. /*
  8946. x[:] -> [^]T
  8947. x[i:] -> [^]T
  8948. x[:n] -> []T
  8949. x[i:n] -> []T
  8950. */
  8951. o->type = alloc_type_slice(t->MultiPointer.elem);
  8952. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  8953. /*
  8954. x[:] -> [^]T
  8955. x[i:] -> [^]T
  8956. x[:n] -> []T
  8957. x[i:n] -> []T
  8958. */
  8959. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  8960. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  8961. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  8962. }
  8963. o->mode = Addressing_Value;
  8964. if (is_type_string(t) && max_count >= 0) {
  8965. bool all_constant = true;
  8966. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8967. if (nodes[i] != nullptr) {
  8968. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8969. if (tav.mode != Addressing_Constant) {
  8970. all_constant = false;
  8971. break;
  8972. }
  8973. }
  8974. }
  8975. if (!all_constant) {
  8976. ERROR_BLOCK();
  8977. gbString str = expr_to_string(o->expr);
  8978. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8979. if (!build_context.terse_errors) {
  8980. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8981. }
  8982. gb_string_free(str);
  8983. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8984. o->expr = node;
  8985. return kind;
  8986. }
  8987. String s = {};
  8988. if (o->value.kind == ExactValue_String) {
  8989. s = o->value.value_string;
  8990. }
  8991. o->mode = Addressing_Constant;
  8992. o->type = t;
  8993. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8994. }
  8995. return kind;
  8996. }
  8997. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8998. u32 prev_state_flags = c->state_flags;
  8999. defer (c->state_flags = prev_state_flags);
  9000. if (node->state_flags != 0) {
  9001. u32 in = node->state_flags;
  9002. u32 out = c->state_flags;
  9003. if (in & StateFlag_no_bounds_check) {
  9004. out |= StateFlag_no_bounds_check;
  9005. out &= ~StateFlag_bounds_check;
  9006. } else if (in & StateFlag_bounds_check) {
  9007. out |= StateFlag_bounds_check;
  9008. out &= ~StateFlag_no_bounds_check;
  9009. }
  9010. if (in & StateFlag_no_type_assert) {
  9011. out |= StateFlag_no_type_assert;
  9012. out &= ~StateFlag_type_assert;
  9013. } else if (in & StateFlag_type_assert) {
  9014. out |= StateFlag_type_assert;
  9015. out &= ~StateFlag_no_type_assert;
  9016. }
  9017. c->state_flags = out;
  9018. }
  9019. ExprKind kind = Expr_Stmt;
  9020. o->mode = Addressing_Invalid;
  9021. o->type = t_invalid;
  9022. o->value = {ExactValue_Invalid};
  9023. switch (node->kind) {
  9024. default:
  9025. return kind;
  9026. case_ast_node(be, BadExpr, node)
  9027. return kind;
  9028. case_end;
  9029. case_ast_node(i, Implicit, node)
  9030. switch (i->kind) {
  9031. case Token_context:
  9032. {
  9033. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9034. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  9035. return kind;
  9036. }
  9037. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9038. c->scope->flags |= ScopeFlag_ContextDefined;
  9039. }
  9040. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9041. error(node, "'context' has not been defined within this scope");
  9042. // Continue with value
  9043. }
  9044. init_core_context(c->checker);
  9045. o->mode = Addressing_Context;
  9046. o->type = t_context;
  9047. }
  9048. break;
  9049. default:
  9050. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9051. return kind;
  9052. }
  9053. case_end;
  9054. case_ast_node(i, Ident, node);
  9055. check_ident(c, o, node, nullptr, type_hint, false);
  9056. case_end;
  9057. case_ast_node(u, Uninit, node);
  9058. o->mode = Addressing_Value;
  9059. o->type = t_untyped_uninit;
  9060. error(node, "Use of --- outside of variable declaration");
  9061. case_end;
  9062. case_ast_node(bl, BasicLit, node);
  9063. Type *t = t_invalid;
  9064. switch (node->tav.value.kind) {
  9065. case ExactValue_String: t = t_untyped_string; break;
  9066. case ExactValue_Float: t = t_untyped_float; break;
  9067. case ExactValue_Complex: t = t_untyped_complex; break;
  9068. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9069. case ExactValue_Integer:
  9070. t = t_untyped_integer;
  9071. if (bl->token.kind == Token_Rune) {
  9072. t = t_untyped_rune;
  9073. }
  9074. break;
  9075. default:
  9076. GB_PANIC("Unhandled value type for basic literal");
  9077. break;
  9078. }
  9079. o->mode = Addressing_Constant;
  9080. o->type = t;
  9081. o->value = node->tav.value;
  9082. case_end;
  9083. case_ast_node(bd, BasicDirective, node);
  9084. kind = check_basic_directive_expr(c, o, node, type_hint);
  9085. case_end;
  9086. case_ast_node(pg, ProcGroup, node);
  9087. error(node, "Illegal use of a procedure group");
  9088. o->mode = Addressing_Invalid;
  9089. case_end;
  9090. case_ast_node(pl, ProcLit, node);
  9091. CheckerContext ctx = *c;
  9092. DeclInfo *decl = nullptr;
  9093. Type *type = alloc_type(Type_Proc);
  9094. check_open_scope(&ctx, pl->type);
  9095. {
  9096. decl = make_decl_info(ctx.scope, ctx.decl);
  9097. decl->proc_lit = node;
  9098. ctx.decl = decl;
  9099. defer (ctx.decl = ctx.decl->parent);
  9100. if (pl->tags != 0) {
  9101. error(node, "A procedure literal cannot have tags");
  9102. pl->tags = 0; // TODO(bill): Should I zero this?!
  9103. }
  9104. check_procedure_type(&ctx, type, pl->type);
  9105. if (!is_type_proc(type)) {
  9106. gbString str = expr_to_string(node);
  9107. error(node, "Invalid procedure literal '%s'", str);
  9108. gb_string_free(str);
  9109. check_close_scope(&ctx);
  9110. return kind;
  9111. }
  9112. if (pl->body == nullptr) {
  9113. error(node, "A procedure literal must have a body");
  9114. return kind;
  9115. }
  9116. pl->decl = decl;
  9117. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9118. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9119. array_add(&ctx.checker->nested_proc_lits, decl);
  9120. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9121. }
  9122. check_close_scope(&ctx);
  9123. o->mode = Addressing_Value;
  9124. o->type = type;
  9125. case_end;
  9126. case_ast_node(te, TernaryIfExpr, node);
  9127. kind = check_ternary_if_expr(c, o, node, type_hint);
  9128. case_end;
  9129. case_ast_node(te, TernaryWhenExpr, node);
  9130. kind = check_ternary_when_expr(c, o, node, type_hint);
  9131. case_end;
  9132. case_ast_node(oe, OrElseExpr, node);
  9133. return check_or_else_expr(c, o, node, type_hint);
  9134. case_end;
  9135. case_ast_node(re, OrReturnExpr, node);
  9136. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9137. return check_or_return_expr(c, o, node, type_hint);
  9138. case_end;
  9139. case_ast_node(re, OrBranchExpr, node);
  9140. return check_or_branch_expr(c, o, node, type_hint);
  9141. case_end;
  9142. case_ast_node(cl, CompoundLit, node);
  9143. kind = check_compound_literal(c, o, node, type_hint);
  9144. case_end;
  9145. case_ast_node(pe, ParenExpr, node);
  9146. kind = check_expr_base(c, o, pe->expr, type_hint);
  9147. node->viral_state_flags |= pe->expr->viral_state_flags;
  9148. o->expr = node;
  9149. case_end;
  9150. case_ast_node(te, TagExpr, node);
  9151. String name = te->name.string;
  9152. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9153. if (te->expr) {
  9154. kind = check_expr_base(c, o, te->expr, type_hint);
  9155. node->viral_state_flags |= te->expr->viral_state_flags;
  9156. }
  9157. o->expr = node;
  9158. case_end;
  9159. case_ast_node(ta, TypeAssertion, node);
  9160. kind = check_type_assertion(c, o, node, type_hint);
  9161. case_end;
  9162. case_ast_node(tc, TypeCast, node);
  9163. check_expr_or_type(c, o, tc->type);
  9164. if (o->mode != Addressing_Type) {
  9165. gbString str = expr_to_string(tc->type);
  9166. error(tc->type, "Expected a type, got %s", str);
  9167. gb_string_free(str);
  9168. o->mode = Addressing_Invalid;
  9169. }
  9170. if (o->mode == Addressing_Invalid) {
  9171. o->expr = node;
  9172. return kind;
  9173. }
  9174. Type *type = o->type;
  9175. check_expr_base(c, o, tc->expr, type);
  9176. node->viral_state_flags |= tc->expr->viral_state_flags;
  9177. if (o->mode != Addressing_Invalid) {
  9178. switch (tc->token.kind) {
  9179. case Token_transmute:
  9180. check_transmute(c, node, o, type);
  9181. break;
  9182. case Token_cast:
  9183. check_cast(c, o, type);
  9184. break;
  9185. default:
  9186. error(node, "Invalid AST: Invalid casting expression");
  9187. o->mode = Addressing_Invalid;
  9188. break;
  9189. }
  9190. }
  9191. return Expr_Expr;
  9192. case_end;
  9193. case_ast_node(ac, AutoCast, node);
  9194. check_expr_base(c, o, ac->expr, type_hint);
  9195. node->viral_state_flags |= ac->expr->viral_state_flags;
  9196. if (o->mode == Addressing_Invalid) {
  9197. o->expr = node;
  9198. return kind;
  9199. }
  9200. if (type_hint) {
  9201. check_cast(c, o, type_hint);
  9202. }
  9203. o->expr = node;
  9204. return Expr_Expr;
  9205. case_end;
  9206. case_ast_node(ue, UnaryExpr, node);
  9207. Type *th = type_hint;
  9208. if (ue->op.kind == Token_And) {
  9209. th = type_deref(th);
  9210. }
  9211. check_expr_base(c, o, ue->expr, th);
  9212. node->viral_state_flags |= ue->expr->viral_state_flags;
  9213. if (o->mode != Addressing_Invalid) {
  9214. check_unary_expr(c, o, ue->op, node);
  9215. }
  9216. o->expr = node;
  9217. return Expr_Expr;
  9218. case_end;
  9219. case_ast_node(be, BinaryExpr, node);
  9220. check_binary_expr(c, o, node, type_hint, true);
  9221. if (o->mode == Addressing_Invalid) {
  9222. o->expr = node;
  9223. return kind;
  9224. }
  9225. case_end;
  9226. case_ast_node(se, SelectorExpr, node);
  9227. check_selector(c, o, node, type_hint);
  9228. node->viral_state_flags |= se->expr->viral_state_flags;
  9229. case_end;
  9230. case_ast_node(se, SelectorCallExpr, node);
  9231. return check_selector_call_expr(c, o, node, type_hint);
  9232. case_end;
  9233. case_ast_node(ise, ImplicitSelectorExpr, node);
  9234. return check_implicit_selector_expr(c, o, node, type_hint);
  9235. case_end;
  9236. case_ast_node(ie, IndexExpr, node);
  9237. kind = check_index_expr(c, o, node, type_hint);
  9238. case_end;
  9239. case_ast_node(se, SliceExpr, node);
  9240. kind = check_slice_expr(c, o, node, type_hint);
  9241. case_end;
  9242. case_ast_node(mie, MatrixIndexExpr, node);
  9243. check_matrix_index_expr(c, o, node, type_hint);
  9244. o->expr = node;
  9245. return Expr_Expr;
  9246. case_end;
  9247. case_ast_node(ce, CallExpr, node);
  9248. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9249. case_end;
  9250. case_ast_node(de, DerefExpr, node);
  9251. check_expr_or_type(c, o, de->expr);
  9252. node->viral_state_flags |= de->expr->viral_state_flags;
  9253. if (o->mode == Addressing_Invalid) {
  9254. o->mode = Addressing_Invalid;
  9255. o->expr = node;
  9256. return kind;
  9257. } else {
  9258. Type *t = base_type(o->type);
  9259. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9260. o->mode = Addressing_Variable;
  9261. o->type = t->Pointer.elem;
  9262. } else if (t->kind == Type_SoaPointer) {
  9263. o->mode = Addressing_SoaVariable;
  9264. o->type = type_deref(t);
  9265. } else if (t->kind == Type_RelativePointer) {
  9266. if (o->mode != Addressing_Variable) {
  9267. gbString str = expr_to_string(o->expr);
  9268. gbString typ = type_to_string(o->type);
  9269. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9270. gb_string_free(typ);
  9271. gb_string_free(str);
  9272. }
  9273. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9274. add_type_info_type(c, o->type);
  9275. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9276. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9277. o->mode = Addressing_Variable;
  9278. o->type = ptr_type->Pointer.elem;
  9279. } else {
  9280. gbString str = expr_to_string(o->expr);
  9281. gbString typ = type_to_string(o->type);
  9282. ERROR_BLOCK();
  9283. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9284. if (o->type && is_type_multi_pointer(o->type)) {
  9285. if (!build_context.terse_errors) {
  9286. error_line("\tDid you mean '%s[0]'?\n", str);
  9287. }
  9288. }
  9289. gb_string_free(typ);
  9290. gb_string_free(str);
  9291. o->mode = Addressing_Invalid;
  9292. o->expr = node;
  9293. return kind;
  9294. }
  9295. }
  9296. case_end;
  9297. case_ast_node(ia, InlineAsmExpr, node);
  9298. if (c->curr_proc_decl == nullptr) {
  9299. error(node, "Inline asm expressions are only allowed within a procedure body");
  9300. }
  9301. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9302. Type *return_type = nullptr;
  9303. for_array(i, ia->param_types) {
  9304. param_types[i] = check_type(c, ia->param_types[i]);
  9305. }
  9306. if (ia->return_type != nullptr) {
  9307. return_type = check_type(c, ia->return_type);
  9308. }
  9309. Operand x = {};
  9310. check_expr(c, &x, ia->asm_string);
  9311. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9312. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9313. }
  9314. check_expr(c, &x, ia->constraints_string);
  9315. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9316. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9317. }
  9318. Scope *scope = create_scope(c->info, c->scope);
  9319. scope->flags |= ScopeFlag_Proc;
  9320. Type *params = alloc_type_tuple();
  9321. Type *results = alloc_type_tuple();
  9322. if (param_types.count != 0) {
  9323. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9324. for_array(i, param_types) {
  9325. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9326. }
  9327. }
  9328. if (return_type != nullptr) {
  9329. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9330. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9331. }
  9332. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9333. o->type = pt;
  9334. o->mode = Addressing_Value;
  9335. o->expr = node;
  9336. return Expr_Expr;
  9337. case_end;
  9338. case Ast_TypeidType:
  9339. case Ast_PolyType:
  9340. case Ast_ProcType:
  9341. case Ast_PointerType:
  9342. case Ast_MultiPointerType:
  9343. case Ast_ArrayType:
  9344. case Ast_DynamicArrayType:
  9345. case Ast_StructType:
  9346. case Ast_UnionType:
  9347. case Ast_EnumType:
  9348. case Ast_MapType:
  9349. case Ast_BitSetType:
  9350. case Ast_MatrixType:
  9351. case Ast_RelativeType:
  9352. o->mode = Addressing_Type;
  9353. o->type = check_type(c, node);
  9354. break;
  9355. }
  9356. kind = Expr_Expr;
  9357. o->expr = node;
  9358. return kind;
  9359. }
  9360. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9361. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9362. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9363. o->type = t_invalid;
  9364. gbString xs = expr_to_string(o->expr);
  9365. if (o->mode == Addressing_Type) {
  9366. error(o->expr, "Invalid type usage '%s'", xs);
  9367. } else {
  9368. error(o->expr, "Invalid expression '%s'", xs);
  9369. }
  9370. gb_string_free(xs);
  9371. }
  9372. if (o->type != nullptr && is_type_untyped(o->type)) {
  9373. add_untyped(c, node, o->mode, o->type, o->value);
  9374. }
  9375. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9376. add_type_and_value(c, node, o->mode, o->type, o->value);
  9377. return kind;
  9378. }
  9379. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9380. check_expr_base(c, o, e, nullptr);
  9381. switch (o->mode) {
  9382. default:
  9383. return; // NOTE(bill): Valid
  9384. case Addressing_NoValue:
  9385. error_operand_no_value(o);
  9386. break;
  9387. }
  9388. o->mode = Addressing_Invalid;
  9389. }
  9390. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9391. check_expr_base(c, o, e, nullptr);
  9392. switch (o->mode) {
  9393. default:
  9394. return; // NOTE(bill): Valid
  9395. case Addressing_NoValue:
  9396. error_operand_no_value(o);
  9397. break;
  9398. case Addressing_Type:
  9399. error_operand_not_expression(o);
  9400. break;
  9401. }
  9402. o->mode = Addressing_Invalid;
  9403. }
  9404. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9405. check_expr_base(c, o, e, type_hint);
  9406. switch (o->mode) {
  9407. default:
  9408. return; // NOTE(bill): Valid
  9409. case Addressing_NoValue:
  9410. error_operand_no_value(o);
  9411. break;
  9412. case Addressing_Type:
  9413. error_operand_not_expression(o);
  9414. break;
  9415. }
  9416. o->mode = Addressing_Invalid;
  9417. }
  9418. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9419. if (o->mode == Addressing_Value) {
  9420. // NOTE(bill): Tuples are not first class thus never named
  9421. if (o->type->kind == Type_Tuple) {
  9422. isize count = o->type->Tuple.variables.count;
  9423. error(o->expr,
  9424. "%td-valued expression found where single value expected", count);
  9425. o->mode = Addressing_Invalid;
  9426. GB_ASSERT(count != 1);
  9427. }
  9428. }
  9429. }
  9430. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9431. check_multi_expr(c, o, e);
  9432. check_not_tuple(c, o);
  9433. }
  9434. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9435. check_expr_base(c, o, e, type_hint);
  9436. check_not_tuple(c, o);
  9437. error_operand_no_value(o);
  9438. }
  9439. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9440. switch (v.kind) {
  9441. case ExactValue_Invalid:
  9442. return true;
  9443. case ExactValue_Bool:
  9444. return !v.value_bool;
  9445. case ExactValue_String:
  9446. return v.value_string.len == 0;
  9447. case ExactValue_Integer:
  9448. return big_int_is_zero(&v.value_integer);
  9449. case ExactValue_Float:
  9450. return v.value_float == 0.0;
  9451. case ExactValue_Complex:
  9452. if (v.value_complex) {
  9453. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9454. }
  9455. return true;
  9456. case ExactValue_Quaternion:
  9457. if (v.value_quaternion) {
  9458. return v.value_quaternion->real == 0.0 &&
  9459. v.value_quaternion->imag == 0.0 &&
  9460. v.value_quaternion->jmag == 0.0 &&
  9461. v.value_quaternion->kmag == 0.0;
  9462. }
  9463. return true;
  9464. case ExactValue_Pointer:
  9465. return v.value_pointer == 0;
  9466. case ExactValue_Compound:
  9467. if (v.value_compound == nullptr) {
  9468. return true;
  9469. } else {
  9470. ast_node(cl, CompoundLit, v.value_compound);
  9471. if (cl->elems.count == 0) {
  9472. return true;
  9473. } else {
  9474. for (Ast *elem : cl->elems) {
  9475. if (elem->tav.mode != Addressing_Constant) {
  9476. return false;
  9477. }
  9478. if (!is_exact_value_zero(elem->tav.value)) {
  9479. return false;
  9480. }
  9481. }
  9482. return true;
  9483. }
  9484. }
  9485. case ExactValue_Procedure:
  9486. return v.value_procedure == nullptr;
  9487. case ExactValue_Typeid:
  9488. return v.value_typeid == nullptr;
  9489. }
  9490. return true;
  9491. }
  9492. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9493. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9494. for_array(i, params) {
  9495. if (i > 0) {
  9496. str = gb_string_appendc(str, ", ");
  9497. }
  9498. str = write_expr_to_string(str, params[i], false);
  9499. }
  9500. return str;
  9501. }
  9502. gb_internal gbString string_append_string(gbString str, String string) {
  9503. if (string.len > 0) {
  9504. return gb_string_append_length(str, &string[0], string.len);
  9505. }
  9506. return str;
  9507. }
  9508. gb_internal gbString string_append_token(gbString str, Token token) {
  9509. str = string_append_string(str, token.string);
  9510. return str;
  9511. }
  9512. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9513. if (node == nullptr)
  9514. return str;
  9515. if (is_ast_stmt(node)) {
  9516. GB_ASSERT("stmt passed to write_expr_to_string");
  9517. }
  9518. switch (node->kind) {
  9519. default:
  9520. str = gb_string_appendc(str, "(BadExpr)");
  9521. break;
  9522. case_ast_node(i, Ident, node);
  9523. str = string_append_token(str, i->token);
  9524. case_end;
  9525. case_ast_node(i, Implicit, node);
  9526. str = string_append_token(str, *i);
  9527. case_end;
  9528. case_ast_node(bl, BasicLit, node);
  9529. str = string_append_token(str, bl->token);
  9530. case_end;
  9531. case_ast_node(bd, BasicDirective, node);
  9532. str = gb_string_append_rune(str, '#');
  9533. str = string_append_string(str, bd->name.string);
  9534. case_end;
  9535. case_ast_node(ud, Uninit, node);
  9536. str = gb_string_appendc(str, "---");
  9537. case_end;
  9538. case_ast_node(pg, ProcGroup, node);
  9539. str = gb_string_appendc(str, "proc{");
  9540. for_array(i, pg->args) {
  9541. if (i > 0) str = gb_string_appendc(str, ", ");
  9542. str = write_expr_to_string(str, pg->args[i], shorthand);
  9543. }
  9544. str = gb_string_append_rune(str, '}');
  9545. case_end;
  9546. case_ast_node(pl, ProcLit, node);
  9547. str = write_expr_to_string(str, pl->type, shorthand);
  9548. if (pl->body) {
  9549. str = gb_string_appendc(str, " {...}");
  9550. } else {
  9551. str = gb_string_appendc(str, " ---");
  9552. }
  9553. case_end;
  9554. case_ast_node(cl, CompoundLit, node);
  9555. str = write_expr_to_string(str, cl->type, shorthand);
  9556. str = gb_string_append_rune(str, '{');
  9557. if (shorthand) {
  9558. str = gb_string_appendc(str, "...");
  9559. } else {
  9560. for_array(i, cl->elems) {
  9561. if (i > 0) str = gb_string_appendc(str, ", ");
  9562. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9563. }
  9564. }
  9565. str = gb_string_append_rune(str, '}');
  9566. case_end;
  9567. case_ast_node(te, TagExpr, node);
  9568. str = gb_string_append_rune(str, '#');
  9569. str = string_append_token(str, te->name);
  9570. str = write_expr_to_string(str, te->expr, shorthand);
  9571. case_end;
  9572. case_ast_node(ue, UnaryExpr, node);
  9573. str = string_append_token(str, ue->op);
  9574. str = write_expr_to_string(str, ue->expr, shorthand);
  9575. case_end;
  9576. case_ast_node(de, DerefExpr, node);
  9577. str = write_expr_to_string(str, de->expr, shorthand);
  9578. str = gb_string_append_rune(str, '^');
  9579. case_end;
  9580. case_ast_node(be, BinaryExpr, node);
  9581. str = write_expr_to_string(str, be->left, shorthand);
  9582. str = gb_string_append_rune(str, ' ');
  9583. str = string_append_token(str, be->op);
  9584. str = gb_string_append_rune(str, ' ');
  9585. str = write_expr_to_string(str, be->right, shorthand);
  9586. case_end;
  9587. case_ast_node(te, TernaryIfExpr, node);
  9588. TokenPos x = ast_token(te->x).pos;
  9589. TokenPos cond = ast_token(te->cond).pos;
  9590. if (x < cond) {
  9591. str = write_expr_to_string(str, te->x, shorthand);
  9592. str = gb_string_appendc(str, " if ");
  9593. str = write_expr_to_string(str, te->cond, shorthand);
  9594. str = gb_string_appendc(str, " else ");
  9595. str = write_expr_to_string(str, te->y, shorthand);
  9596. } else {
  9597. str = write_expr_to_string(str, te->cond, shorthand);
  9598. str = gb_string_appendc(str, " ? ");
  9599. str = write_expr_to_string(str, te->x, shorthand);
  9600. str = gb_string_appendc(str, " : ");
  9601. str = write_expr_to_string(str, te->y, shorthand);
  9602. }
  9603. case_end;
  9604. case_ast_node(te, TernaryWhenExpr, node);
  9605. str = write_expr_to_string(str, te->x, shorthand);
  9606. str = gb_string_appendc(str, " when ");
  9607. str = write_expr_to_string(str, te->cond, shorthand);
  9608. str = gb_string_appendc(str, " else ");
  9609. str = write_expr_to_string(str, te->y, shorthand);
  9610. case_end;
  9611. case_ast_node(oe, OrElseExpr, node);
  9612. str = write_expr_to_string(str, oe->x, shorthand);
  9613. str = gb_string_appendc(str, " or_else ");
  9614. str = write_expr_to_string(str, oe->y, shorthand);
  9615. case_end;
  9616. case_ast_node(oe, OrReturnExpr, node);
  9617. str = write_expr_to_string(str, oe->expr, shorthand);
  9618. str = gb_string_appendc(str, " or_return");
  9619. case_end;
  9620. case_ast_node(oe, OrBranchExpr, node);
  9621. str = write_expr_to_string(str, oe->expr, shorthand);
  9622. str = gb_string_append_rune(str, ' ');
  9623. str = string_append_token(str, oe->token);
  9624. if (oe->label) {
  9625. str = gb_string_append_rune(str, ' ');
  9626. str = write_expr_to_string(str, oe->label, shorthand);
  9627. }
  9628. case_end;
  9629. case_ast_node(pe, ParenExpr, node);
  9630. str = gb_string_append_rune(str, '(');
  9631. str = write_expr_to_string(str, pe->expr, shorthand);
  9632. str = gb_string_append_rune(str, ')');
  9633. case_end;
  9634. case_ast_node(se, SelectorExpr, node);
  9635. str = write_expr_to_string(str, se->expr, shorthand);
  9636. str = string_append_token(str, se->token);
  9637. str = write_expr_to_string(str, se->selector, shorthand);
  9638. case_end;
  9639. case_ast_node(se, ImplicitSelectorExpr, node);
  9640. str = gb_string_append_rune(str, '.');
  9641. str = write_expr_to_string(str, se->selector, shorthand);
  9642. case_end;
  9643. case_ast_node(se, SelectorCallExpr, node);
  9644. str = write_expr_to_string(str, se->expr, shorthand);
  9645. str = gb_string_appendc(str, "(");
  9646. ast_node(ce, CallExpr, se->call);
  9647. isize start = se->modified_call ? 1 : 0;
  9648. for (isize i = start; i < ce->args.count; i++) {
  9649. Ast *arg = ce->args[i];
  9650. if (i > start) {
  9651. str = gb_string_appendc(str, ", ");
  9652. }
  9653. str = write_expr_to_string(str, arg, shorthand);
  9654. }
  9655. str = gb_string_appendc(str, ")");
  9656. case_end;
  9657. case_ast_node(ta, TypeAssertion, node);
  9658. str = write_expr_to_string(str, ta->expr, shorthand);
  9659. if (ta->type != nullptr &&
  9660. ta->type->kind == Ast_UnaryExpr &&
  9661. ta->type->UnaryExpr.op.kind == Token_Question) {
  9662. str = gb_string_appendc(str, ".?");
  9663. } else {
  9664. str = gb_string_appendc(str, ".(");
  9665. str = write_expr_to_string(str, ta->type, shorthand);
  9666. str = gb_string_append_rune(str, ')');
  9667. }
  9668. case_end;
  9669. case_ast_node(tc, TypeCast, node);
  9670. str = string_append_token(str, tc->token);
  9671. str = gb_string_append_rune(str, '(');
  9672. str = write_expr_to_string(str, tc->type, shorthand);
  9673. str = gb_string_append_rune(str, ')');
  9674. str = write_expr_to_string(str, tc->expr, shorthand);
  9675. case_end;
  9676. case_ast_node(ac, AutoCast, node);
  9677. str = string_append_token(str, ac->token);
  9678. str = gb_string_append_rune(str, ' ');
  9679. str = write_expr_to_string(str, ac->expr, shorthand);
  9680. case_end;
  9681. case_ast_node(ie, IndexExpr, node);
  9682. str = write_expr_to_string(str, ie->expr, shorthand);
  9683. str = gb_string_append_rune(str, '[');
  9684. str = write_expr_to_string(str, ie->index, shorthand);
  9685. str = gb_string_append_rune(str, ']');
  9686. case_end;
  9687. case_ast_node(se, SliceExpr, node);
  9688. str = write_expr_to_string(str, se->expr, shorthand);
  9689. str = gb_string_append_rune(str, '[');
  9690. str = write_expr_to_string(str, se->low, shorthand);
  9691. str = string_append_token(str, se->interval);
  9692. str = write_expr_to_string(str, se->high, shorthand);
  9693. str = gb_string_append_rune(str, ']');
  9694. case_end;
  9695. case_ast_node(mie, MatrixIndexExpr, node);
  9696. str = write_expr_to_string(str, mie->expr, shorthand);
  9697. str = gb_string_append_rune(str, '[');
  9698. str = write_expr_to_string(str, mie->row_index, shorthand);
  9699. str = gb_string_appendc(str, ", ");
  9700. str = write_expr_to_string(str, mie->column_index, shorthand);
  9701. str = gb_string_append_rune(str, ']');
  9702. case_end;
  9703. case_ast_node(e, Ellipsis, node);
  9704. str = gb_string_appendc(str, "..");
  9705. str = write_expr_to_string(str, e->expr, shorthand);
  9706. case_end;
  9707. case_ast_node(fv, FieldValue, node);
  9708. str = write_expr_to_string(str, fv->field, shorthand);
  9709. str = gb_string_appendc(str, " = ");
  9710. str = write_expr_to_string(str, fv->value, shorthand);
  9711. case_end;
  9712. case_ast_node(fv, EnumFieldValue, node);
  9713. str = write_expr_to_string(str, fv->name, shorthand);
  9714. if (fv->value) {
  9715. str = gb_string_appendc(str, " = ");
  9716. str = write_expr_to_string(str, fv->value, shorthand);
  9717. }
  9718. case_end;
  9719. case_ast_node(ht, HelperType, node);
  9720. str = gb_string_appendc(str, "#type ");
  9721. str = write_expr_to_string(str, ht->type, shorthand);
  9722. case_end;
  9723. case_ast_node(ht, DistinctType, node);
  9724. str = gb_string_appendc(str, "distinct ");
  9725. str = write_expr_to_string(str, ht->type, shorthand);
  9726. case_end;
  9727. case_ast_node(pt, PolyType, node);
  9728. str = gb_string_append_rune(str, '$');
  9729. str = write_expr_to_string(str, pt->type, shorthand);
  9730. if (pt->specialization != nullptr) {
  9731. str = gb_string_append_rune(str, '/');
  9732. str = write_expr_to_string(str, pt->specialization, shorthand);
  9733. }
  9734. case_end;
  9735. case_ast_node(pt, PointerType, node);
  9736. str = gb_string_append_rune(str, '^');
  9737. str = write_expr_to_string(str, pt->type, shorthand);
  9738. case_end;
  9739. case_ast_node(pt, MultiPointerType, node);
  9740. str = gb_string_appendc(str, "[^]");
  9741. str = write_expr_to_string(str, pt->type, shorthand);
  9742. case_end;
  9743. case_ast_node(at, ArrayType, node);
  9744. str = gb_string_append_rune(str, '[');
  9745. if (at->count != nullptr &&
  9746. at->count->kind == Ast_UnaryExpr &&
  9747. at->count->UnaryExpr.op.kind == Token_Question) {
  9748. str = gb_string_appendc(str, "?");
  9749. } else {
  9750. str = write_expr_to_string(str, at->count, shorthand);
  9751. }
  9752. str = gb_string_append_rune(str, ']');
  9753. str = write_expr_to_string(str, at->elem, shorthand);
  9754. case_end;
  9755. case_ast_node(at, DynamicArrayType, node);
  9756. str = gb_string_appendc(str, "[dynamic]");
  9757. str = write_expr_to_string(str, at->elem, shorthand);
  9758. case_end;
  9759. case_ast_node(bs, BitSetType, node);
  9760. str = gb_string_appendc(str, "bit_set[");
  9761. str = write_expr_to_string(str, bs->elem, shorthand);
  9762. str = gb_string_appendc(str, "]");
  9763. case_end;
  9764. case_ast_node(mt, MapType, node);
  9765. str = gb_string_appendc(str, "map[");
  9766. str = write_expr_to_string(str, mt->key, shorthand);
  9767. str = gb_string_append_rune(str, ']');
  9768. str = write_expr_to_string(str, mt->value, shorthand);
  9769. case_end;
  9770. case_ast_node(mt, MatrixType, node);
  9771. str = gb_string_appendc(str, "matrix[");
  9772. str = write_expr_to_string(str, mt->row_count, shorthand);
  9773. str = gb_string_appendc(str, ", ");
  9774. str = write_expr_to_string(str, mt->column_count, shorthand);
  9775. str = gb_string_append_rune(str, ']');
  9776. str = write_expr_to_string(str, mt->elem, shorthand);
  9777. case_end;
  9778. case_ast_node(f, Field, node);
  9779. if (f->flags&FieldFlag_using) {
  9780. str = gb_string_appendc(str, "using ");
  9781. }
  9782. if (f->flags&FieldFlag_no_alias) {
  9783. str = gb_string_appendc(str, "#no_alias ");
  9784. }
  9785. if (f->flags&FieldFlag_c_vararg) {
  9786. str = gb_string_appendc(str, "#c_vararg ");
  9787. }
  9788. if (f->flags&FieldFlag_any_int) {
  9789. str = gb_string_appendc(str, "#any_int ");
  9790. }
  9791. if (f->flags&FieldFlag_no_broadcast) {
  9792. str = gb_string_appendc(str, "#no_broadcast ");
  9793. }
  9794. if (f->flags&FieldFlag_const) {
  9795. str = gb_string_appendc(str, "#const ");
  9796. }
  9797. if (f->flags&FieldFlag_subtype) {
  9798. str = gb_string_appendc(str, "#subtype ");
  9799. }
  9800. for_array(i, f->names) {
  9801. Ast *name = f->names[i];
  9802. if (i > 0) str = gb_string_appendc(str, ", ");
  9803. str = write_expr_to_string(str, name, shorthand);
  9804. }
  9805. if (f->names.count > 0) {
  9806. if (f->type == nullptr && f->default_value != nullptr) {
  9807. str = gb_string_append_rune(str, ' ');
  9808. }
  9809. str = gb_string_appendc(str, ":");
  9810. }
  9811. if (f->type != nullptr) {
  9812. str = gb_string_append_rune(str, ' ');
  9813. str = write_expr_to_string(str, f->type, shorthand);
  9814. }
  9815. if (f->default_value != nullptr) {
  9816. if (f->type != nullptr) {
  9817. str = gb_string_append_rune(str, ' ');
  9818. }
  9819. str = gb_string_appendc(str, "= ");
  9820. str = write_expr_to_string(str, f->default_value, shorthand);
  9821. }
  9822. case_end;
  9823. case_ast_node(f, FieldList, node);
  9824. bool has_name = false;
  9825. for_array(i, f->list) {
  9826. ast_node(field, Field, f->list[i]);
  9827. if (field->names.count > 1) {
  9828. has_name = true;
  9829. break;
  9830. }
  9831. if (field->names.count == 0) {
  9832. continue;
  9833. }
  9834. if (!is_blank_ident(field->names[0])) {
  9835. has_name = true;
  9836. break;
  9837. }
  9838. }
  9839. for_array(i, f->list) {
  9840. if (i > 0) str = gb_string_appendc(str, ", ");
  9841. if (has_name) {
  9842. str = write_expr_to_string(str, f->list[i], shorthand);
  9843. } else {
  9844. ast_node(field, Field, f->list[i]);
  9845. if (field->flags&FieldFlag_using) {
  9846. str = gb_string_appendc(str, "using ");
  9847. }
  9848. if (field->flags&FieldFlag_no_alias) {
  9849. str = gb_string_appendc(str, "#no_alias ");
  9850. }
  9851. if (field->flags&FieldFlag_c_vararg) {
  9852. str = gb_string_appendc(str, "#c_vararg ");
  9853. }
  9854. if (field->flags&FieldFlag_any_int) {
  9855. str = gb_string_appendc(str, "#any_int ");
  9856. }
  9857. if (field->flags&FieldFlag_no_broadcast) {
  9858. str = gb_string_appendc(str, "#no_broadcast ");
  9859. }
  9860. if (field->flags&FieldFlag_const) {
  9861. str = gb_string_appendc(str, "#const ");
  9862. }
  9863. if (field->flags&FieldFlag_subtype) {
  9864. str = gb_string_appendc(str, "#subtype ");
  9865. }
  9866. str = write_expr_to_string(str, field->type, shorthand);
  9867. }
  9868. }
  9869. case_end;
  9870. case_ast_node(ce, CallExpr, node);
  9871. switch (ce->inlining) {
  9872. case ProcInlining_inline:
  9873. str = gb_string_appendc(str, "#force_inline ");
  9874. break;
  9875. case ProcInlining_no_inline:
  9876. str = gb_string_appendc(str, "#force_no_inline ");
  9877. break;
  9878. }
  9879. str = write_expr_to_string(str, ce->proc, shorthand);
  9880. str = gb_string_appendc(str, "(");
  9881. isize idx0 = cast(isize)ce->was_selector;
  9882. for (isize i = idx0; i < ce->args.count; i++) {
  9883. Ast *arg = ce->args[i];
  9884. if (i > idx0) {
  9885. str = gb_string_appendc(str, ", ");
  9886. }
  9887. str = write_expr_to_string(str, arg, shorthand);
  9888. }
  9889. str = gb_string_appendc(str, ")");
  9890. case_end;
  9891. case_ast_node(tt, TypeidType, node);
  9892. str = gb_string_appendc(str, "typeid");
  9893. if (tt->specialization) {
  9894. str = gb_string_appendc(str, "/");
  9895. str = write_expr_to_string(str, tt->specialization, shorthand);
  9896. }
  9897. case_end;
  9898. case_ast_node(pt, ProcType, node);
  9899. str = gb_string_appendc(str, "proc(");
  9900. str = write_expr_to_string(str, pt->params, shorthand);
  9901. str = gb_string_appendc(str, ")");
  9902. if (pt->results != nullptr) {
  9903. str = gb_string_appendc(str, " -> ");
  9904. bool parens_needed = false;
  9905. if (pt->results && pt->results->kind == Ast_FieldList) {
  9906. for (Ast *field : pt->results->FieldList.list) {
  9907. ast_node(f, Field, field);
  9908. if (f->names.count != 0) {
  9909. parens_needed = true;
  9910. break;
  9911. }
  9912. }
  9913. }
  9914. if (parens_needed) {
  9915. str = gb_string_append_rune(str, '(');
  9916. }
  9917. str = write_expr_to_string(str, pt->results, shorthand);
  9918. if (parens_needed) {
  9919. str = gb_string_append_rune(str, ')');
  9920. }
  9921. }
  9922. case_end;
  9923. case_ast_node(st, StructType, node);
  9924. str = gb_string_appendc(str, "struct ");
  9925. if (st->polymorphic_params) {
  9926. str = gb_string_append_rune(str, '(');
  9927. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9928. str = gb_string_appendc(str, ") ");
  9929. }
  9930. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9931. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9932. if (st->align) {
  9933. str = gb_string_appendc(str, "#align ");
  9934. str = write_expr_to_string(str, st->align, shorthand);
  9935. str = gb_string_append_rune(str, ' ');
  9936. }
  9937. str = gb_string_append_rune(str, '{');
  9938. if (shorthand) {
  9939. str = gb_string_appendc(str, "...");
  9940. } else {
  9941. str = write_struct_fields_to_string(str, st->fields);
  9942. }
  9943. str = gb_string_append_rune(str, '}');
  9944. case_end;
  9945. case_ast_node(st, UnionType, node);
  9946. str = gb_string_appendc(str, "union ");
  9947. if (st->polymorphic_params) {
  9948. str = gb_string_append_rune(str, '(');
  9949. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9950. str = gb_string_appendc(str, ") ");
  9951. }
  9952. switch (st->kind) {
  9953. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9954. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9955. }
  9956. if (st->align) {
  9957. str = gb_string_appendc(str, "#align ");
  9958. str = write_expr_to_string(str, st->align, shorthand);
  9959. str = gb_string_append_rune(str, ' ');
  9960. }
  9961. str = gb_string_append_rune(str, '{');
  9962. if (shorthand) {
  9963. str = gb_string_appendc(str, "...");
  9964. } else {
  9965. str = write_struct_fields_to_string(str, st->variants);
  9966. }
  9967. str = gb_string_append_rune(str, '}');
  9968. case_end;
  9969. case_ast_node(et, EnumType, node);
  9970. str = gb_string_appendc(str, "enum ");
  9971. if (et->base_type != nullptr) {
  9972. str = write_expr_to_string(str, et->base_type, shorthand);
  9973. str = gb_string_append_rune(str, ' ');
  9974. }
  9975. str = gb_string_append_rune(str, '{');
  9976. if (shorthand) {
  9977. str = gb_string_appendc(str, "...");
  9978. } else {
  9979. for_array(i, et->fields) {
  9980. if (i > 0) {
  9981. str = gb_string_appendc(str, ", ");
  9982. }
  9983. str = write_expr_to_string(str, et->fields[i], shorthand);
  9984. }
  9985. }
  9986. str = gb_string_append_rune(str, '}');
  9987. case_end;
  9988. case_ast_node(rt, RelativeType, node);
  9989. str = write_expr_to_string(str, rt->tag, shorthand);
  9990. str = gb_string_appendc(str, "" );
  9991. str = write_expr_to_string(str, rt->type, shorthand);
  9992. case_end;
  9993. case_ast_node(f, BitFieldField, node);
  9994. str = write_expr_to_string(str, f->name, shorthand);
  9995. str = gb_string_appendc(str, ": ");
  9996. str = write_expr_to_string(str, f->type, shorthand);
  9997. str = gb_string_appendc(str, " | ");
  9998. str = write_expr_to_string(str, f->bit_size, shorthand);
  9999. case_end;
  10000. case_ast_node(bf, BitFieldType, node);
  10001. str = gb_string_appendc(str, "bit_field ");
  10002. if (!shorthand) {
  10003. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10004. }
  10005. str = gb_string_appendc(str, " {");
  10006. if (shorthand) {
  10007. str = gb_string_appendc(str, "...");
  10008. } else {
  10009. for_array(i, bf->fields) {
  10010. if (i > 0) {
  10011. str = gb_string_appendc(str, ", ");
  10012. }
  10013. str = write_expr_to_string(str, bf->fields[i], false);
  10014. }
  10015. }
  10016. str = gb_string_appendc(str, "}");
  10017. case_end;
  10018. case_ast_node(ia, InlineAsmExpr, node);
  10019. str = gb_string_appendc(str, "asm(");
  10020. for_array(i, ia->param_types) {
  10021. if (i > 0) {
  10022. str = gb_string_appendc(str, ", ");
  10023. }
  10024. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10025. }
  10026. str = gb_string_appendc(str, ")");
  10027. if (ia->return_type != nullptr) {
  10028. str = gb_string_appendc(str, " -> ");
  10029. str = write_expr_to_string(str, ia->return_type, shorthand);
  10030. }
  10031. if (ia->has_side_effects) {
  10032. str = gb_string_appendc(str, " #side_effects");
  10033. }
  10034. if (ia->is_align_stack) {
  10035. str = gb_string_appendc(str, " #stack_align");
  10036. }
  10037. if (ia->dialect) {
  10038. str = gb_string_appendc(str, " #");
  10039. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10040. }
  10041. str = gb_string_appendc(str, " {");
  10042. if (shorthand) {
  10043. str = gb_string_appendc(str, "...");
  10044. } else {
  10045. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10046. str = gb_string_appendc(str, ", ");
  10047. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10048. }
  10049. str = gb_string_appendc(str, "}");
  10050. case_end;
  10051. }
  10052. return str;
  10053. }
  10054. gb_internal gbString expr_to_string(Ast *expression) {
  10055. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10056. }
  10057. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10058. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10059. }
  10060. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10061. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10062. }