check_expr.cpp 302 KB

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