check_expr.cpp 282 KB

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