check_expr.cpp 299 KB

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