check_expr.cpp 339 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  73. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gb_internal gbString expr_to_string (Ast *expression);
  75. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  76. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. gb_internal bool check_is_terminating (Ast *node, String const &label);
  78. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  84. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  89. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  90. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  91. gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
  96. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  97. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  98. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  99. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal bool is_diverging_expr(Ast *expr);
  101. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  102. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  103. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  104. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  105. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y);
  106. enum LoadDirectiveResult {
  107. LoadDirective_Success = 0,
  108. LoadDirective_Error = 1,
  109. LoadDirective_NotFound = 2,
  110. };
  111. gb_internal bool is_load_directive_call(Ast *call) {
  112. call = unparen_expr(call);
  113. if (call->kind != Ast_CallExpr) {
  114. return false;
  115. }
  116. ast_node(ce, CallExpr, call);
  117. if (ce->proc->kind != Ast_BasicDirective) {
  118. return false;
  119. }
  120. ast_node(bd, BasicDirective, ce->proc);
  121. String name = bd->name.string;
  122. return name == "load";
  123. }
  124. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  125. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  126. auto results = did_you_mean_results(d);
  127. if (results.count != 0) {
  128. error_line("\tSuggestion: Did you mean?\n");
  129. for (auto const &result : results) {
  130. String const &target = result.target;
  131. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  132. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  133. }
  134. }
  135. }
  136. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  137. if (e->kind != Entity_TypeName) {
  138. return;
  139. }
  140. if (e->TypeName.objc_metadata == nullptr) {
  141. return;
  142. }
  143. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  144. Type *t = base_type(e->type);
  145. GB_ASSERT(t->kind == Type_Struct);
  146. if (is_type) {
  147. for (auto const &entry : objc_metadata->type_entries) {
  148. string_set_add(set, entry.name);
  149. }
  150. } else {
  151. for (auto const &entry : objc_metadata->value_entries) {
  152. string_set_add(set, entry.name);
  153. }
  154. }
  155. for (Entity *f : t->Struct.fields) {
  156. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  157. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  158. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  159. }
  160. }
  161. }
  162. }
  163. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  164. if (build_context.terse_errors) { return; }
  165. ERROR_BLOCK();
  166. GB_ASSERT(e->kind == Entity_TypeName);
  167. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  168. auto *objc_metadata = e->TypeName.objc_metadata;
  169. MUTEX_GUARD(objc_metadata->mutex);
  170. StringSet set = {};
  171. defer (string_set_destroy(&set));
  172. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  173. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  174. defer (did_you_mean_destroy(&d));
  175. for (String const &target : set) {
  176. did_you_mean_append(&d, target);
  177. }
  178. check_did_you_mean_print(&d, prefix);
  179. }
  180. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  181. if (build_context.terse_errors) { return; }
  182. ERROR_BLOCK();
  183. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  184. defer (did_you_mean_destroy(&d));
  185. for (Entity *e : fields) {
  186. did_you_mean_append(&d, e->token.string);
  187. }
  188. check_did_you_mean_print(&d, prefix);
  189. }
  190. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  191. if (build_context.terse_errors) { return; }
  192. ERROR_BLOCK();
  193. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  194. defer (did_you_mean_destroy(&d));
  195. for (Entity *e : fields) {
  196. did_you_mean_append(&d, e->token.string);
  197. }
  198. check_did_you_mean_print(&d, prefix);
  199. }
  200. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  201. if (build_context.terse_errors) { return; }
  202. ERROR_BLOCK();
  203. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  204. defer (did_you_mean_destroy(&d));
  205. rw_mutex_shared_lock(&scope->mutex);
  206. for (auto const &entry : scope->elements) {
  207. Entity *e = entry.value;
  208. did_you_mean_append(&d, e->token.string);
  209. }
  210. rw_mutex_shared_unlock(&scope->mutex);
  211. check_did_you_mean_print(&d, prefix);
  212. }
  213. gb_internal Entity *entity_from_expr(Ast *expr) {
  214. expr = unparen_expr(expr);
  215. switch (expr->kind) {
  216. case Ast_Ident:
  217. return expr->Ident.entity;
  218. case Ast_SelectorExpr:
  219. return entity_from_expr(expr->SelectorExpr.selector);
  220. }
  221. return nullptr;
  222. }
  223. gb_internal void error_operand_not_expression(Operand *o) {
  224. if (o->mode == Addressing_Type) {
  225. gbString err = expr_to_string(o->expr);
  226. error(o->expr, "'%s' is not an expression but a type", err);
  227. gb_string_free(err);
  228. o->mode = Addressing_Invalid;
  229. }
  230. }
  231. gb_internal void error_operand_no_value(Operand *o) {
  232. if (o->mode == Addressing_NoValue) {
  233. gbString err = expr_to_string(o->expr);
  234. Ast *x = unparen_expr(o->expr);
  235. if (x->kind == Ast_CallExpr) {
  236. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  237. } else {
  238. error(o->expr, "'%s' used as a value", err);
  239. }
  240. gb_string_free(err);
  241. o->mode = Addressing_Invalid;
  242. }
  243. }
  244. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  245. if (build_context.dynamic_map_calls) {
  246. add_package_dependency(c, "runtime", "__dynamic_map_get");
  247. } else {
  248. add_package_dependency(c, "runtime", "map_desired_position");
  249. add_package_dependency(c, "runtime", "map_probe_distance");
  250. }
  251. }
  252. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  253. init_core_source_code_location(c->checker);
  254. if (t_map_set_proc == nullptr) {
  255. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  256. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  257. }
  258. if (build_context.dynamic_map_calls) {
  259. add_package_dependency(c, "runtime", "__dynamic_map_set");
  260. } else {
  261. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  262. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  263. }
  264. }
  265. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  266. init_core_source_code_location(c->checker);
  267. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  268. }
  269. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  270. Scope *s = c->scope;
  271. check_collect_entities(c, nodes);
  272. for (auto const &entry : s->elements) {
  273. Entity *e = entry.value;
  274. switch (e->kind) {
  275. case Entity_Constant:
  276. case Entity_TypeName:
  277. case Entity_Procedure:
  278. break;
  279. default:
  280. continue;
  281. }
  282. DeclInfo *d = decl_info_of_entity(e);
  283. if (d != nullptr) {
  284. check_entity_decl(c, e, d, nullptr);
  285. }
  286. }
  287. }
  288. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  289. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  290. ///////////////////////////////////////////////////////////////////////////////
  291. // //
  292. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  293. // //
  294. ///////////////////////////////////////////////////////////////////////////////
  295. CheckerInfo *info = old_c->info;
  296. if (base_entity == nullptr) {
  297. return false;
  298. }
  299. if (!is_type_proc(base_entity->type)) {
  300. return false;
  301. }
  302. if (base_entity->flags & EntityFlag_Disabled) {
  303. return false;
  304. }
  305. String name = base_entity->token.string;
  306. Type *src = base_type(base_entity->type);
  307. Type *dst = nullptr;
  308. if (type != nullptr) {
  309. dst = base_type(type);
  310. }
  311. if (param_operands == nullptr) {
  312. GB_ASSERT(dst != nullptr);
  313. }
  314. if (param_operands != nullptr) {
  315. GB_ASSERT(dst == nullptr);
  316. }
  317. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  318. return false;
  319. }
  320. if (dst != nullptr) {
  321. if (dst->Proc.is_polymorphic) {
  322. return false;
  323. }
  324. if (dst->Proc.param_count != src->Proc.param_count ||
  325. dst->Proc.result_count != src->Proc.result_count) {
  326. return false;
  327. }
  328. }
  329. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  330. if (old_decl == nullptr) {
  331. return false;
  332. }
  333. gbAllocator a = heap_allocator();
  334. Array<Operand> operands = {};
  335. if (param_operands) {
  336. operands = *param_operands;
  337. } else {
  338. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  339. for (isize i = 0; i < dst->Proc.param_count; i++) {
  340. Entity *param = dst->Proc.params->Tuple.variables[i];
  341. Operand o = {Addressing_Value};
  342. o.type = param->type;
  343. array_add(&operands, o);
  344. }
  345. }
  346. defer (if (param_operands == nullptr) {
  347. array_free(&operands);
  348. });
  349. CheckerContext nctx = *old_c;
  350. Scope *scope = create_scope(info, base_entity->scope);
  351. scope->flags |= ScopeFlag_Proc;
  352. nctx.scope = scope;
  353. nctx.allow_polymorphic_types = true;
  354. if (nctx.polymorphic_scope == nullptr) {
  355. nctx.polymorphic_scope = scope;
  356. }
  357. auto *pt = &src->Proc;
  358. // NOTE(bill): This is slightly memory leaking if the type already exists
  359. // Maybe it's better to check with the previous types first?
  360. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  361. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  362. if (!success) {
  363. return false;
  364. }
  365. GenProcsData *gen_procs = nullptr;
  366. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  367. GB_ASSERT(base_entity->kind == Entity_Procedure);
  368. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  369. gen_procs = base_entity->Procedure.gen_procs;
  370. if (gen_procs) {
  371. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  372. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  373. for (Entity *other : gen_procs->procs) {
  374. Type *pt = base_type(other->type);
  375. if (are_types_identical(pt, final_proc_type)) {
  376. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  377. if (poly_proc_data) {
  378. poly_proc_data->gen_entity = other;
  379. }
  380. return true;
  381. }
  382. }
  383. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  384. } else {
  385. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  386. gen_procs->procs.allocator = heap_allocator();
  387. base_entity->Procedure.gen_procs = gen_procs;
  388. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  389. }
  390. {
  391. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  392. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  393. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  394. nctx.no_polymorphic_errors = false;
  395. // NOTE(bill): Reset scope from the failed procedure type
  396. scope_reset(scope);
  397. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  398. Ast *cloned_proc_type_node = clone_ast(pt->node);
  399. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  400. if (!success) {
  401. return false;
  402. }
  403. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  404. for (Entity *other : gen_procs->procs) {
  405. Type *pt = base_type(other->type);
  406. if (are_types_identical(pt, final_proc_type)) {
  407. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  408. if (poly_proc_data) {
  409. poly_proc_data->gen_entity = other;
  410. }
  411. DeclInfo *decl = other->decl_info;
  412. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  413. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  414. proc_info->file = other->file;
  415. proc_info->token = other->token;
  416. proc_info->decl = decl;
  417. proc_info->type = other->type;
  418. proc_info->body = decl->proc_lit->ProcLit.body;
  419. proc_info->tags = other->Procedure.tags;;
  420. proc_info->generated_from_polymorphic = true;
  421. proc_info->poly_def_node = poly_def_node;
  422. check_procedure_later(nctx.checker, proc_info);
  423. }
  424. return true;
  425. }
  426. }
  427. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  428. }
  429. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  430. ast_node(pl, ProcLit, proc_lit);
  431. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  432. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  433. final_proc_type->Proc.is_poly_specialized = true;
  434. final_proc_type->Proc.is_polymorphic = true;
  435. final_proc_type->Proc.variadic = src->Proc.variadic;
  436. final_proc_type->Proc.require_results = src->Proc.require_results;
  437. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  438. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  439. final_proc_type->Proc.diverging = src->Proc.diverging;
  440. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  441. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  442. for (isize i = 0; i < operands.count; i++) {
  443. Operand o = operands[i];
  444. if (final_proc_type == o.type ||
  445. base_entity->type == o.type) {
  446. // NOTE(bill): Cycle
  447. final_proc_type->Proc.is_poly_specialized = false;
  448. break;
  449. }
  450. }
  451. u64 tags = base_entity->Procedure.tags;
  452. Ast *ident = clone_ast(base_entity->identifier);
  453. Token token = ident->Ident.token;
  454. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  455. d->gen_proc_type = final_proc_type;
  456. d->type_expr = pl->type;
  457. d->proc_lit = proc_lit;
  458. d->proc_checked_state = ProcCheckedState_Unchecked;
  459. d->defer_use_checked = false;
  460. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  461. entity->identifier = ident;
  462. add_entity_and_decl_info(&nctx, ident, entity, d);
  463. // NOTE(bill): Set the scope afterwards as this is not real overloading
  464. entity->scope = scope->parent;
  465. entity->file = base_entity->file;
  466. entity->pkg = base_entity->pkg;
  467. entity->flags = 0;
  468. d->entity = entity;
  469. AstFile *file = nullptr;
  470. {
  471. Scope *s = entity->scope;
  472. while (s != nullptr && s->file == nullptr) {
  473. file = s->file;
  474. s = s->parent;
  475. }
  476. }
  477. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  478. array_add(&gen_procs->procs, entity);
  479. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  480. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  481. proc_info->file = file;
  482. proc_info->token = token;
  483. proc_info->decl = d;
  484. proc_info->type = final_proc_type;
  485. proc_info->body = pl->body;
  486. proc_info->tags = tags;
  487. proc_info->generated_from_polymorphic = true;
  488. proc_info->poly_def_node = poly_def_node;
  489. if (poly_proc_data) {
  490. poly_proc_data->gen_entity = entity;
  491. poly_proc_data->proc_info = proc_info;
  492. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  493. }
  494. // NOTE(bill): Check the newly generated procedure body
  495. check_procedure_later(nctx.checker, proc_info);
  496. return true;
  497. }
  498. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  499. if (operand->expr == nullptr) return false;
  500. Entity *base_entity = entity_of_node(operand->expr);
  501. if (base_entity == nullptr) return false;
  502. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  503. }
  504. gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> const *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  505. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  506. }
  507. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  508. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  509. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  510. #define MAXIMUM_TYPE_DISTANCE 10
  511. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  512. if (c == nullptr) {
  513. GB_ASSERT(operand->mode == Addressing_Value);
  514. GB_ASSERT(is_type_typed(operand->type));
  515. }
  516. if (operand->mode == Addressing_Invalid ||
  517. type == t_invalid) {
  518. return -1;
  519. }
  520. if (operand->mode == Addressing_Builtin) {
  521. return -1;
  522. }
  523. if (operand->mode == Addressing_Type) {
  524. if (is_type_typeid(type)) {
  525. if (is_type_polymorphic(operand->type)) {
  526. return -1;
  527. }
  528. add_type_info_type(c, operand->type);
  529. return 4;
  530. }
  531. return -1;
  532. }
  533. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  534. return -1;
  535. }
  536. Type *s = operand->type;
  537. if (are_types_identical(s, type)) {
  538. return 0;
  539. }
  540. Type *src = base_type(s);
  541. Type *dst = base_type(type);
  542. if (is_type_untyped_uninit(src)) {
  543. return 1;
  544. }
  545. if (is_type_untyped_nil(src)) {
  546. if (type_has_nil(dst)) {
  547. return 1;
  548. }
  549. return -1;
  550. }
  551. if (is_type_untyped(src)) {
  552. if (is_type_any(dst)) {
  553. // NOTE(bill): Anything can cast to 'Any'
  554. add_type_info_type(c, s);
  555. return MAXIMUM_TYPE_DISTANCE;
  556. }
  557. if (dst->kind == Type_Basic) {
  558. if (operand->mode == Addressing_Constant) {
  559. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  560. if (is_type_typed(dst) && src->kind == Type_Basic) {
  561. switch (src->Basic.kind) {
  562. case Basic_UntypedBool:
  563. if (is_type_boolean(dst)) {
  564. return 1;
  565. }
  566. break;
  567. case Basic_UntypedRune:
  568. if (is_type_integer(dst) || is_type_rune(dst)) {
  569. return 1;
  570. }
  571. break;
  572. case Basic_UntypedInteger:
  573. if (is_type_integer(dst) || is_type_rune(dst)) {
  574. return 1;
  575. }
  576. break;
  577. case Basic_UntypedString:
  578. if (is_type_string(dst)) {
  579. return 1;
  580. }
  581. break;
  582. case Basic_UntypedFloat:
  583. if (is_type_float(dst)) {
  584. return 1;
  585. }
  586. break;
  587. case Basic_UntypedComplex:
  588. if (is_type_complex(dst)) {
  589. return 1;
  590. }
  591. if (is_type_quaternion(dst)) {
  592. return 2;
  593. }
  594. break;
  595. case Basic_UntypedQuaternion:
  596. if (is_type_quaternion(dst)) {
  597. return 1;
  598. }
  599. break;
  600. }
  601. }
  602. return 2;
  603. }
  604. return -1;
  605. }
  606. if (src->kind == Type_Basic) {
  607. Type *d = base_array_type(dst);
  608. i64 score = -1;
  609. switch (src->Basic.kind) {
  610. case Basic_UntypedBool:
  611. if (is_type_boolean(d)) {
  612. score = 1;
  613. }
  614. break;
  615. case Basic_UntypedRune:
  616. if (is_type_integer(d) || is_type_rune(d)) {
  617. score = 1;
  618. }
  619. break;
  620. case Basic_UntypedInteger:
  621. if (is_type_integer(d) || is_type_rune(d)) {
  622. score = 1;
  623. }
  624. break;
  625. case Basic_UntypedString:
  626. if (is_type_string(d)) {
  627. score = 1;
  628. }
  629. break;
  630. case Basic_UntypedFloat:
  631. if (is_type_float(d)) {
  632. score = 1;
  633. }
  634. break;
  635. case Basic_UntypedComplex:
  636. if (is_type_complex(d)) {
  637. score = 1;
  638. }
  639. if (is_type_quaternion(d)) {
  640. score = 2;
  641. }
  642. break;
  643. case Basic_UntypedQuaternion:
  644. if (is_type_quaternion(d)) {
  645. score = 1;
  646. }
  647. break;
  648. }
  649. if (score > 0) {
  650. if (is_type_typed(d)) {
  651. score += 1;
  652. }
  653. if (d != dst) {
  654. score += 6;
  655. }
  656. }
  657. return score;
  658. }
  659. }
  660. }
  661. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  662. if (c->in_enum_type) {
  663. return 3;
  664. }
  665. }
  666. {
  667. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  668. if (subtype_level > 0) {
  669. return 4 + subtype_level;
  670. }
  671. }
  672. // rawptr <- ^T
  673. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  674. return 5;
  675. }
  676. // rawptr <- [^]T
  677. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  678. return 5;
  679. }
  680. // ^T <- [^]T
  681. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  682. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  683. return 4;
  684. }
  685. }
  686. // [^]T <- ^T
  687. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  688. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  689. return 4;
  690. }
  691. }
  692. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  693. bool modify_type = !c->no_polymorphic_errors;
  694. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  695. return 2;
  696. }
  697. }
  698. if (is_type_union(dst)) {
  699. for (Type *vt : dst->Union.variants) {
  700. if (are_types_identical(vt, s)) {
  701. return 1;
  702. }
  703. }
  704. if (dst->Union.variants.count == 1) {
  705. Type *vt = dst->Union.variants[0];
  706. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  707. if (score >= 0) {
  708. return score+2;
  709. }
  710. } else if (is_type_untyped(src)) {
  711. i64 prev_lowest_score = -1;
  712. i64 lowest_score = -1;
  713. for (Type *vt : dst->Union.variants) {
  714. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  715. if (score >= 0) {
  716. if (lowest_score < 0) {
  717. lowest_score = score;
  718. } else {
  719. if (prev_lowest_score < 0) {
  720. prev_lowest_score = lowest_score;
  721. } else {
  722. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  723. }
  724. lowest_score = gb_min(lowest_score, score);
  725. }
  726. }
  727. }
  728. if (lowest_score >= 0) {
  729. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  730. return lowest_score+2;
  731. }
  732. }
  733. }
  734. }
  735. if (is_type_relative_pointer(dst)) {
  736. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type, allow_array_programming);
  737. if (score >= 0) {
  738. return score+2;
  739. }
  740. }
  741. if (is_type_relative_multi_pointer(dst)) {
  742. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type, allow_array_programming);
  743. if (score >= 0) {
  744. return score+2;
  745. }
  746. }
  747. if (is_type_proc(dst)) {
  748. if (are_types_identical(src, dst)) {
  749. return 3;
  750. }
  751. PolyProcData poly_proc_data = {};
  752. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  753. Entity *e = poly_proc_data.gen_entity;
  754. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  755. add_entity_use(c, operand->expr, e);
  756. return 4;
  757. }
  758. }
  759. if (is_type_complex_or_quaternion(dst)) {
  760. Type *elem = base_complex_elem_type(dst);
  761. if (are_types_identical(elem, base_type(src))) {
  762. return 5;
  763. }
  764. }
  765. if (allow_array_programming) {
  766. if (is_type_array(dst)) {
  767. Type *elem = base_array_type(dst);
  768. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  769. if (distance >= 0) {
  770. return distance + 6;
  771. }
  772. }
  773. if (is_type_simd_vector(dst)) {
  774. Type *dst_elem = base_array_type(dst);
  775. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  776. if (distance >= 0) {
  777. return distance + 6;
  778. }
  779. }
  780. }
  781. if (is_type_matrix(dst)) {
  782. if (are_types_identical(src, dst)) {
  783. return 5;
  784. }
  785. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  786. Type *dst_elem = base_array_type(dst);
  787. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  788. if (distance >= 0) {
  789. return distance + 7;
  790. }
  791. }
  792. }
  793. if (is_type_any(dst)) {
  794. if (!is_type_polymorphic(src)) {
  795. if (operand->mode == Addressing_Context && operand->type == t_context) {
  796. return -1;
  797. } else {
  798. // NOTE(bill): Anything can cast to 'Any'
  799. add_type_info_type(c, s);
  800. return MAXIMUM_TYPE_DISTANCE;
  801. }
  802. }
  803. }
  804. Ast *expr = unparen_expr(operand->expr);
  805. if (expr != nullptr) {
  806. if (expr->kind == Ast_AutoCast) {
  807. Operand x = *operand;
  808. x.expr = expr->AutoCast.expr;
  809. if (check_cast_internal(c, &x, type)) {
  810. return MAXIMUM_TYPE_DISTANCE;
  811. }
  812. }
  813. }
  814. return -1;
  815. }
  816. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  817. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  818. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  819. // TODO(bill): A decent score function
  820. i64 d = distance*distance; // x^2
  821. if (is_variadic && d >= 0) {
  822. d += distance + 1; // x^2 + x + 1
  823. }
  824. return gb_max(c - d, 0);
  825. }
  826. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false, bool allow_array_programming=true) {
  827. i64 score = 0;
  828. i64 distance = check_distance_between_types(c, operand, type, allow_array_programming);
  829. bool ok = distance >= 0;
  830. if (ok) {
  831. score = assign_score_function(distance, is_variadic);
  832. }
  833. if (score_) *score_ = score;
  834. return ok;
  835. }
  836. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  837. i64 score = 0;
  838. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  839. }
  840. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  841. Operand x = {};
  842. x.type = src;
  843. x.mode = Addressing_Value;
  844. return check_is_assignable_to(nullptr, &x, dst);
  845. }
  846. gb_internal AstPackage *get_package_of_type(Type *type) {
  847. for (;;) {
  848. if (type == nullptr) {
  849. return nullptr;
  850. }
  851. switch (type->kind) {
  852. case Type_Basic:
  853. return builtin_pkg;
  854. case Type_Named:
  855. if (type->Named.type_name != nullptr) {
  856. return type->Named.type_name->pkg;
  857. }
  858. return nullptr;
  859. case Type_Pointer:
  860. type = type->Pointer.elem;
  861. continue;
  862. case Type_Array:
  863. type = type->Array.elem;
  864. continue;
  865. case Type_Slice:
  866. type = type->Slice.elem;
  867. continue;
  868. case Type_DynamicArray:
  869. type = type->DynamicArray.elem;
  870. continue;
  871. case Type_RelativePointer:
  872. type = type->RelativePointer.pointer_type;
  873. continue;
  874. case Type_RelativeMultiPointer:
  875. type = type->RelativeMultiPointer.pointer_type;
  876. continue;
  877. }
  878. return nullptr;
  879. }
  880. }
  881. // NOTE(bill): 'content_name' is for debugging and error messages
  882. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  883. check_not_tuple(c, operand);
  884. if (operand->mode == Addressing_Invalid) {
  885. return;
  886. }
  887. if (is_type_untyped(operand->type)) {
  888. Type *target_type = type;
  889. if (type == nullptr || is_type_any(type)) {
  890. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  891. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  892. operand->mode = Addressing_Invalid;
  893. return;
  894. }
  895. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  896. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  897. operand->mode = Addressing_Invalid;
  898. return;
  899. }
  900. target_type = default_type(operand->type);
  901. if (type != nullptr && !is_type_any(type)) {
  902. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  903. }
  904. add_type_info_type(c, type);
  905. add_type_info_type(c, target_type);
  906. }
  907. convert_to_typed(c, operand, target_type);
  908. if (operand->mode == Addressing_Invalid) {
  909. return;
  910. }
  911. }
  912. if (type == nullptr) {
  913. return;
  914. }
  915. if (operand->mode == Addressing_ProcGroup) {
  916. bool good = false;
  917. if (type != nullptr && is_type_proc(type)) {
  918. Array<Entity *> procs = proc_group_entities(c, *operand);
  919. // NOTE(bill): These should be done
  920. for (Entity *e : procs) {
  921. Type *t = base_type(e->type);
  922. if (t == t_invalid) {
  923. continue;
  924. }
  925. Operand x = {};
  926. x.mode = Addressing_Value;
  927. x.type = t;
  928. if (check_is_assignable_to(c, &x, type)) {
  929. add_entity_use(c, operand->expr, e);
  930. good = true;
  931. break;
  932. }
  933. }
  934. }
  935. if (!good) {
  936. gbString expr_str = expr_to_string(operand->expr);
  937. gbString op_type_str = type_to_string(operand->type);
  938. gbString type_str = type_to_string(type);
  939. defer (gb_string_free(type_str));
  940. defer (gb_string_free(op_type_str));
  941. defer (gb_string_free(expr_str));
  942. // TODO(bill): is this a good enough error message?
  943. error(operand->expr,
  944. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  945. expr_str,
  946. op_type_str,
  947. LIT(context_name));
  948. operand->mode = Addressing_Invalid;
  949. }
  950. convert_to_typed(c, operand, type);
  951. return;
  952. }
  953. if (check_is_assignable_to(c, operand, type)) {
  954. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  955. add_type_info_type(c, operand->type);
  956. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  957. }
  958. } else {
  959. gbString expr_str = expr_to_string(operand->expr);
  960. gbString op_type_str = type_to_string(operand->type);
  961. gbString type_str = type_to_string(type);
  962. defer (gb_string_free(type_str));
  963. defer (gb_string_free(op_type_str));
  964. defer (gb_string_free(expr_str));
  965. switch (operand->mode) {
  966. case Addressing_Builtin:
  967. error(operand->expr,
  968. "Cannot assign built-in procedure '%s' in %.*s",
  969. expr_str,
  970. LIT(context_name));
  971. break;
  972. case Addressing_Type:
  973. if (is_type_polymorphic(operand->type)) {
  974. error(operand->expr,
  975. "Cannot assign '%s' which is a polymorphic type in %.*s",
  976. op_type_str,
  977. LIT(context_name));
  978. } else {
  979. error(operand->expr,
  980. "Cannot assign '%s' which is a type in %.*s",
  981. op_type_str,
  982. LIT(context_name));
  983. }
  984. break;
  985. default:
  986. // TODO(bill): is this a good enough error message?
  987. {
  988. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  989. gbString type_extra = gb_string_make(heap_allocator(), "");
  990. defer (gb_string_free(op_type_extra));
  991. defer (gb_string_free(type_extra));
  992. isize on = gb_string_length(op_type_str);
  993. isize tn = gb_string_length(type_str);
  994. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  995. AstPackage *op_pkg = get_package_of_type(operand->type);
  996. AstPackage *type_pkg = get_package_of_type(type);
  997. if (op_pkg != nullptr) {
  998. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  999. }
  1000. if (type_pkg != nullptr) {
  1001. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1002. }
  1003. }
  1004. ERROR_BLOCK();
  1005. error(operand->expr,
  1006. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  1007. expr_str,
  1008. op_type_str, op_type_extra,
  1009. type_str, type_extra,
  1010. LIT(context_name));
  1011. check_assignment_error_suggestion(c, operand, type);
  1012. Type *src = base_type(operand->type);
  1013. Type *dst = base_type(type);
  1014. if (context_name == "procedure argument") {
  1015. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1016. gbString a = expr_to_string(operand->expr);
  1017. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1018. gb_string_free(a);
  1019. }
  1020. }
  1021. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1022. Type *x = src;
  1023. Type *y = dst;
  1024. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1025. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1026. if (same_inputs && same_outputs &&
  1027. x->Proc.calling_convention != y->Proc.calling_convention) {
  1028. gbString s_expected = type_to_string(y);
  1029. gbString s_got = type_to_string(x);
  1030. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1031. error_line("\t Expected \"%s\", got \"%s\"\n",
  1032. proc_calling_convention_strings[y->Proc.calling_convention],
  1033. proc_calling_convention_strings[x->Proc.calling_convention]);
  1034. error_line("\t Expected: %s\n", s_expected);
  1035. error_line("\t Got: %s\n", s_got);
  1036. gb_string_free(s_got);
  1037. gb_string_free(s_expected);
  1038. } else if (same_inputs && !same_outputs) {
  1039. gbString s_expected = type_to_string(y->Proc.results);
  1040. gbString s_got = type_to_string(x->Proc.results);
  1041. error_line("\tNote: The return types differ between the procedure signature types\n");
  1042. error_line("\t Expected: %s\n", s_expected);
  1043. error_line("\t Got: %s\n", s_got);
  1044. gb_string_free(s_got);
  1045. gb_string_free(s_expected);
  1046. } else if (!same_inputs && same_outputs) {
  1047. gbString s_expected = type_to_string(y->Proc.params);
  1048. gbString s_got = type_to_string(x->Proc.params);
  1049. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1050. error_line("\t Expected: %s\n", s_expected);
  1051. error_line("\t Got: %s\n", s_got);
  1052. gb_string_free(s_got);
  1053. gb_string_free(s_expected);
  1054. } else {
  1055. gbString s_expected = type_to_string(y);
  1056. gbString s_got = type_to_string(x);
  1057. error_line("\tNote: The signature type do not match whatsoever\n");
  1058. error_line("\t Expected: %s\n", s_expected);
  1059. error_line("\t Got: %s\n", s_got);
  1060. gb_string_free(s_got);
  1061. gb_string_free(s_expected);
  1062. }
  1063. }
  1064. }
  1065. break;
  1066. }
  1067. operand->mode = Addressing_Invalid;
  1068. return;
  1069. }
  1070. }
  1071. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1072. Type *gt = *gt_;
  1073. GB_ASSERT(gt->kind == Type_Generic);
  1074. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1075. GB_ASSERT(e != nullptr);
  1076. if (e->kind == Entity_TypeName) {
  1077. *gt_ = nullptr;
  1078. *dst_count = source_count;
  1079. e->kind = Entity_Constant;
  1080. e->Constant.value = exact_value_i64(source_count);
  1081. e->type = t_untyped_integer;
  1082. return true;
  1083. } else if (e->kind == Entity_Constant) {
  1084. *gt_ = nullptr;
  1085. if (e->Constant.value.kind != ExactValue_Integer) {
  1086. return false;
  1087. }
  1088. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1089. if (count != source_count) {
  1090. return false;
  1091. }
  1092. *dst_count = source_count;
  1093. return true;
  1094. }
  1095. return false;
  1096. }
  1097. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1098. Operand o = {Addressing_Value};
  1099. o.type = source;
  1100. switch (poly->kind) {
  1101. case Type_Basic:
  1102. if (compound) return are_types_identical(poly, source);
  1103. return check_is_assignable_to(c, &o, poly);
  1104. case Type_Named: {
  1105. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1106. return true;
  1107. }
  1108. if (compound || !is_type_generic(poly)) {
  1109. return are_types_identical(poly, source);
  1110. }
  1111. return check_is_assignable_to(c, &o, poly);
  1112. }
  1113. case Type_Generic: {
  1114. if (poly->Generic.specialized != nullptr) {
  1115. Type *s = poly->Generic.specialized;
  1116. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1117. return false;
  1118. }
  1119. }
  1120. if (modify_type) {
  1121. Type *ds = default_type(source);
  1122. gb_memmove(poly, ds, gb_size_of(Type));
  1123. }
  1124. return true;
  1125. }
  1126. case Type_Pointer:
  1127. if (source->kind == Type_Pointer) {
  1128. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1129. if (level > 0) {
  1130. return true;
  1131. }
  1132. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1133. } else if (source->kind == Type_MultiPointer) {
  1134. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1135. if (level > 0) {
  1136. return true;
  1137. }
  1138. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1139. }
  1140. return false;
  1141. case Type_MultiPointer:
  1142. if (source->kind == Type_MultiPointer) {
  1143. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1144. if (level > 0) {
  1145. return true;
  1146. }
  1147. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1148. } else if (source->kind == Type_Pointer) {
  1149. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1150. if (level > 0) {
  1151. return true;
  1152. }
  1153. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1154. }
  1155. return false;
  1156. case Type_Array:
  1157. if (source->kind == Type_Array) {
  1158. if (poly->Array.generic_count != nullptr) {
  1159. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1160. return false;
  1161. }
  1162. }
  1163. if (poly->Array.count == source->Array.count) {
  1164. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1165. }
  1166. } else if (source->kind == Type_EnumeratedArray) {
  1167. if (poly->Array.generic_count != nullptr) {
  1168. Type *gt = poly->Array.generic_count;
  1169. GB_ASSERT(gt->kind == Type_Generic);
  1170. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1171. GB_ASSERT(e != nullptr);
  1172. if (e->kind == Entity_TypeName) {
  1173. Type *index = source->EnumeratedArray.index;
  1174. Type *it = base_type(index);
  1175. if (it->kind != Type_Enum) {
  1176. return false;
  1177. }
  1178. poly->kind = Type_EnumeratedArray;
  1179. poly->cached_size = -1;
  1180. poly->cached_align = -1;
  1181. poly->flags.exchange(source->flags);
  1182. poly->failure = false;
  1183. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1184. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1185. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1186. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1187. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1188. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1189. e->kind = Entity_TypeName;
  1190. e->TypeName.is_type_alias = true;
  1191. e->type = index;
  1192. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1193. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1194. }
  1195. }
  1196. }
  1197. }
  1198. return false;
  1199. case Type_EnumeratedArray:
  1200. if (source->kind == Type_EnumeratedArray) {
  1201. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1202. return false;
  1203. }
  1204. if (poly->EnumeratedArray.op) {
  1205. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1206. return false;
  1207. }
  1208. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1209. return false;
  1210. }
  1211. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1212. return false;
  1213. }
  1214. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1215. }
  1216. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1217. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1218. return index || elem;
  1219. }
  1220. return false;
  1221. case Type_DynamicArray:
  1222. if (source->kind == Type_DynamicArray) {
  1223. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1224. }
  1225. return false;
  1226. case Type_Slice:
  1227. if (source->kind == Type_Slice) {
  1228. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1229. }
  1230. return false;
  1231. case Type_Enum:
  1232. return false;
  1233. case Type_BitSet:
  1234. if (source->kind == Type_BitSet) {
  1235. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1236. return false;
  1237. }
  1238. if (poly->BitSet.underlying == nullptr) {
  1239. if (modify_type) {
  1240. poly->BitSet.underlying = source->BitSet.underlying;
  1241. }
  1242. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1243. return false;
  1244. }
  1245. return true;
  1246. }
  1247. return false;
  1248. case Type_Union:
  1249. if (source->kind == Type_Union) {
  1250. TypeUnion *x = &poly->Union;
  1251. TypeUnion *y = &source->Union;
  1252. if (x->variants.count != y->variants.count) {
  1253. return false;
  1254. }
  1255. for_array(i, x->variants) {
  1256. Type *a = x->variants[i];
  1257. Type *b = y->variants[i];
  1258. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1259. if (!ok) return false;
  1260. }
  1261. return true;
  1262. }
  1263. return false;
  1264. case Type_Struct:
  1265. if (source->kind == Type_Struct) {
  1266. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1267. poly->Struct.soa_kind != StructSoa_None) {
  1268. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1269. if (ok) switch (source->Struct.soa_kind) {
  1270. case StructSoa_None:
  1271. default:
  1272. GB_PANIC("Unhandled SOA Kind");
  1273. break;
  1274. case StructSoa_Fixed:
  1275. if (modify_type) {
  1276. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1277. gb_memmove(poly, type, gb_size_of(*type));
  1278. }
  1279. break;
  1280. case StructSoa_Slice:
  1281. if (modify_type) {
  1282. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1283. gb_memmove(poly, type, gb_size_of(*type));
  1284. }
  1285. break;
  1286. case StructSoa_Dynamic:
  1287. if (modify_type) {
  1288. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1289. gb_memmove(poly, type, gb_size_of(*type));
  1290. }
  1291. break;
  1292. }
  1293. return ok;
  1294. }
  1295. // NOTE(bill): Check for subtypes of
  1296. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1297. }
  1298. return false;
  1299. case Type_BitField:
  1300. if (source->kind == Type_BitField) {
  1301. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1302. }
  1303. return false;
  1304. case Type_Tuple:
  1305. GB_PANIC("This should never happen");
  1306. return false;
  1307. case Type_Proc:
  1308. if (source->kind == Type_Proc) {
  1309. TypeProc *x = &poly->Proc;
  1310. TypeProc *y = &source->Proc;
  1311. if (x->calling_convention != y->calling_convention) {
  1312. return false;
  1313. }
  1314. if (x->c_vararg != y->c_vararg) {
  1315. return false;
  1316. }
  1317. if (x->variadic != y->variadic) {
  1318. return false;
  1319. }
  1320. if (x->param_count != y->param_count) {
  1321. return false;
  1322. }
  1323. if (x->result_count != y->result_count) {
  1324. return false;
  1325. }
  1326. for (isize i = 0; i < x->param_count; i++) {
  1327. Entity *a = x->params->Tuple.variables[i];
  1328. Entity *b = y->params->Tuple.variables[i];
  1329. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1330. if (!ok) return false;
  1331. }
  1332. for (isize i = 0; i < x->result_count; i++) {
  1333. Entity *a = x->results->Tuple.variables[i];
  1334. Entity *b = y->results->Tuple.variables[i];
  1335. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1336. if (!ok) return false;
  1337. }
  1338. return true;
  1339. }
  1340. return false;
  1341. case Type_Map:
  1342. if (source->kind == Type_Map) {
  1343. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1344. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1345. if (key || value) {
  1346. poly->Map.lookup_result_type = nullptr;
  1347. init_map_internal_types(poly);
  1348. return true;
  1349. }
  1350. }
  1351. return false;
  1352. case Type_Matrix:
  1353. if (source->kind == Type_Matrix) {
  1354. if (poly->Matrix.generic_row_count != nullptr) {
  1355. poly->Matrix.stride_in_bytes = 0;
  1356. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1357. return false;
  1358. }
  1359. }
  1360. if (poly->Matrix.generic_column_count != nullptr) {
  1361. poly->Matrix.stride_in_bytes = 0;
  1362. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1363. return false;
  1364. }
  1365. }
  1366. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1367. poly->Matrix.column_count == source->Matrix.column_count) {
  1368. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1369. }
  1370. }
  1371. return false;
  1372. case Type_SimdVector:
  1373. if (source->kind == Type_SimdVector) {
  1374. if (poly->SimdVector.generic_count != nullptr) {
  1375. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1376. return false;
  1377. }
  1378. }
  1379. if (poly->SimdVector.count == source->SimdVector.count) {
  1380. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1381. }
  1382. }
  1383. return false;
  1384. }
  1385. return false;
  1386. }
  1387. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1388. if (curr->state != EntityState_InProgress) {
  1389. return false;
  1390. }
  1391. for_array(i, *c->type_path) {
  1392. Entity *prev = c->type_path->data[i];
  1393. if (prev == curr) {
  1394. if (report) {
  1395. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1396. for (isize j = i; j < c->type_path->count; j++) {
  1397. Entity *curr = (*c->type_path)[j];
  1398. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1399. }
  1400. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1401. curr->type = t_invalid;
  1402. }
  1403. return true;
  1404. }
  1405. }
  1406. return false;
  1407. }
  1408. struct CIdentSuggestion {
  1409. String name;
  1410. String msg;
  1411. };
  1412. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1413. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1414. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1415. {str_lit("sizeof"), str_lit("'size_of'?")},
  1416. {str_lit("alignof"), str_lit("'align_of'?")},
  1417. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1418. {str_lit("_Bool"), str_lit("'bool'?")},
  1419. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1420. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1421. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1422. {str_lit("float"), str_lit("'f32'?")},
  1423. {str_lit("double"), str_lit("'f64'?")},
  1424. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1425. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1426. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1427. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1428. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1429. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1430. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1431. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1432. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1433. {str_lit("uint8_t"), str_lit("'u8'?")},
  1434. {str_lit("int8_t"), str_lit("'i8'?")},
  1435. {str_lit("uint16_t"), str_lit("'u16'?")},
  1436. {str_lit("int16_t"), str_lit("'i16'?")},
  1437. {str_lit("uint32_t"), str_lit("'u32'?")},
  1438. {str_lit("int32_t"), str_lit("'i32'?")},
  1439. {str_lit("uint64_t"), str_lit("'u64'?")},
  1440. {str_lit("int64_t"), str_lit("'i64'?")},
  1441. {str_lit("uint128_t"), str_lit("'u128'?")},
  1442. {str_lit("int128_t"), str_lit("'i128'?")},
  1443. {str_lit("float32"), str_lit("'f32'?")},
  1444. {str_lit("float64"), str_lit("'f64'?")},
  1445. {str_lit("float32_t"), str_lit("'f32'?")},
  1446. {str_lit("float64_t"), str_lit("'f64'?")},
  1447. };
  1448. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1449. GB_ASSERT(n->kind == Ast_Ident);
  1450. o->mode = Addressing_Invalid;
  1451. o->expr = n;
  1452. String name = n->Ident.token.string;
  1453. Entity *e = scope_lookup(c->scope, name);
  1454. if (e == nullptr) {
  1455. if (is_blank_ident(name)) {
  1456. error(n, "'_' cannot be used as a value");
  1457. } else {
  1458. ERROR_BLOCK();
  1459. error(n, "Undeclared name: %.*s", LIT(name));
  1460. // NOTE(bill): Loads of checks for C programmers
  1461. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1462. if (name == suggestion.name) {
  1463. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1464. }
  1465. }
  1466. }
  1467. o->type = t_invalid;
  1468. o->mode = Addressing_Invalid;
  1469. if (named_type != nullptr) {
  1470. set_base_type(named_type, t_invalid);
  1471. }
  1472. return nullptr;
  1473. }
  1474. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1475. if (e->parent_proc_decl != nullptr &&
  1476. e->parent_proc_decl != c->curr_proc_decl) {
  1477. if (e->kind == Entity_Variable) {
  1478. if ((e->flags & EntityFlag_Static) == 0) {
  1479. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1480. return nullptr;
  1481. }
  1482. } else if (e->kind == Entity_Label) {
  1483. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1484. return nullptr;
  1485. }
  1486. }
  1487. if (e->kind == Entity_ProcGroup) {
  1488. auto *pge = &e->ProcGroup;
  1489. DeclInfo *d = decl_info_of_entity(e);
  1490. check_entity_decl(c, e, d, nullptr);
  1491. Array<Entity *> procs = pge->entities;
  1492. bool skip = false;
  1493. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1494. // NOTE(bill): These should be done
  1495. for (Entity *proc : procs) {
  1496. Type *t = base_type(proc->type);
  1497. if (t == t_invalid) {
  1498. continue;
  1499. }
  1500. Operand x = {};
  1501. x.mode = Addressing_Value;
  1502. x.type = t;
  1503. if (check_is_assignable_to(c, &x, type_hint)) {
  1504. e = proc;
  1505. add_entity_use(c, n, e);
  1506. skip = true;
  1507. break;
  1508. }
  1509. }
  1510. }
  1511. if (!skip) {
  1512. o->mode = Addressing_ProcGroup;
  1513. o->type = t_invalid;
  1514. o->proc_group = e;
  1515. return nullptr;
  1516. }
  1517. }
  1518. add_entity_use(c, n, e);
  1519. if (e->state == EntityState_Unresolved) {
  1520. check_entity_decl(c, e, nullptr, named_type);
  1521. }
  1522. if (e->type == nullptr) {
  1523. // TODO(bill): Which is correct? return or compiler_error?
  1524. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1525. return nullptr;
  1526. }
  1527. e->flags |= EntityFlag_Used;
  1528. Type *type = e->type;
  1529. o->type = type;
  1530. switch (e->kind) {
  1531. case Entity_Constant:
  1532. if (type == t_invalid) {
  1533. o->type = t_invalid;
  1534. return e;
  1535. }
  1536. o->value = e->Constant.value;
  1537. if (o->value.kind == ExactValue_Invalid) {
  1538. return e;
  1539. }
  1540. if (o->value.kind == ExactValue_Procedure) {
  1541. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1542. if (proc != nullptr) {
  1543. o->mode = Addressing_Value;
  1544. o->type = proc->type;
  1545. return proc;
  1546. }
  1547. }
  1548. o->mode = Addressing_Constant;
  1549. break;
  1550. case Entity_Variable:
  1551. e->flags |= EntityFlag_Used;
  1552. if (type == t_invalid) {
  1553. o->type = t_invalid;
  1554. return e;
  1555. }
  1556. o->mode = Addressing_Variable;
  1557. if (e->flags & EntityFlag_Value) {
  1558. o->mode = Addressing_Value;
  1559. }
  1560. break;
  1561. case Entity_Procedure:
  1562. o->mode = Addressing_Value;
  1563. o->value = exact_value_procedure(n);
  1564. break;
  1565. case Entity_Builtin:
  1566. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1567. o->mode = Addressing_Builtin;
  1568. break;
  1569. case Entity_TypeName:
  1570. o->mode = Addressing_Type;
  1571. if (check_cycle(c, e, true)) {
  1572. o->type = t_invalid;
  1573. }
  1574. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1575. o->type = base_type(o->type);
  1576. }
  1577. break;
  1578. case Entity_ImportName:
  1579. if (!allow_import_name) {
  1580. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1581. }
  1582. return e;
  1583. case Entity_LibraryName:
  1584. if (!allow_import_name) {
  1585. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1586. }
  1587. return e;
  1588. case Entity_Label:
  1589. o->mode = Addressing_NoValue;
  1590. break;
  1591. case Entity_Nil:
  1592. o->mode = Addressing_Value;
  1593. break;
  1594. default:
  1595. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1596. break;
  1597. }
  1598. return e;
  1599. }
  1600. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1601. if (o->type == nullptr) {
  1602. gbString str = expr_to_string(o->expr);
  1603. error(o->expr, "Expression has no value '%s'", str);
  1604. gb_string_free(str);
  1605. return false;
  1606. }
  1607. if (o->mode == Addressing_Type) {
  1608. gbString str = type_to_string(o->type);
  1609. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1610. gb_string_free(str);
  1611. return false;
  1612. }
  1613. Type *type = base_type(core_array_type(o->type));
  1614. gbString str = nullptr;
  1615. switch (op.kind) {
  1616. case Token_Add:
  1617. case Token_Sub:
  1618. if (!is_type_numeric(type)) {
  1619. str = expr_to_string(o->expr);
  1620. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1621. gb_string_free(str);
  1622. }
  1623. break;
  1624. case Token_Xor:
  1625. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1626. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1627. }
  1628. break;
  1629. case Token_Not:
  1630. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1631. ERROR_BLOCK();
  1632. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1633. if (is_type_integer(type)) {
  1634. str = expr_to_string(o->expr);
  1635. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1636. error_line("\t\t'%s == 0'?\n", str);
  1637. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1638. gb_string_free(str);
  1639. }
  1640. } else {
  1641. o->type = t_untyped_bool;
  1642. }
  1643. break;
  1644. case Token_Mul:
  1645. {
  1646. ERROR_BLOCK();
  1647. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1648. if (is_type_pointer(o->type)) {
  1649. str = expr_to_string(o->expr);
  1650. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1651. o->type = type_deref(o->type);
  1652. } else if (is_type_multi_pointer(o->type)) {
  1653. str = expr_to_string(o->expr);
  1654. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1655. o->type = type_deref(o->type, true);
  1656. }
  1657. }
  1658. break;
  1659. default:
  1660. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1661. return false;
  1662. }
  1663. return true;
  1664. }
  1665. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1666. Type *main_type = o->type;
  1667. Type *type = base_type(core_array_type(main_type));
  1668. Type *ct = core_type(type);
  1669. switch (op.kind) {
  1670. case Token_Sub:
  1671. case Token_SubEq:
  1672. if (is_type_bit_set(type)) {
  1673. return true;
  1674. } else if (!is_type_numeric(type)) {
  1675. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1676. return false;
  1677. }
  1678. break;
  1679. case Token_Quo:
  1680. case Token_QuoEq:
  1681. if (is_type_matrix(main_type)) {
  1682. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1683. return false;
  1684. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1685. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1686. return false;
  1687. }
  1688. /*fallthrough*/
  1689. case Token_Mul:
  1690. case Token_MulEq:
  1691. case Token_AddEq:
  1692. if (is_type_bit_set(type)) {
  1693. return true;
  1694. } else if (!is_type_numeric(type)) {
  1695. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1696. return false;
  1697. }
  1698. break;
  1699. case Token_Add:
  1700. if (is_type_string(type)) {
  1701. if (o->mode == Addressing_Constant) {
  1702. return true;
  1703. }
  1704. error(op, "String concatenation is only allowed with constant strings");
  1705. return false;
  1706. } else if (is_type_bit_set(type)) {
  1707. return true;
  1708. } else if (!is_type_numeric(type)) {
  1709. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1710. return false;
  1711. }
  1712. break;
  1713. case Token_And:
  1714. case Token_Or:
  1715. case Token_AndEq:
  1716. case Token_OrEq:
  1717. case Token_Xor:
  1718. case Token_XorEq:
  1719. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1720. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1721. return false;
  1722. }
  1723. break;
  1724. case Token_Mod:
  1725. case Token_ModMod:
  1726. case Token_ModEq:
  1727. case Token_ModModEq:
  1728. if (is_type_matrix(main_type)) {
  1729. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1730. return false;
  1731. }
  1732. if (!is_type_integer(type)) {
  1733. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1734. return false;
  1735. } else if (is_type_simd_vector(main_type)) {
  1736. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1737. return false;
  1738. }
  1739. break;
  1740. case Token_AndNot:
  1741. case Token_AndNotEq:
  1742. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1743. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1744. return false;
  1745. }
  1746. break;
  1747. case Token_CmpAnd:
  1748. case Token_CmpOr:
  1749. case Token_CmpAndEq:
  1750. case Token_CmpOrEq:
  1751. if (!is_type_boolean(type)) {
  1752. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1753. return false;
  1754. }
  1755. break;
  1756. default:
  1757. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1758. return false;
  1759. }
  1760. return true;
  1761. }
  1762. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1763. if (in_value.kind == ExactValue_Invalid) {
  1764. // NOTE(bill): There's already been an error
  1765. return true;
  1766. }
  1767. type = core_type(type);
  1768. if (type == t_invalid) {
  1769. return false;
  1770. } else if (is_type_boolean(type)) {
  1771. return in_value.kind == ExactValue_Bool;
  1772. } else if (is_type_string(type)) {
  1773. return in_value.kind == ExactValue_String;
  1774. } else if (is_type_integer(type) || is_type_rune(type)) {
  1775. if (in_value.kind == ExactValue_Bool) {
  1776. return false;
  1777. }
  1778. ExactValue v = exact_value_to_integer(in_value);
  1779. if (v.kind != ExactValue_Integer) {
  1780. return false;
  1781. }
  1782. if (out_value) *out_value = v;
  1783. if (is_type_untyped(type)) {
  1784. return true;
  1785. }
  1786. BigInt i = v.value_integer;
  1787. i64 byte_size = type_size_of(type);
  1788. BigInt umax = {};
  1789. BigInt imin = {};
  1790. BigInt imax = {};
  1791. if (c->bit_field_bit_size > 0) {
  1792. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1793. big_int_from_u64(&umax, 1);
  1794. big_int_from_i64(&imin, 1);
  1795. big_int_from_i64(&imax, 1);
  1796. BigInt bu = {};
  1797. BigInt bi = {};
  1798. big_int_from_i64(&bu, bit_size);
  1799. big_int_from_i64(&bi, bit_size-1);
  1800. big_int_shl_eq(&umax, &bu);
  1801. mp_decr(&umax);
  1802. big_int_shl_eq(&imin, &bi);
  1803. big_int_neg(&imin, &imin);
  1804. big_int_shl_eq(&imax, &bi);
  1805. mp_decr(&imax);
  1806. } else {
  1807. if (byte_size < 16) {
  1808. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1809. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1810. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1811. } else {
  1812. big_int_from_u64(&umax, 1);
  1813. big_int_from_i64(&imin, 1);
  1814. big_int_from_i64(&imax, 1);
  1815. BigInt bi128 = {};
  1816. BigInt bi127 = {};
  1817. big_int_from_i64(&bi128, 128);
  1818. big_int_from_i64(&bi127, 127);
  1819. big_int_shl_eq(&umax, &bi128);
  1820. mp_decr(&umax);
  1821. big_int_shl_eq(&imin, &bi127);
  1822. big_int_neg(&imin, &imin);
  1823. big_int_shl_eq(&imax, &bi127);
  1824. mp_decr(&imax);
  1825. }
  1826. }
  1827. switch (type->Basic.kind) {
  1828. case Basic_rune:
  1829. case Basic_i8:
  1830. case Basic_i16:
  1831. case Basic_i32:
  1832. case Basic_i64:
  1833. case Basic_i128:
  1834. case Basic_int:
  1835. case Basic_i16le:
  1836. case Basic_i32le:
  1837. case Basic_i64le:
  1838. case Basic_i128le:
  1839. case Basic_i16be:
  1840. case Basic_i32be:
  1841. case Basic_i64be:
  1842. case Basic_i128be:
  1843. {
  1844. // return imin <= i && i <= imax;
  1845. int a = big_int_cmp(&imin, &i);
  1846. int b = big_int_cmp(&i, &imax);
  1847. return (a <= 0) && (b <= 0);
  1848. }
  1849. case Basic_u8:
  1850. case Basic_u16:
  1851. case Basic_u32:
  1852. case Basic_u64:
  1853. case Basic_u128:
  1854. case Basic_uint:
  1855. case Basic_uintptr:
  1856. case Basic_u16le:
  1857. case Basic_u32le:
  1858. case Basic_u64le:
  1859. case Basic_u128le:
  1860. case Basic_u16be:
  1861. case Basic_u32be:
  1862. case Basic_u64be:
  1863. case Basic_u128be:
  1864. {
  1865. // return 0ull <= i && i <= umax;
  1866. int b = big_int_cmp(&i, &umax);
  1867. return !i.sign && (b <= 0);
  1868. }
  1869. case Basic_UntypedInteger:
  1870. return true;
  1871. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1872. }
  1873. } else if (is_type_float(type)) {
  1874. ExactValue v = exact_value_to_float(in_value);
  1875. if (v.kind != ExactValue_Float) {
  1876. return false;
  1877. }
  1878. if (out_value) *out_value = v;
  1879. switch (type->Basic.kind) {
  1880. case Basic_f16:
  1881. case Basic_f32:
  1882. case Basic_f64:
  1883. return true;
  1884. case Basic_f16le:
  1885. case Basic_f16be:
  1886. case Basic_f32le:
  1887. case Basic_f32be:
  1888. case Basic_f64le:
  1889. case Basic_f64be:
  1890. return true;
  1891. case Basic_UntypedFloat:
  1892. return true;
  1893. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1894. }
  1895. } else if (is_type_complex(type)) {
  1896. ExactValue v = exact_value_to_complex(in_value);
  1897. if (v.kind != ExactValue_Complex) {
  1898. return false;
  1899. }
  1900. switch (type->Basic.kind) {
  1901. case Basic_complex32:
  1902. case Basic_complex64:
  1903. case Basic_complex128: {
  1904. ExactValue real = exact_value_real(v);
  1905. ExactValue imag = exact_value_imag(v);
  1906. if (real.kind != ExactValue_Invalid &&
  1907. imag.kind != ExactValue_Invalid) {
  1908. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1909. return true;
  1910. }
  1911. break;
  1912. }
  1913. case Basic_UntypedComplex:
  1914. return true;
  1915. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1916. }
  1917. return false;
  1918. } else if (is_type_quaternion(type)) {
  1919. ExactValue v = exact_value_to_quaternion(in_value);
  1920. if (v.kind != ExactValue_Quaternion) {
  1921. return false;
  1922. }
  1923. switch (type->Basic.kind) {
  1924. case Basic_quaternion64:
  1925. case Basic_quaternion128:
  1926. case Basic_quaternion256: {
  1927. ExactValue real = exact_value_real(v);
  1928. ExactValue imag = exact_value_imag(v);
  1929. ExactValue jmag = exact_value_jmag(v);
  1930. ExactValue kmag = exact_value_kmag(v);
  1931. if (real.kind != ExactValue_Invalid &&
  1932. imag.kind != ExactValue_Invalid) {
  1933. 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));
  1934. return true;
  1935. }
  1936. break;
  1937. }
  1938. case Basic_UntypedComplex:
  1939. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1940. return true;
  1941. case Basic_UntypedQuaternion:
  1942. return true;
  1943. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1944. }
  1945. return false;
  1946. } else if (is_type_pointer(type)) {
  1947. if (in_value.kind == ExactValue_Pointer) {
  1948. return true;
  1949. }
  1950. if (in_value.kind == ExactValue_Integer) {
  1951. return false;
  1952. // return true;
  1953. }
  1954. if (in_value.kind == ExactValue_String) {
  1955. return false;
  1956. }
  1957. if (out_value) *out_value = in_value;
  1958. } else if (is_type_bit_set(type)) {
  1959. if (in_value.kind == ExactValue_Integer) {
  1960. return true;
  1961. }
  1962. }
  1963. return false;
  1964. }
  1965. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  1966. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1967. gbString b = type_to_string(type);
  1968. defer (gb_string_free(b));
  1969. if (is_type_enum(o->type)) {
  1970. if (check_is_castable_to(c, o, type)) {
  1971. gbString ot = type_to_string(o->type);
  1972. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  1973. gb_string_free(ot);
  1974. }
  1975. return true;
  1976. }
  1977. i64 sz = type_size_of(type);
  1978. i64 bit_size = 8*sz;
  1979. bool size_changed = false;
  1980. if (max_bit_size > 0) {
  1981. size_changed = (bit_size != max_bit_size);
  1982. bit_size = gb_min(bit_size, max_bit_size);
  1983. }
  1984. BigInt *bi = &o->value.value_integer;
  1985. if (is_type_unsigned(type)) {
  1986. if (big_int_is_neg(bi)) {
  1987. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1988. } else {
  1989. BigInt one = big_int_make_u64(1);
  1990. BigInt max_size = big_int_make_u64(1);
  1991. BigInt bits = big_int_make_i64(bit_size);
  1992. big_int_shl_eq(&max_size, &bits);
  1993. big_int_sub_eq(&max_size, &one);
  1994. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1995. if (size_changed) {
  1996. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  1997. } else {
  1998. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1999. }
  2000. }
  2001. } else {
  2002. BigInt zero = big_int_make_u64(0);
  2003. BigInt one = big_int_make_u64(1);
  2004. BigInt max_size = big_int_make_u64(1);
  2005. BigInt bits = big_int_make_i64(bit_size - 1);
  2006. big_int_shl_eq(&max_size, &bits);
  2007. String max_size_str = {};
  2008. if (big_int_is_neg(bi)) {
  2009. big_int_neg(&max_size, &max_size);
  2010. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2011. } else {
  2012. big_int_sub_eq(&max_size, &one);
  2013. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2014. }
  2015. if (size_changed) {
  2016. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2017. } else {
  2018. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2019. }
  2020. }
  2021. return true;
  2022. }
  2023. return false;
  2024. }
  2025. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2026. gbString a = expr_to_string(o->expr);
  2027. gbString b = type_to_string(type);
  2028. defer(
  2029. gb_string_free(b);
  2030. gb_string_free(a);
  2031. );
  2032. Type *src = base_type(o->type);
  2033. Type *dst = base_type(type);
  2034. if (is_type_array(src) && is_type_slice(dst)) {
  2035. Type *s = src->Array.elem;
  2036. Type *d = dst->Slice.elem;
  2037. if (are_types_identical(s, d)) {
  2038. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2039. }
  2040. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2041. Type *s = src->DynamicArray.elem;
  2042. Type *d = dst->Slice.elem;
  2043. if (are_types_identical(s, d)) {
  2044. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  2045. }
  2046. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2047. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  2048. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2049. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2050. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  2051. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2052. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2053. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  2054. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2055. return;
  2056. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2057. gbString s = expr_to_string(c->type_hint_expr);
  2058. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  2059. gb_string_free(s);
  2060. } else if (is_type_pointer(type) &&
  2061. o->mode == Addressing_Variable &&
  2062. are_types_identical(type_deref(type), o->type)) {
  2063. gbString s = expr_to_string(o->expr);
  2064. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2065. gb_string_free(s);
  2066. } else if (is_type_pointer(o->type) &&
  2067. are_types_identical(type_deref(o->type), type)) {
  2068. gbString s = expr_to_string(o->expr);
  2069. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2070. gb_string_free(s);
  2071. }
  2072. }
  2073. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2074. gbString a = expr_to_string(o->expr);
  2075. gbString b = type_to_string(type);
  2076. defer(
  2077. gb_string_free(b);
  2078. gb_string_free(a);
  2079. );
  2080. Type *src = base_type(o->type);
  2081. Type *dst = base_type(type);
  2082. if (is_type_array(src) && is_type_slice(dst)) {
  2083. Type *s = src->Array.elem;
  2084. Type *d = dst->Slice.elem;
  2085. if (are_types_identical(s, d)) {
  2086. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2087. }
  2088. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2089. if (is_type_uintptr(type)) {
  2090. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2091. } else {
  2092. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2093. i64 x = type_size_of(o->type);
  2094. i64 y = type_size_of(type);
  2095. if (x != y) {
  2096. 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);
  2097. }
  2098. }
  2099. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2100. if (is_type_uintptr(o->type)) {
  2101. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2102. } else {
  2103. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2104. }
  2105. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2106. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2107. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2108. return;
  2109. }
  2110. }
  2111. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2112. GB_ASSERT(o->mode == Addressing_Constant);
  2113. ExactValue out_value = o->value;
  2114. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2115. o->value = out_value;
  2116. return true;
  2117. } else {
  2118. o->value = out_value;
  2119. gbString a = expr_to_string(o->expr);
  2120. gbString b = type_to_string(type);
  2121. gbString c = type_to_string(o->type);
  2122. gbString s = exact_value_to_string(o->value);
  2123. defer(
  2124. gb_string_free(s);
  2125. gb_string_free(c);
  2126. gb_string_free(b);
  2127. gb_string_free(a);
  2128. o->mode = Addressing_Invalid;
  2129. );
  2130. ERROR_BLOCK();
  2131. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2132. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2133. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2134. } else {
  2135. i64 max_bit_size = 0;
  2136. if (ctx->bit_field_bit_size) {
  2137. max_bit_size = ctx->bit_field_bit_size;
  2138. }
  2139. if (are_types_identical(o->type, type)) {
  2140. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2141. } else {
  2142. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2143. }
  2144. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2145. }
  2146. } else {
  2147. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2148. check_assignment_error_suggestion(ctx, o, type);
  2149. }
  2150. return false;
  2151. }
  2152. }
  2153. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2154. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2155. if (o->expr->SelectorExpr.is_bit_field) {
  2156. return true;
  2157. }
  2158. }
  2159. if (o->mode == Addressing_OptionalOk) {
  2160. Ast *expr = unselector_expr(o->expr);
  2161. if (expr->kind != Ast_TypeAssertion) {
  2162. return true;
  2163. }
  2164. ast_node(ta, TypeAssertion, expr);
  2165. TypeAndValue tv = ta->expr->tav;
  2166. if (is_type_pointer(tv.type)) {
  2167. return false;
  2168. }
  2169. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2170. return false;
  2171. }
  2172. if (is_type_any(tv.type)) {
  2173. return false;
  2174. }
  2175. return true;
  2176. }
  2177. if (o->mode == Addressing_MapIndex) {
  2178. return false;
  2179. }
  2180. Ast *expr = unparen_expr(o->expr);
  2181. if (expr->kind == Ast_CompoundLit) {
  2182. return false;
  2183. }
  2184. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2185. }
  2186. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2187. switch (op.kind) {
  2188. case Token_And: { // Pointer address
  2189. if (check_is_not_addressable(c, o)) {
  2190. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2191. ast_node(ue, UnaryExpr, node);
  2192. gbString str = expr_to_string(ue->expr);
  2193. defer (gb_string_free(str));
  2194. Entity *e = entity_of_node(ue->expr);
  2195. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2196. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2197. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2198. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2199. } else {
  2200. switch (o->mode) {
  2201. case Addressing_Constant:
  2202. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2203. break;
  2204. case Addressing_SwizzleValue:
  2205. case Addressing_SwizzleVariable:
  2206. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2207. break;
  2208. default:
  2209. {
  2210. ERROR_BLOCK();
  2211. error(op, "Cannot take the pointer address of '%s'", str);
  2212. if (e == nullptr) {
  2213. break;
  2214. }
  2215. if ((e->flags & EntityFlag_ForValue) != 0) {
  2216. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2217. if (parent_type != nullptr && is_type_string(parent_type)) {
  2218. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2219. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2220. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2221. } else {
  2222. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2223. }
  2224. if (is_type_map(parent_type)) {
  2225. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2226. } else {
  2227. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2228. }
  2229. }
  2230. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2231. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2232. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2233. }
  2234. }
  2235. break;
  2236. }
  2237. }
  2238. }
  2239. o->mode = Addressing_Invalid;
  2240. return;
  2241. }
  2242. if (o->mode == Addressing_SoaVariable) {
  2243. ast_node(ue, UnaryExpr, node);
  2244. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2245. ast_node(ie, IndexExpr, ue->expr);
  2246. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2247. GB_ASSERT(is_type_soa_struct(soa_type));
  2248. o->type = alloc_type_soa_pointer(soa_type);
  2249. } else {
  2250. o->type = alloc_type_pointer(o->type);
  2251. }
  2252. } else {
  2253. o->type = alloc_type_pointer(o->type);
  2254. }
  2255. switch (o->mode) {
  2256. case Addressing_OptionalOk:
  2257. case Addressing_MapIndex:
  2258. o->mode = Addressing_OptionalOkPtr;
  2259. break;
  2260. default:
  2261. o->mode = Addressing_Value;
  2262. break;
  2263. }
  2264. return;
  2265. }
  2266. }
  2267. if (!check_unary_op(c, o, op)) {
  2268. o->mode = Addressing_Invalid;
  2269. return;
  2270. }
  2271. if (o->mode == Addressing_Constant) {
  2272. Type *type = base_type(o->type);
  2273. if (!is_type_constant_type(o->type)) {
  2274. gbString xt = type_to_string(o->type);
  2275. gbString err_str = expr_to_string(node);
  2276. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2277. gb_string_free(err_str);
  2278. gb_string_free(xt);
  2279. o->mode = Addressing_Invalid;
  2280. return;
  2281. }
  2282. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2283. gbString err_str = expr_to_string(node);
  2284. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2285. gb_string_free(err_str);
  2286. o->mode = Addressing_Invalid;
  2287. return;
  2288. }
  2289. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2290. gbString err_str = expr_to_string(node);
  2291. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2292. gb_string_free(err_str);
  2293. o->mode = Addressing_Invalid;
  2294. return;
  2295. }
  2296. i32 precision = 0;
  2297. if (is_type_typed(type)) {
  2298. precision = cast(i32)(8 * type_size_of(type));
  2299. }
  2300. bool is_unsigned = is_type_unsigned(type);
  2301. if (is_type_rune(type)) {
  2302. GB_ASSERT(!is_unsigned);
  2303. }
  2304. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2305. if (is_type_typed(type)) {
  2306. if (node != nullptr) {
  2307. o->expr = node;
  2308. }
  2309. check_is_expressible(c, o, type);
  2310. }
  2311. return;
  2312. }
  2313. o->mode = Addressing_Value;
  2314. }
  2315. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2316. if (t == nullptr) {
  2317. return;
  2318. }
  2319. t = base_type(t);
  2320. if (!is_type_comparable(t)) {
  2321. return;
  2322. }
  2323. switch (t->kind) {
  2324. case Type_Basic:
  2325. switch (t->Basic.kind) {
  2326. case Basic_complex32:
  2327. add_package_dependency(c, "runtime", "complex32_eq");
  2328. add_package_dependency(c, "runtime", "complex32_ne");
  2329. break;
  2330. case Basic_complex64:
  2331. add_package_dependency(c, "runtime", "complex64_eq");
  2332. add_package_dependency(c, "runtime", "complex64_ne");
  2333. break;
  2334. case Basic_complex128:
  2335. add_package_dependency(c, "runtime", "complex128_eq");
  2336. add_package_dependency(c, "runtime", "complex128_ne");
  2337. break;
  2338. case Basic_quaternion64:
  2339. add_package_dependency(c, "runtime", "quaternion64_eq");
  2340. add_package_dependency(c, "runtime", "quaternion64_ne");
  2341. break;
  2342. case Basic_quaternion128:
  2343. add_package_dependency(c, "runtime", "quaternion128_eq");
  2344. add_package_dependency(c, "runtime", "quaternion128_ne");
  2345. break;
  2346. case Basic_quaternion256:
  2347. add_package_dependency(c, "runtime", "quaternion256_eq");
  2348. add_package_dependency(c, "runtime", "quaternion256_ne");
  2349. break;
  2350. case Basic_cstring:
  2351. add_package_dependency(c, "runtime", "cstring_eq");
  2352. add_package_dependency(c, "runtime", "cstring_ne");
  2353. break;
  2354. case Basic_string:
  2355. add_package_dependency(c, "runtime", "string_eq");
  2356. add_package_dependency(c, "runtime", "string_ne");
  2357. break;
  2358. }
  2359. break;
  2360. case Type_Struct:
  2361. for (Entity *field : t->Struct.fields) {
  2362. add_comparison_procedures_for_fields(c, field->type);
  2363. }
  2364. break;
  2365. }
  2366. }
  2367. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2368. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2369. bool comp = are_types_identical(x->type, y->type);
  2370. switch (op) {
  2371. case Token_CmpEq: /* comp = comp; */ break;
  2372. case Token_NotEq: comp = !comp; break;
  2373. }
  2374. x->mode = Addressing_Constant;
  2375. x->type = t_untyped_bool;
  2376. x->value = exact_value_bool(comp);
  2377. return;
  2378. }
  2379. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2380. add_type_info_type(c, x->type);
  2381. add_type_info_type(c, y->type);
  2382. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2383. x->mode = Addressing_Value;
  2384. x->type = t_untyped_bool;
  2385. return;
  2386. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2387. add_type_info_type(c, x->type);
  2388. add_type_info_type(c, y->type);
  2389. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2390. x->mode = Addressing_Value;
  2391. x->type = t_untyped_bool;
  2392. return;
  2393. }
  2394. TEMPORARY_ALLOCATOR_GUARD();
  2395. gbString err_str = nullptr;
  2396. if (check_is_assignable_to(c, x, y->type) ||
  2397. check_is_assignable_to(c, y, x->type)) {
  2398. Type *err_type = x->type;
  2399. bool defined = false;
  2400. switch (op) {
  2401. case Token_CmpEq:
  2402. case Token_NotEq:
  2403. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2404. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2405. (is_operand_nil(*y) && type_has_nil(x->type));
  2406. break;
  2407. case Token_Lt:
  2408. case Token_Gt:
  2409. case Token_LtEq:
  2410. case Token_GtEq:
  2411. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2412. defined = true;
  2413. } else {
  2414. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2415. }
  2416. break;
  2417. }
  2418. if (!defined) {
  2419. gbString xs = type_to_string(x->type, temporary_allocator());
  2420. gbString ys = type_to_string(y->type, temporary_allocator());
  2421. err_str = gb_string_make(temporary_allocator(),
  2422. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2423. );
  2424. } else {
  2425. Type *comparison_type = x->type;
  2426. if (x->type == err_type && is_operand_nil(*x)) {
  2427. comparison_type = y->type;
  2428. }
  2429. add_comparison_procedures_for_fields(c, comparison_type);
  2430. }
  2431. } else {
  2432. gbString xt, yt;
  2433. if (x->mode == Addressing_ProcGroup) {
  2434. xt = gb_string_make(temporary_allocator(), "procedure group");
  2435. } else {
  2436. xt = type_to_string(x->type);
  2437. }
  2438. if (y->mode == Addressing_ProcGroup) {
  2439. yt = gb_string_make(temporary_allocator(), "procedure group");
  2440. } else {
  2441. yt = type_to_string(y->type);
  2442. }
  2443. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2444. }
  2445. if (err_str != nullptr) {
  2446. error(node, "Cannot compare expression, %s", err_str);
  2447. x->type = t_untyped_bool;
  2448. } else {
  2449. if (x->mode == Addressing_Constant &&
  2450. y->mode == Addressing_Constant) {
  2451. if (is_type_constant_type(x->type)) {
  2452. if (is_type_bit_set(x->type)) {
  2453. switch (op) {
  2454. case Token_CmpEq:
  2455. case Token_NotEq:
  2456. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2457. break;
  2458. case Token_Lt:
  2459. case Token_LtEq:
  2460. {
  2461. ExactValue lhs = x->value;
  2462. ExactValue rhs = y->value;
  2463. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2464. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2465. if (op == Token_Lt) {
  2466. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2467. }
  2468. x->value = res;
  2469. break;
  2470. }
  2471. case Token_Gt:
  2472. case Token_GtEq:
  2473. {
  2474. ExactValue lhs = x->value;
  2475. ExactValue rhs = y->value;
  2476. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2477. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2478. if (op == Token_Gt) {
  2479. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2480. }
  2481. x->value = res;
  2482. break;
  2483. }
  2484. }
  2485. } else {
  2486. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2487. }
  2488. } else {
  2489. x->mode = Addressing_Value;
  2490. }
  2491. } else {
  2492. x->mode = Addressing_Value;
  2493. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2494. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2495. i64 size = 0;
  2496. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2497. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2498. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2499. switch (op) {
  2500. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2501. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2502. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2503. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2504. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2505. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2506. }
  2507. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2508. switch (op) {
  2509. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2510. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2511. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2512. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2513. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2514. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2515. }
  2516. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2517. switch (op) {
  2518. case Token_CmpEq:
  2519. switch (8*size) {
  2520. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2521. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2522. }
  2523. break;
  2524. case Token_NotEq:
  2525. switch (8*size) {
  2526. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2527. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2528. }
  2529. break;
  2530. }
  2531. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2532. switch (op) {
  2533. case Token_CmpEq:
  2534. switch (8*size) {
  2535. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2536. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2537. }
  2538. break;
  2539. case Token_NotEq:
  2540. switch (8*size) {
  2541. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2542. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2543. }
  2544. break;
  2545. }
  2546. }
  2547. }
  2548. x->type = t_untyped_bool;
  2549. }
  2550. }
  2551. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2552. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2553. ast_node(be, BinaryExpr, node);
  2554. ExactValue x_val = {};
  2555. if (x->mode == Addressing_Constant) {
  2556. x_val = exact_value_to_integer(x->value);
  2557. }
  2558. bool x_is_untyped = is_type_untyped(x->type);
  2559. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2560. gbString err_str = expr_to_string(x->expr);
  2561. error(node, "Shifted operand '%s' must be an integer", err_str);
  2562. gb_string_free(err_str);
  2563. x->mode = Addressing_Invalid;
  2564. return;
  2565. }
  2566. if (is_type_unsigned(y->type)) {
  2567. } else if (is_type_untyped(y->type)) {
  2568. convert_to_typed(c, y, t_untyped_integer);
  2569. if (y->mode == Addressing_Invalid) {
  2570. x->mode = Addressing_Invalid;
  2571. return;
  2572. }
  2573. } else {
  2574. gbString err_str = expr_to_string(y->expr);
  2575. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2576. gb_string_free(err_str);
  2577. x->mode = Addressing_Invalid;
  2578. return;
  2579. }
  2580. if (x->mode == Addressing_Constant) {
  2581. if (y->mode == Addressing_Constant) {
  2582. ExactValue y_val = exact_value_to_integer(y->value);
  2583. if (y_val.kind != ExactValue_Integer) {
  2584. gbString err_str = expr_to_string(y->expr);
  2585. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2586. gb_string_free(err_str);
  2587. x->mode = Addressing_Invalid;
  2588. return;
  2589. }
  2590. BigInt max_shift = {};
  2591. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2592. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2593. gbString err_str = expr_to_string(y->expr);
  2594. error(node, "Shift amount too large: '%s'", err_str);
  2595. gb_string_free(err_str);
  2596. x->mode = Addressing_Invalid;
  2597. return;
  2598. }
  2599. if (!is_type_integer(x->type)) {
  2600. // NOTE(bill): It could be an untyped float but still representable
  2601. // as an integer
  2602. x->type = t_untyped_integer;
  2603. }
  2604. x->expr = node;
  2605. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2606. if (is_type_typed(x->type)) {
  2607. check_is_expressible(c, x, x->type);
  2608. }
  2609. return;
  2610. }
  2611. TokenPos pos = ast_token(x->expr).pos;
  2612. if (x_is_untyped) {
  2613. if (x->expr != nullptr) {
  2614. x->expr->tav.is_lhs = true;
  2615. }
  2616. x->mode = Addressing_Value;
  2617. if (type_hint) {
  2618. if (is_type_integer(type_hint)) {
  2619. x->type = type_hint;
  2620. } else {
  2621. gbString x_str = expr_to_string(x->expr);
  2622. gbString to_type = type_to_string(type_hint);
  2623. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2624. gb_string_free(x_str);
  2625. gb_string_free(to_type);
  2626. x->mode = Addressing_Invalid;
  2627. }
  2628. } else if (!is_type_integer(x->type)) {
  2629. gbString x_str = expr_to_string(x->expr);
  2630. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2631. gb_string_free(x_str);
  2632. x->mode = Addressing_Invalid;
  2633. }
  2634. // x->value = x_val;
  2635. return;
  2636. }
  2637. }
  2638. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2639. gbString err_str = expr_to_string(y->expr);
  2640. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2641. gb_string_free(err_str);
  2642. }
  2643. if (!is_type_integer(x->type)) {
  2644. gbString err_str = expr_to_string(x->expr);
  2645. error(node, "Shift operand '%s' must be an integer", err_str);
  2646. gb_string_free(err_str);
  2647. x->mode = Addressing_Invalid;
  2648. return;
  2649. }
  2650. if (is_type_untyped(y->type)) {
  2651. convert_to_typed(c, y, t_uint);
  2652. }
  2653. x->mode = Addressing_Value;
  2654. }
  2655. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2656. if (check_is_assignable_to(c, operand, y)) {
  2657. return true;
  2658. }
  2659. bool is_constant = operand->mode == Addressing_Constant;
  2660. Type *x = operand->type;
  2661. Type *src = core_type(x);
  2662. Type *dst = core_type(y);
  2663. if (are_types_identical(src, dst)) {
  2664. return true;
  2665. }
  2666. // if (is_type_tuple(src)) {
  2667. // Ast *expr = unparen_expr(operand->expr);
  2668. // if (expr && expr->kind == Ast_CallExpr) {
  2669. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2670. // ast_node(ce, CallExpr, expr);
  2671. // Type *pt = base_type(type_of_expr(ce->proc));
  2672. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2673. // if (pt->Proc.result_count > 0) {
  2674. // Operand op = *operand;
  2675. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2676. // bool ok = check_is_castable_to(c, &op, y);
  2677. // if (ok) {
  2678. // ce->optional_ok_one = true;
  2679. // }
  2680. // return ok;
  2681. // }
  2682. // }
  2683. // }
  2684. // }
  2685. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2686. if (is_type_u8_array(dst)) {
  2687. String s = operand->value.value_string;
  2688. return s.len == dst->Array.count;
  2689. }
  2690. if (is_type_rune_array(dst)) {
  2691. String s = operand->value.value_string;
  2692. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2693. }
  2694. }
  2695. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2696. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2697. return dst->Array.count == src->Array.count;
  2698. }
  2699. }
  2700. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2701. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2702. }
  2703. // Cast between booleans and integers
  2704. if (is_type_boolean(src) || is_type_integer(src)) {
  2705. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2706. return true;
  2707. }
  2708. }
  2709. // Cast between numbers
  2710. if (is_type_integer(src) || is_type_float(src)) {
  2711. if (is_type_integer(dst) || is_type_float(dst)) {
  2712. return true;
  2713. }
  2714. }
  2715. if (is_type_bit_field(src)) {
  2716. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2717. }
  2718. if (is_type_bit_field(dst)) {
  2719. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2720. }
  2721. if (is_type_integer(src) && is_type_rune(dst)) {
  2722. return true;
  2723. }
  2724. if (is_type_rune(src) && is_type_integer(dst)) {
  2725. return true;
  2726. }
  2727. if (is_type_complex(src) && is_type_complex(dst)) {
  2728. return true;
  2729. }
  2730. if (is_type_float(src) && is_type_complex(dst)) {
  2731. return true;
  2732. }
  2733. if (is_type_float(src) && is_type_quaternion(dst)) {
  2734. return true;
  2735. }
  2736. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2737. return true;
  2738. }
  2739. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2740. return true;
  2741. }
  2742. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2743. GB_ASSERT(src->kind == Type_Matrix);
  2744. GB_ASSERT(dst->kind == Type_Matrix);
  2745. Operand op = *operand;
  2746. op.type = src->Matrix.elem;
  2747. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2748. return false;
  2749. }
  2750. if (src->Matrix.row_count != src->Matrix.column_count) {
  2751. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2752. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2753. return src_count == dst_count;
  2754. }
  2755. return is_matrix_square(dst) && is_matrix_square(src);
  2756. }
  2757. // Cast between pointers
  2758. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2759. return true;
  2760. }
  2761. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2762. return true;
  2763. }
  2764. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2765. return true;
  2766. }
  2767. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2768. return true;
  2769. }
  2770. // uintptr <-> pointer
  2771. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2772. return true;
  2773. }
  2774. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2775. return true;
  2776. }
  2777. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2778. return true;
  2779. }
  2780. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2781. return true;
  2782. }
  2783. // []byte/[]u8 <-> string (not cstring)
  2784. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2785. return true;
  2786. }
  2787. // cstring -> string
  2788. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2789. if (operand->mode != Addressing_Constant) {
  2790. add_package_dependency(c, "runtime", "cstring_to_string");
  2791. }
  2792. return true;
  2793. }
  2794. // cstring -> ^u8
  2795. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2796. return !is_constant;
  2797. }
  2798. // cstring -> [^]u8
  2799. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2800. return !is_constant;
  2801. }
  2802. // cstring -> rawptr
  2803. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2804. return !is_constant;
  2805. }
  2806. // ^u8 -> cstring
  2807. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2808. return !is_constant;
  2809. }
  2810. // [^]u8 -> cstring
  2811. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2812. return !is_constant;
  2813. }
  2814. // rawptr -> cstring
  2815. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2816. return !is_constant;
  2817. }
  2818. // proc <-> proc
  2819. if (is_type_proc(src) && is_type_proc(dst)) {
  2820. if (is_type_polymorphic(dst)) {
  2821. if (is_type_polymorphic(src) &&
  2822. operand->mode == Addressing_Variable) {
  2823. return true;
  2824. }
  2825. return false;
  2826. }
  2827. return true;
  2828. }
  2829. // proc -> rawptr
  2830. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2831. return true;
  2832. }
  2833. // rawptr -> proc
  2834. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2835. return true;
  2836. }
  2837. if (is_type_array(dst)) {
  2838. Type *elem = base_array_type(dst);
  2839. if (check_is_castable_to(c, operand, elem)) {
  2840. return true;
  2841. }
  2842. }
  2843. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2844. if (src->SimdVector.count != dst->SimdVector.count) {
  2845. return false;
  2846. }
  2847. Type *elem_src = base_array_type(src);
  2848. Type *elem_dst = base_array_type(dst);
  2849. Operand x = {};
  2850. x.type = elem_src;
  2851. x.mode = Addressing_Value;
  2852. return check_is_castable_to(c, &x, elem_dst);
  2853. }
  2854. if (is_type_simd_vector(dst)) {
  2855. Type *elem = base_array_type(dst);
  2856. if (check_is_castable_to(c, operand, elem)) {
  2857. return true;
  2858. }
  2859. }
  2860. return false;
  2861. }
  2862. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2863. bool is_const_expr = x->mode == Addressing_Constant;
  2864. Type *bt = base_type(type);
  2865. if (is_const_expr && is_type_constant_type(bt)) {
  2866. if (core_type(bt)->kind == Type_Basic) {
  2867. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2868. return true;
  2869. } else if (check_is_castable_to(c, x, type)) {
  2870. if (is_type_pointer(type)) {
  2871. return true;
  2872. }
  2873. }
  2874. } else if (check_is_castable_to(c, x, type)) {
  2875. x->value = {};
  2876. x->mode = Addressing_Value;
  2877. return true;
  2878. }
  2879. } else if (check_is_castable_to(c, x, type)) {
  2880. if (x->mode != Addressing_Constant) {
  2881. x->mode = Addressing_Value;
  2882. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2883. x->mode = Addressing_Value;
  2884. } else if (is_type_union(type)) {
  2885. x->mode = Addressing_Value;
  2886. }
  2887. if (x->mode == Addressing_Value) {
  2888. x->value = {};
  2889. }
  2890. return true;
  2891. }
  2892. return false;
  2893. }
  2894. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2895. if (!is_operand_value(*x)) {
  2896. error(x->expr, "Only values can be casted");
  2897. x->mode = Addressing_Invalid;
  2898. return;
  2899. }
  2900. bool is_const_expr = x->mode == Addressing_Constant;
  2901. bool can_convert = check_cast_internal(c, x, type);
  2902. if (!can_convert) {
  2903. TEMPORARY_ALLOCATOR_GUARD();
  2904. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2905. gbString to_type = type_to_string(type, temporary_allocator());
  2906. gbString from_type = type_to_string(x->type, temporary_allocator());
  2907. x->mode = Addressing_Invalid;
  2908. ERROR_BLOCK();
  2909. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2910. if (is_const_expr) {
  2911. gbString val_str = exact_value_to_string(x->value);
  2912. if (is_type_float(x->type) && is_type_integer(type)) {
  2913. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2914. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2915. x->mode = Addressing_Constant;
  2916. x->type = type;
  2917. } else {
  2918. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2919. if (is_type_numeric(type)) {
  2920. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2921. x->mode = Addressing_Constant;
  2922. x->type = type;
  2923. }
  2924. }
  2925. gb_string_free(val_str);
  2926. }
  2927. check_cast_error_suggestion(c, x, type);
  2928. return;
  2929. }
  2930. if (is_type_untyped(x->type)) {
  2931. convert_to_typed(c, x, type);
  2932. // Type *final_type = type;
  2933. // if (is_const_expr && !is_type_constant_type(type)) {
  2934. // final_type = default_type(x->type);
  2935. // }
  2936. // update_untyped_expr_type(c, x->expr, final_type, true);
  2937. } else {
  2938. Type *src = core_type(x->type);
  2939. Type *dst = core_type(type);
  2940. if (src != dst) {
  2941. bool const REQUIRE = true;
  2942. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  2943. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  2944. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  2945. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  2946. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  2947. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  2948. } else if (src == t_f16 && is_type_float(dst)) {
  2949. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  2950. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  2951. } else if (is_type_float(dst) && dst == t_f16) {
  2952. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  2953. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  2954. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  2955. }
  2956. }
  2957. }
  2958. x->type = type;
  2959. }
  2960. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2961. if (!is_operand_value(*o)) {
  2962. error(o->expr, "'transmute' can only be applied to values");
  2963. o->mode = Addressing_Invalid;
  2964. return false;
  2965. }
  2966. // if (o->mode == Addressing_Constant) {
  2967. // gbString expr_str = expr_to_string(o->expr);
  2968. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2969. // gb_string_free(expr_str);
  2970. // o->mode = Addressing_Invalid;
  2971. // o->expr = node;
  2972. // return false;
  2973. // }
  2974. Type *src_t = o->type;
  2975. Type *dst_t = t;
  2976. Type *src_bt = base_type(src_t);
  2977. Type *dst_bt = base_type(dst_t);
  2978. if (is_type_untyped(src_t)) {
  2979. gbString expr_str = expr_to_string(o->expr);
  2980. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2981. gb_string_free(expr_str);
  2982. o->mode = Addressing_Invalid;
  2983. o->expr = node;
  2984. return false;
  2985. }
  2986. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2987. GB_ASSERT(global_error_collector.count != 0);
  2988. o->mode = Addressing_Invalid;
  2989. o->expr = node;
  2990. return false;
  2991. }
  2992. if (src_bt == nullptr || src_bt == t_invalid) {
  2993. // NOTE(bill): this should be an error
  2994. GB_ASSERT(global_error_collector.count != 0);
  2995. o->mode = Addressing_Value;
  2996. o->expr = node;
  2997. o->type = dst_t;
  2998. return true;
  2999. }
  3000. i64 srcz = type_size_of(src_t);
  3001. i64 dstz = type_size_of(dst_t);
  3002. if (srcz != dstz) {
  3003. gbString expr_str = expr_to_string(o->expr);
  3004. gbString type_str = type_to_string(dst_t);
  3005. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3006. gb_string_free(type_str);
  3007. gb_string_free(expr_str);
  3008. o->mode = Addressing_Invalid;
  3009. o->expr = node;
  3010. return false;
  3011. }
  3012. o->expr = node;
  3013. o->type = dst_t;
  3014. if (o->mode == Addressing_Constant) {
  3015. if (are_types_identical(src_bt, dst_bt)) {
  3016. return true;
  3017. }
  3018. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  3019. if (types_have_same_internal_endian(src_t, dst_t)) {
  3020. ExactValue src_v = exact_value_to_integer(o->value);
  3021. GB_ASSERT(src_v.kind == ExactValue_Integer);
  3022. BigInt v = src_v.value_integer;
  3023. BigInt smax = {};
  3024. BigInt umax = {};
  3025. big_int_from_u64(&smax, 0);
  3026. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3027. big_int_from_u64(&umax, 1);
  3028. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3029. big_int_shl_eq(&umax, &sz_in_bits);
  3030. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3031. if (big_int_cmp(&v, &smax) >= 0) {
  3032. big_int_sub_eq(&v, &umax);
  3033. }
  3034. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3035. if (big_int_is_neg(&v)) {
  3036. big_int_add_eq(&v, &umax);
  3037. }
  3038. }
  3039. o->value.kind = ExactValue_Integer;
  3040. o->value.value_integer = v;
  3041. return true;
  3042. }
  3043. }
  3044. }
  3045. o->mode = Addressing_Value;
  3046. o->value = {};
  3047. return true;
  3048. }
  3049. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3050. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3051. if (check_is_assignable_to(c, y, x->type)) {
  3052. if (check_binary_op(c, x, op)) {
  3053. return true;
  3054. }
  3055. }
  3056. }
  3057. return false;
  3058. }
  3059. gb_internal bool is_ise_expr(Ast *node) {
  3060. node = unparen_expr(node);
  3061. return node->kind == Ast_ImplicitSelectorExpr;
  3062. }
  3063. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3064. if (use_lhs_as_type_hint) { // RHS in this case
  3065. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3066. }
  3067. return false;
  3068. }
  3069. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3070. Type *xt = base_type(matrix);
  3071. if (type_hint != nullptr) {
  3072. Type *th = base_type(type_hint);
  3073. if (are_types_identical(th, xt)) {
  3074. return type_hint;
  3075. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3076. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3077. // ignore
  3078. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3079. xt->Matrix.column_count == th->Matrix.column_count) {
  3080. return type_hint;
  3081. }
  3082. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3083. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3084. // ignore
  3085. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3086. return type_hint;
  3087. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3088. return type_hint;
  3089. }
  3090. }
  3091. }
  3092. return matrix;
  3093. }
  3094. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3095. if (!check_binary_op(c, x, op)) {
  3096. x->mode = Addressing_Invalid;
  3097. return;
  3098. }
  3099. Type *xt = base_type(x->type);
  3100. Type *yt = base_type(y->type);
  3101. if (is_type_matrix(x->type)) {
  3102. GB_ASSERT(xt->kind == Type_Matrix);
  3103. if (op.kind == Token_Mul) {
  3104. if (yt->kind == Type_Matrix) {
  3105. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3106. goto matrix_error;
  3107. }
  3108. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3109. goto matrix_error;
  3110. }
  3111. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3112. goto matrix_error;
  3113. }
  3114. x->mode = Addressing_Value;
  3115. if (are_types_identical(xt, yt)) {
  3116. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3117. // prefer the named type
  3118. x->type = y->type;
  3119. }
  3120. } else {
  3121. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3122. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3123. }
  3124. goto matrix_success;
  3125. } else if (yt->kind == Type_Array) {
  3126. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3127. goto matrix_error;
  3128. }
  3129. if (xt->Matrix.column_count != yt->Array.count) {
  3130. goto matrix_error;
  3131. }
  3132. // Treat arrays as column vectors
  3133. x->mode = Addressing_Value;
  3134. if (xt->Matrix.row_count == yt->Array.count) {
  3135. x->type = y->type;
  3136. } else {
  3137. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3138. }
  3139. goto matrix_success;
  3140. }
  3141. }
  3142. if (!are_types_identical(xt, yt)) {
  3143. goto matrix_error;
  3144. }
  3145. x->mode = Addressing_Value;
  3146. x->type = xt;
  3147. goto matrix_success;
  3148. } else {
  3149. GB_ASSERT(!is_type_matrix(xt));
  3150. GB_ASSERT(is_type_matrix(yt));
  3151. if (op.kind == Token_Mul) {
  3152. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3153. if (xt->kind == Type_Array) {
  3154. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3155. goto matrix_error;
  3156. }
  3157. if (xt->Array.count != yt->Matrix.row_count) {
  3158. goto matrix_error;
  3159. }
  3160. // Treat arrays as row vectors
  3161. x->mode = Addressing_Value;
  3162. if (yt->Matrix.column_count == xt->Array.count) {
  3163. x->type = x->type;
  3164. } else {
  3165. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3166. }
  3167. goto matrix_success;
  3168. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3169. x->type = check_matrix_type_hint(y->type, type_hint);
  3170. return;
  3171. }
  3172. }
  3173. if (!are_types_identical(xt, yt)) {
  3174. goto matrix_error;
  3175. }
  3176. x->mode = Addressing_Value;
  3177. x->type = xt;
  3178. goto matrix_success;
  3179. }
  3180. matrix_success:
  3181. x->type = check_matrix_type_hint(x->type, type_hint);
  3182. return;
  3183. matrix_error:
  3184. gbString xts = type_to_string(x->type);
  3185. gbString yts = type_to_string(y->type);
  3186. gbString expr_str = expr_to_string(x->expr);
  3187. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3188. gb_string_free(expr_str);
  3189. gb_string_free(yts);
  3190. gb_string_free(xts);
  3191. x->type = t_invalid;
  3192. x->mode = Addressing_Invalid;
  3193. return;
  3194. }
  3195. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3196. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3197. Operand y_ = {}, *y = &y_;
  3198. ast_node(be, BinaryExpr, node);
  3199. defer({
  3200. node->viral_state_flags |= be->left->viral_state_flags;
  3201. node->viral_state_flags |= be->right->viral_state_flags;
  3202. });
  3203. Token op = be->op;
  3204. switch (op.kind) {
  3205. case Token_CmpEq:
  3206. case Token_NotEq: {
  3207. // NOTE(bill): Allow comparisons between types
  3208. if (is_ise_expr(be->left)) {
  3209. // Evalute the right before the left for an '.X' expression
  3210. check_expr_or_type(c, y, be->right, type_hint);
  3211. check_expr_or_type(c, x, be->left, y->type);
  3212. } else {
  3213. check_expr_or_type(c, x, be->left, type_hint);
  3214. check_expr_or_type(c, y, be->right, x->type);
  3215. }
  3216. bool xt = x->mode == Addressing_Type;
  3217. bool yt = y->mode == Addressing_Type;
  3218. // If only one is a type, this is an error
  3219. if (xt ^ yt) {
  3220. GB_ASSERT(xt != yt);
  3221. if (xt) {
  3222. if (!is_type_typeid(y->type)) {
  3223. error_operand_not_expression(x);
  3224. }
  3225. }
  3226. if (yt) {
  3227. if (!is_type_typeid(x->type)) {
  3228. error_operand_not_expression(y);
  3229. }
  3230. }
  3231. }
  3232. break;
  3233. }
  3234. case Token_in:
  3235. case Token_not_in:
  3236. {
  3237. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3238. check_expr(c, y, be->right);
  3239. Type *rhs_type = type_deref(y->type);
  3240. if (is_type_bit_set(rhs_type)) {
  3241. Type *elem = base_type(rhs_type)->BitSet.elem;
  3242. check_expr_with_type_hint(c, x, be->left, elem);
  3243. } else if (is_type_map(rhs_type)) {
  3244. Type *key = base_type(rhs_type)->Map.key;
  3245. check_expr_with_type_hint(c, x, be->left, key);
  3246. } else {
  3247. check_expr(c, x, be->left);
  3248. }
  3249. if (x->mode == Addressing_Invalid) {
  3250. return;
  3251. }
  3252. if (y->mode == Addressing_Invalid) {
  3253. x->mode = Addressing_Invalid;
  3254. x->expr = y->expr;
  3255. return;
  3256. }
  3257. if (is_type_map(rhs_type)) {
  3258. Type *yt = base_type(rhs_type);
  3259. if (op.kind == Token_in) {
  3260. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3261. } else {
  3262. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3263. }
  3264. add_map_get_dependencies(c);
  3265. } else if (is_type_bit_set(rhs_type)) {
  3266. Type *yt = base_type(rhs_type);
  3267. if (op.kind == Token_in) {
  3268. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3269. } else {
  3270. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3271. }
  3272. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3273. ExactValue k = exact_value_to_integer(x->value);
  3274. ExactValue v = exact_value_to_integer(y->value);
  3275. GB_ASSERT(k.kind == ExactValue_Integer);
  3276. GB_ASSERT(v.kind == ExactValue_Integer);
  3277. i64 key = big_int_to_i64(&k.value_integer);
  3278. i64 lower = yt->BitSet.lower;
  3279. i64 upper = yt->BitSet.upper;
  3280. if (lower <= key && key <= upper) {
  3281. i64 bit = 1ll<<key;
  3282. i64 bits = big_int_to_i64(&v.value_integer);
  3283. x->mode = Addressing_Constant;
  3284. x->type = t_untyped_bool;
  3285. if (op.kind == Token_in) {
  3286. x->value = exact_value_bool((bit & bits) != 0);
  3287. } else {
  3288. x->value = exact_value_bool((bit & bits) == 0);
  3289. }
  3290. x->expr = node;
  3291. return;
  3292. } else {
  3293. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3294. x->mode = Addressing_Invalid;
  3295. }
  3296. }
  3297. } else {
  3298. gbString t = type_to_string(y->type);
  3299. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3300. gb_string_free(t);
  3301. x->expr = node;
  3302. x->mode = Addressing_Invalid;
  3303. return;
  3304. }
  3305. if (x->mode != Addressing_Invalid) {
  3306. x->mode = Addressing_Value;
  3307. x->type = t_untyped_bool;
  3308. }
  3309. x->expr = node;
  3310. return;
  3311. }
  3312. default:
  3313. if (is_ise_expr(be->left)) {
  3314. // Evalute the right before the left for an '.X' expression
  3315. check_expr_or_type(c, y, be->right, type_hint);
  3316. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3317. check_expr_or_type(c, x, be->left, y->type);
  3318. } else {
  3319. check_expr_with_type_hint(c, x, be->left, type_hint);
  3320. }
  3321. } else {
  3322. check_expr_with_type_hint(c, x, be->left, type_hint);
  3323. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3324. check_expr_with_type_hint(c, y, be->right, x->type);
  3325. } else {
  3326. check_expr_with_type_hint(c, y, be->right, type_hint);
  3327. }
  3328. }
  3329. break;
  3330. }
  3331. if (x->mode == Addressing_Invalid) {
  3332. return;
  3333. }
  3334. if (y->mode == Addressing_Invalid) {
  3335. x->mode = Addressing_Invalid;
  3336. x->expr = y->expr;
  3337. return;
  3338. }
  3339. if (x->mode == Addressing_Builtin) {
  3340. x->mode = Addressing_Invalid;
  3341. error(x->expr, "built-in expression in binary expression");
  3342. return;
  3343. }
  3344. if (y->mode == Addressing_Builtin) {
  3345. x->mode = Addressing_Invalid;
  3346. error(y->expr, "built-in expression in binary expression");
  3347. return;
  3348. }
  3349. if (x->mode == Addressing_ProcGroup) {
  3350. x->mode = Addressing_Invalid;
  3351. if (x->proc_group != nullptr) {
  3352. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3353. } else {
  3354. error(x->expr, "procedure group used in binary expression");
  3355. }
  3356. return;
  3357. }
  3358. if (y->mode == Addressing_ProcGroup) {
  3359. x->mode = Addressing_Invalid;
  3360. if (x->proc_group != nullptr) {
  3361. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3362. } else {
  3363. error(y->expr, "procedure group used in binary expression");
  3364. }
  3365. return;
  3366. }
  3367. if (token_is_shift(op.kind)) {
  3368. check_shift(c, x, y, node, type_hint);
  3369. return;
  3370. }
  3371. switch (op.kind) {
  3372. case Token_Quo:
  3373. case Token_Mod:
  3374. case Token_ModMod:
  3375. case Token_QuoEq:
  3376. case Token_ModEq:
  3377. case Token_ModModEq:
  3378. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3379. is_type_float(x->type) && is_type_untyped(x->type)) {
  3380. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3381. gbString t = type_to_string(y->type);
  3382. if (x->value.kind != ExactValue_Invalid) {
  3383. gbString s = exact_value_to_string(x->value);
  3384. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3385. gb_string_free(s);
  3386. } else {
  3387. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3388. }
  3389. gb_string_free(t);
  3390. }
  3391. break;
  3392. }
  3393. convert_to_typed(c, x, y->type);
  3394. if (x->mode == Addressing_Invalid) {
  3395. return;
  3396. }
  3397. convert_to_typed(c, y, x->type);
  3398. if (y->mode == Addressing_Invalid) {
  3399. x->mode = Addressing_Invalid;
  3400. return;
  3401. }
  3402. if (token_is_comparison(op.kind)) {
  3403. check_comparison(c, node, x, y, op.kind);
  3404. return;
  3405. }
  3406. if (check_binary_array_expr(c, op, x, y)) {
  3407. x->mode = Addressing_Value;
  3408. x->type = x->type;
  3409. return;
  3410. }
  3411. if (check_binary_array_expr(c, op, y, x)) {
  3412. x->mode = Addressing_Value;
  3413. x->type = y->type;
  3414. return;
  3415. }
  3416. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3417. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3418. x->expr = node;
  3419. return;
  3420. }
  3421. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3422. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3423. // NOTE(bill, 2022-06-26)
  3424. // Allow any boolean types within `&&` and `||`
  3425. // This is an exception to all other binary expressions since the result
  3426. // of a comparison will always be an untyped boolean, and allowing
  3427. // any boolean between these two simplifies a lot of expressions
  3428. } else if (!are_types_identical(x->type, y->type)) {
  3429. if (x->type != t_invalid &&
  3430. y->type != t_invalid) {
  3431. gbString xt = type_to_string(x->type);
  3432. gbString yt = type_to_string(y->type);
  3433. gbString expr_str = expr_to_string(node);
  3434. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3435. gb_string_free(expr_str);
  3436. gb_string_free(yt);
  3437. gb_string_free(xt);
  3438. }
  3439. x->mode = Addressing_Invalid;
  3440. return;
  3441. }
  3442. if (!check_binary_op(c, x, op)) {
  3443. x->mode = Addressing_Invalid;
  3444. return;
  3445. }
  3446. switch (op.kind) {
  3447. case Token_Quo:
  3448. case Token_Mod:
  3449. case Token_ModMod:
  3450. case Token_QuoEq:
  3451. case Token_ModEq:
  3452. case Token_ModModEq:
  3453. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3454. y->mode == Addressing_Constant) {
  3455. bool fail = false;
  3456. switch (y->value.kind) {
  3457. case ExactValue_Integer:
  3458. if (big_int_is_zero(&y->value.value_integer)) {
  3459. fail = true;
  3460. }
  3461. break;
  3462. case ExactValue_Float:
  3463. if (y->value.value_float == 0.0) {
  3464. fail = true;
  3465. }
  3466. break;
  3467. }
  3468. if (fail) {
  3469. error(y->expr, "Division by zero not allowed");
  3470. x->mode = Addressing_Invalid;
  3471. return;
  3472. }
  3473. }
  3474. break;
  3475. case Token_CmpAnd:
  3476. case Token_CmpOr:
  3477. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3478. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3479. }
  3480. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3481. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3482. }
  3483. break;
  3484. }
  3485. if (x->mode == Addressing_Constant &&
  3486. y->mode == Addressing_Constant) {
  3487. ExactValue a = x->value;
  3488. ExactValue b = y->value;
  3489. if (!is_type_constant_type(x->type)) {
  3490. x->mode = Addressing_Value;
  3491. return;
  3492. }
  3493. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3494. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3495. }
  3496. if (is_type_bit_set(x->type)) {
  3497. switch (op.kind) {
  3498. case Token_Add: op.kind = Token_Or; break;
  3499. case Token_Sub: op.kind = Token_AndNot; break;
  3500. }
  3501. }
  3502. x->value = exact_binary_operator_value(op.kind, a, b);
  3503. if (is_type_typed(x->type)) {
  3504. if (node != nullptr) {
  3505. x->expr = node;
  3506. }
  3507. check_is_expressible(c, x, x->type);
  3508. }
  3509. return;
  3510. } else if (is_type_string(x->type)) {
  3511. error(node, "String concatenation is only allowed with constant strings");
  3512. x->mode = Addressing_Invalid;
  3513. return;
  3514. }
  3515. bool REQUIRE = true;
  3516. Type *bt = base_type(x->type);
  3517. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3518. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3519. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3520. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3521. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3522. }
  3523. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3524. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3525. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3526. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3527. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3528. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3529. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3530. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3531. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3532. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3533. }
  3534. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3535. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3536. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3537. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3538. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3539. case Basic_u128:
  3540. case Basic_i128:
  3541. if (is_arch_wasm()) {
  3542. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3543. }
  3544. break;
  3545. }
  3546. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3547. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3548. case Basic_u128:
  3549. case Basic_i128:
  3550. if (is_arch_wasm()) {
  3551. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3552. }
  3553. break;
  3554. }
  3555. }
  3556. x->mode = Addressing_Value;
  3557. }
  3558. gb_internal Operand make_operand_from_node(Ast *node) {
  3559. GB_ASSERT(node != nullptr);
  3560. Operand x = {};
  3561. x.expr = node;
  3562. x.mode = node->tav.mode;
  3563. x.type = node->tav.type;
  3564. x.value = node->tav.value;
  3565. return x;
  3566. }
  3567. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3568. GB_ASSERT(e != nullptr);
  3569. ExprInfo *old = check_get_expr_info(c, e);
  3570. if (old == nullptr) {
  3571. if (type != nullptr && type != t_invalid) {
  3572. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3573. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3574. if (e->kind == Ast_TernaryIfExpr) {
  3575. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3576. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3577. }
  3578. }
  3579. }
  3580. return;
  3581. }
  3582. switch (e->kind) {
  3583. case_ast_node(ue, UnaryExpr, e);
  3584. if (old->value.kind != ExactValue_Invalid) {
  3585. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3586. // They don't need to be updated as they will be updated later and
  3587. // checked at the end of general checking stage.
  3588. break;
  3589. }
  3590. update_untyped_expr_type(c, ue->expr, type, final);
  3591. case_end;
  3592. case_ast_node(be, BinaryExpr, e);
  3593. if (old->value.kind != ExactValue_Invalid) {
  3594. // See above note in UnaryExpr case
  3595. break;
  3596. }
  3597. if (token_is_comparison(be->op.kind)) {
  3598. // NOTE(bill): Do nothing as the types are fine
  3599. } else if (token_is_shift(be->op.kind)) {
  3600. update_untyped_expr_type(c, be->left, type, final);
  3601. } else {
  3602. update_untyped_expr_type(c, be->left, type, final);
  3603. update_untyped_expr_type(c, be->right, type, final);
  3604. }
  3605. case_end;
  3606. case_ast_node(te, TernaryIfExpr, e);
  3607. if (old->value.kind != ExactValue_Invalid) {
  3608. // See above note in UnaryExpr case
  3609. break;
  3610. }
  3611. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3612. // having an untyped value
  3613. Operand x = make_operand_from_node(te->x);
  3614. Operand y = make_operand_from_node(te->y);
  3615. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3616. update_untyped_expr_type(c, te->x, type, final);
  3617. }
  3618. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3619. update_untyped_expr_type(c, te->y, type, final);
  3620. }
  3621. case_end;
  3622. case_ast_node(te, TernaryWhenExpr, e);
  3623. if (old->value.kind != ExactValue_Invalid) {
  3624. // See above note in UnaryExpr case
  3625. break;
  3626. }
  3627. update_untyped_expr_type(c, te->x, type, final);
  3628. update_untyped_expr_type(c, te->y, type, final);
  3629. case_end;
  3630. case_ast_node(ore, OrReturnExpr, e);
  3631. if (old->value.kind != ExactValue_Invalid) {
  3632. // See above note in UnaryExpr case
  3633. break;
  3634. }
  3635. update_untyped_expr_type(c, ore->expr, type, final);
  3636. case_end;
  3637. case_ast_node(obe, OrBranchExpr, e);
  3638. if (old->value.kind != ExactValue_Invalid) {
  3639. // See above note in UnaryExpr case
  3640. break;
  3641. }
  3642. update_untyped_expr_type(c, obe->expr, type, final);
  3643. case_end;
  3644. case_ast_node(oee, OrElseExpr, e);
  3645. if (old->value.kind != ExactValue_Invalid) {
  3646. // See above note in UnaryExpr case
  3647. break;
  3648. }
  3649. update_untyped_expr_type(c, oee->x, type, final);
  3650. update_untyped_expr_type(c, oee->y, type, final);
  3651. case_end;
  3652. case_ast_node(pe, ParenExpr, e);
  3653. update_untyped_expr_type(c, pe->expr, type, final);
  3654. case_end;
  3655. }
  3656. if (!final && is_type_untyped(type)) {
  3657. old->type = base_type(type);
  3658. return;
  3659. }
  3660. // We need to remove it and then give it a new one
  3661. check_remove_expr_info(c, e);
  3662. if (old->is_lhs && !is_type_integer(type)) {
  3663. gbString expr_str = expr_to_string(e);
  3664. gbString type_str = type_to_string(type);
  3665. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3666. gb_string_free(type_str);
  3667. gb_string_free(expr_str);
  3668. return;
  3669. }
  3670. add_type_and_value(c, e, old->mode, type, old->value);
  3671. }
  3672. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3673. GB_ASSERT(e != nullptr);
  3674. ExprInfo *found = check_get_expr_info(c, e);
  3675. if (found) {
  3676. found->value = value;
  3677. }
  3678. }
  3679. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3680. gbString expr_str = expr_to_string(operand->expr);
  3681. gbString type_str = type_to_string(target_type);
  3682. gbString from_type_str = type_to_string(operand->type);
  3683. char const *extra_text = "";
  3684. if (operand->mode == Addressing_Constant) {
  3685. if (big_int_is_zero(&operand->value.value_integer)) {
  3686. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3687. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3688. extra_text = " - Did you want 'nil'?";
  3689. }
  3690. }
  3691. }
  3692. if (!ignore_error_block) {
  3693. begin_error_block();
  3694. }
  3695. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3696. if (operand->value.kind == ExactValue_String) {
  3697. String key = operand->value.value_string;
  3698. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3699. Type *et = base_type(target_type);
  3700. check_did_you_mean_type(key, et->Enum.fields, ".");
  3701. }
  3702. }
  3703. gb_string_free(from_type_str);
  3704. gb_string_free(type_str);
  3705. gb_string_free(expr_str);
  3706. operand->mode = Addressing_Invalid;
  3707. if (!ignore_error_block) {
  3708. end_error_block();
  3709. }
  3710. }
  3711. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3712. Type *t = core_type(type);
  3713. if (is_type_boolean(t)) {
  3714. // v = exact_value_to_boolean(v);
  3715. } else if (is_type_float(t)) {
  3716. v = exact_value_to_float(v);
  3717. } else if (is_type_integer(t)) {
  3718. v = exact_value_to_integer(v);
  3719. } else if (is_type_pointer(t)) {
  3720. v = exact_value_to_integer(v);
  3721. } else if (is_type_complex(t)) {
  3722. v = exact_value_to_complex(v);
  3723. } else if (is_type_quaternion(t)) {
  3724. v = exact_value_to_quaternion(v);
  3725. }
  3726. return v;
  3727. }
  3728. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3729. GB_ASSERT_NOT_NULL(target_type);
  3730. if (operand->mode == Addressing_Invalid ||
  3731. operand->mode == Addressing_Type ||
  3732. is_type_typed(operand->type) ||
  3733. target_type == t_invalid) {
  3734. return;
  3735. }
  3736. if (is_type_untyped(target_type)) {
  3737. GB_ASSERT(operand->type->kind == Type_Basic);
  3738. GB_ASSERT(target_type->kind == Type_Basic);
  3739. BasicKind x_kind = operand->type->Basic.kind;
  3740. BasicKind y_kind = target_type->Basic.kind;
  3741. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3742. if (x_kind < y_kind) {
  3743. operand->type = target_type;
  3744. update_untyped_expr_type(c, operand->expr, target_type, false);
  3745. }
  3746. } else if (x_kind != y_kind) {
  3747. operand->mode = Addressing_Invalid;
  3748. convert_untyped_error(c, operand, target_type);
  3749. return;
  3750. }
  3751. return;
  3752. }
  3753. Type *t = base_type(target_type);
  3754. if (c->in_enum_type) {
  3755. t = core_type(target_type);
  3756. }
  3757. switch (t->kind) {
  3758. case Type_Basic:
  3759. if (operand->mode == Addressing_Constant) {
  3760. check_is_expressible(c, operand, t);
  3761. if (operand->mode == Addressing_Invalid) {
  3762. return;
  3763. }
  3764. update_untyped_expr_value(c, operand->expr, operand->value);
  3765. } else {
  3766. switch (operand->type->Basic.kind) {
  3767. case Basic_UntypedBool:
  3768. if (!is_type_boolean(target_type) &&
  3769. !is_type_integer(target_type)) {
  3770. operand->mode = Addressing_Invalid;
  3771. convert_untyped_error(c, operand, target_type);
  3772. return;
  3773. }
  3774. break;
  3775. case Basic_UntypedInteger:
  3776. case Basic_UntypedFloat:
  3777. case Basic_UntypedComplex:
  3778. case Basic_UntypedQuaternion:
  3779. case Basic_UntypedRune:
  3780. if (!is_type_numeric(target_type)) {
  3781. operand->mode = Addressing_Invalid;
  3782. convert_untyped_error(c, operand, target_type);
  3783. return;
  3784. }
  3785. break;
  3786. case Basic_UntypedNil:
  3787. if (is_type_any(target_type)) {
  3788. // target_type = t_untyped_nil;
  3789. } else if (is_type_cstring(target_type)) {
  3790. // target_type = t_untyped_nil;
  3791. } else if (!type_has_nil(target_type)) {
  3792. operand->mode = Addressing_Invalid;
  3793. convert_untyped_error(c, operand, target_type);
  3794. return;
  3795. }
  3796. break;
  3797. }
  3798. }
  3799. break;
  3800. case Type_Array: {
  3801. Type *elem = base_array_type(t);
  3802. if (check_is_assignable_to(c, operand, elem)) {
  3803. operand->mode = Addressing_Value;
  3804. } else {
  3805. if (operand->value.kind == ExactValue_String) {
  3806. String s = operand->value.value_string;
  3807. if (is_type_u8_array(t)) {
  3808. if (s.len == t->Array.count) {
  3809. break;
  3810. }
  3811. } else if (is_type_rune_array(t)) {
  3812. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3813. if (rune_count == t->Array.count) {
  3814. break;
  3815. }
  3816. }
  3817. }
  3818. operand->mode = Addressing_Invalid;
  3819. convert_untyped_error(c, operand, target_type);
  3820. return;
  3821. }
  3822. break;
  3823. }
  3824. case Type_Matrix: {
  3825. Type *elem = base_array_type(t);
  3826. if (check_is_assignable_to(c, operand, elem)) {
  3827. if (t->Matrix.row_count != t->Matrix.column_count) {
  3828. operand->mode = Addressing_Invalid;
  3829. ERROR_BLOCK();
  3830. convert_untyped_error(c, operand, target_type, true);
  3831. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3832. return;
  3833. } else {
  3834. operand->mode = Addressing_Value;
  3835. }
  3836. } else {
  3837. operand->mode = Addressing_Invalid;
  3838. convert_untyped_error(c, operand, target_type);
  3839. return;
  3840. }
  3841. break;
  3842. }
  3843. case Type_Union:
  3844. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3845. TEMPORARY_ALLOCATOR_GUARD();
  3846. isize count = t->Union.variants.count;
  3847. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3848. isize valid_count = 0;
  3849. isize first_success_index = -1;
  3850. for_array(i, t->Union.variants) {
  3851. Type *vt = t->Union.variants[i];
  3852. i64 score = 0;
  3853. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3854. valids[valid_count].index = i;
  3855. valids[valid_count].score = score;
  3856. valid_count += 1;
  3857. if (first_success_index < 0) {
  3858. first_success_index = i;
  3859. }
  3860. }
  3861. }
  3862. if (valid_count > 1) {
  3863. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3864. i64 best_score = valids[0].score;
  3865. for (isize i = 1; i < valid_count; i++) {
  3866. auto v = valids[i];
  3867. if (best_score > v.score) {
  3868. valid_count = i;
  3869. break;
  3870. }
  3871. best_score = v.score;
  3872. }
  3873. first_success_index = valids[0].index;
  3874. }
  3875. gbString type_str = type_to_string(target_type);
  3876. defer (gb_string_free(type_str));
  3877. if (valid_count == 1) {
  3878. operand->mode = Addressing_Value;
  3879. operand->type = t->Union.variants[first_success_index];
  3880. target_type = t->Union.variants[first_success_index];
  3881. break;
  3882. } else if (valid_count > 1) {
  3883. ERROR_BLOCK();
  3884. GB_ASSERT(first_success_index >= 0);
  3885. operand->mode = Addressing_Invalid;
  3886. convert_untyped_error(c, operand, target_type, true);
  3887. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3888. i32 j = 0;
  3889. for (i32 i = 0; i < valid_count; i++) {
  3890. ValidIndexAndScore valid = valids[i];
  3891. if (j > 0 && valid_count > 2) error_line(", ");
  3892. if (j == valid_count-1) {
  3893. if (valid_count == 2) error_line(" ");
  3894. error_line("or ");
  3895. }
  3896. gbString str = type_to_string(t->Union.variants[valid.index]);
  3897. error_line("'%s'", str);
  3898. gb_string_free(str);
  3899. j++;
  3900. }
  3901. error_line("\n\n");
  3902. return;
  3903. } else if (is_type_untyped_uninit(operand->type)) {
  3904. target_type = t_untyped_uninit;
  3905. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3906. ERROR_BLOCK();
  3907. operand->mode = Addressing_Invalid;
  3908. convert_untyped_error(c, operand, target_type, true);
  3909. if (count > 0) {
  3910. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3911. error_line("\t");
  3912. for (i32 i = 0; i < count; i++) {
  3913. Type *v = t->Union.variants[i];
  3914. if (i > 0 && count > 2) error_line(", ");
  3915. if (i == count-1) {
  3916. if (count == 2) error_line(" ");
  3917. if (count > 1) {
  3918. error_line("or ");
  3919. }
  3920. }
  3921. gbString str = type_to_string(v);
  3922. error_line("'%s'", str);
  3923. gb_string_free(str);
  3924. }
  3925. error_line("\n\n");
  3926. }
  3927. return;
  3928. }
  3929. }
  3930. /* fallthrough */
  3931. default:
  3932. if (is_type_untyped_uninit(operand->type)) {
  3933. target_type = t_untyped_uninit;
  3934. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3935. target_type = t_untyped_nil;
  3936. } else {
  3937. operand->mode = Addressing_Invalid;
  3938. convert_untyped_error(c, operand, target_type);
  3939. return;
  3940. }
  3941. break;
  3942. }
  3943. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3944. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3945. } else {
  3946. target_type = default_type(operand->type);
  3947. }
  3948. }
  3949. update_untyped_expr_type(c, operand->expr, target_type, true);
  3950. operand->type = target_type;
  3951. }
  3952. gb_internal bool check_index_value(CheckerContext *c, Type *main_type, bool open_range, Ast *index_value, i64 max_count, i64 *value, Type *type_hint=nullptr) {
  3953. Operand operand = {Addressing_Invalid};
  3954. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3955. if (operand.mode == Addressing_Invalid) {
  3956. if (value) *value = 0;
  3957. return false;
  3958. }
  3959. Type *index_type = t_int;
  3960. if (type_hint != nullptr) {
  3961. index_type = type_hint;
  3962. }
  3963. convert_to_typed(c, &operand, index_type);
  3964. if (operand.mode == Addressing_Invalid) {
  3965. if (value) *value = 0;
  3966. return false;
  3967. }
  3968. if (type_hint != nullptr) {
  3969. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3970. gbString expr_str = expr_to_string(operand.expr);
  3971. gbString index_type_str = type_to_string(type_hint);
  3972. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3973. gb_string_free(index_type_str);
  3974. gb_string_free(expr_str);
  3975. if (value) *value = 0;
  3976. return false;
  3977. }
  3978. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3979. gbString expr_str = expr_to_string(operand.expr);
  3980. gbString type_str = type_to_string(operand.type);
  3981. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3982. gb_string_free(type_str);
  3983. gb_string_free(expr_str);
  3984. if (value) *value = 0;
  3985. return false;
  3986. }
  3987. if (operand.mode == Addressing_Constant &&
  3988. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3989. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3990. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3991. TEMPORARY_ALLOCATOR_GUARD();
  3992. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3993. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3994. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3995. if (value) *value = 0;
  3996. return false;
  3997. }
  3998. if (max_count >= 0) {
  3999. if (is_type_enum(index_type)) {
  4000. Type *bt = base_type(index_type);
  4001. GB_ASSERT(bt->kind == Type_Enum);
  4002. ExactValue const &lo = *bt->Enum.min_value;
  4003. ExactValue const &hi = *bt->Enum.max_value;
  4004. String lo_str = {};
  4005. String hi_str = {};
  4006. if (bt->Enum.fields.count > 0) {
  4007. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4008. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4009. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4010. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4011. }
  4012. bool out_of_bounds = false;
  4013. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4014. out_of_bounds = true;
  4015. }
  4016. if (out_of_bounds) {
  4017. gbString expr_str = expr_to_string(operand.expr);
  4018. if (lo_str.len > 0) {
  4019. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4020. } else {
  4021. gbString index_type_str = type_to_string(index_type);
  4022. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4023. gb_string_free(index_type_str);
  4024. }
  4025. gb_string_free(expr_str);
  4026. return false;
  4027. }
  4028. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4029. return true;
  4030. } else { // NOTE(bill): Do array bound checking
  4031. i64 v = -1;
  4032. if (i.used <= 1) {
  4033. v = big_int_to_i64(&i);
  4034. }
  4035. if (value) *value = v;
  4036. bool out_of_bounds = false;
  4037. if (v < 0) {
  4038. out_of_bounds = true;
  4039. } else if (open_range) {
  4040. out_of_bounds = v > max_count;
  4041. } else {
  4042. out_of_bounds = v >= max_count;
  4043. }
  4044. if (out_of_bounds) {
  4045. TEMPORARY_ALLOCATOR_GUARD();
  4046. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4047. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4048. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4049. return false;
  4050. }
  4051. return true;
  4052. }
  4053. } else {
  4054. if (value) *value = exact_value_to_i64(operand.value);
  4055. return true;
  4056. }
  4057. }
  4058. // NOTE(bill): It's alright :D
  4059. if (value) *value = -1;
  4060. return true;
  4061. }
  4062. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4063. if (value.kind == ExactValue_String) {
  4064. GB_ASSERT(0 <= index && index < value.value_string.len);
  4065. u8 val = value.value_string[index];
  4066. if (success_) *success_ = true;
  4067. if (finish_) *finish_ = true;
  4068. return exact_value_u64(val);
  4069. }
  4070. if (value.kind != ExactValue_Compound) {
  4071. if (success_) *success_ = true;
  4072. if (finish_) *finish_ = true;
  4073. return value;
  4074. }
  4075. Ast *node = value.value_compound;
  4076. switch (node->kind) {
  4077. case_ast_node(cl, CompoundLit, node);
  4078. if (cl->elems.count == 0) {
  4079. if (success_) *success_ = true;
  4080. if (finish_) *finish_ = true;
  4081. return empty_exact_value;
  4082. }
  4083. if (cl->elems[0]->kind == Ast_FieldValue) {
  4084. if (is_type_struct(node->tav.type)) {
  4085. bool found = false;
  4086. for (Ast *elem : cl->elems) {
  4087. if (elem->kind != Ast_FieldValue) {
  4088. continue;
  4089. }
  4090. ast_node(fv, FieldValue, elem);
  4091. String name = fv->field->Ident.token.string;
  4092. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4093. defer (array_free(&sub_sel.index));
  4094. if (sub_sel.index.count > 0 &&
  4095. sub_sel.index[0] == index) {
  4096. value = fv->value->tav.value;
  4097. found = true;
  4098. break;
  4099. }
  4100. }
  4101. if (!found) {
  4102. // Use the zero value if it is not found
  4103. value = {};
  4104. }
  4105. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4106. for (Ast *elem : cl->elems) {
  4107. if (elem->kind != Ast_FieldValue) {
  4108. continue;
  4109. }
  4110. ast_node(fv, FieldValue, elem);
  4111. if (is_ast_range(fv->field)) {
  4112. ast_node(ie, BinaryExpr, fv->field);
  4113. TypeAndValue lo_tav = ie->left->tav;
  4114. TypeAndValue hi_tav = ie->right->tav;
  4115. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4116. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4117. TokenKind op = ie->op.kind;
  4118. i64 lo = exact_value_to_i64(lo_tav.value);
  4119. i64 hi = exact_value_to_i64(hi_tav.value);
  4120. i64 corrected_index = index;
  4121. if (is_type_enumerated_array(node->tav.type)) {
  4122. Type *bt = base_type(node->tav.type);
  4123. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4124. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4125. }
  4126. if (op != Token_RangeHalf) {
  4127. if (lo <= corrected_index && corrected_index <= hi) {
  4128. TypeAndValue tav = fv->value->tav;
  4129. if (success_) *success_ = true;
  4130. if (finish_) *finish_ = false;
  4131. return tav.value;
  4132. }
  4133. } else {
  4134. if (lo <= corrected_index && corrected_index < hi) {
  4135. TypeAndValue tav = fv->value->tav;
  4136. if (success_) *success_ = true;
  4137. if (finish_) *finish_ = false;
  4138. return tav.value;
  4139. }
  4140. }
  4141. } else {
  4142. TypeAndValue index_tav = fv->field->tav;
  4143. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4144. ExactValue index_value = index_tav.value;
  4145. if (is_type_enumerated_array(node->tav.type)) {
  4146. Type *bt = base_type(node->tav.type);
  4147. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4148. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4149. }
  4150. i64 field_index = exact_value_to_i64(index_value);
  4151. if (index == field_index) {
  4152. TypeAndValue tav = fv->value->tav;
  4153. if (success_) *success_ = true;
  4154. if (finish_) *finish_ = false;
  4155. return tav.value;;
  4156. }
  4157. }
  4158. }
  4159. }
  4160. } else {
  4161. i32 count = (i32)cl->elems.count;
  4162. if (count < index) {
  4163. if (success_) *success_ = false;
  4164. if (finish_) *finish_ = true;
  4165. return empty_exact_value;
  4166. }
  4167. if (cl->elems.count <= index) {
  4168. if (success_) *success_ = false;
  4169. if (finish_) *finish_ = false;
  4170. return value;
  4171. }
  4172. TypeAndValue tav = cl->elems[index]->tav;
  4173. if (tav.mode == Addressing_Constant) {
  4174. if (success_) *success_ = true;
  4175. if (finish_) *finish_ = false;
  4176. return tav.value;
  4177. } else {
  4178. GB_ASSERT(is_type_untyped_nil(tav.type));
  4179. if (success_) *success_ = true;
  4180. if (finish_) *finish_ = false;
  4181. return tav.value;
  4182. }
  4183. }
  4184. case_end;
  4185. default:
  4186. if (success_) *success_ = true;
  4187. if (finish_) *finish_ = true;
  4188. return empty_exact_value;
  4189. }
  4190. if (finish_) *finish_ = false;
  4191. return value;
  4192. }
  4193. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4194. if (operand->mode != Addressing_Constant) {
  4195. if (success_) *success_ = false;
  4196. return empty_exact_value;
  4197. }
  4198. if (sel.indirect) {
  4199. if (success_) *success_ = false;
  4200. return empty_exact_value;
  4201. }
  4202. if (sel.index.count == 0) {
  4203. if (success_) *success_ = false;
  4204. return empty_exact_value;
  4205. }
  4206. ExactValue value = operand->value;
  4207. if (value.kind == ExactValue_Compound) {
  4208. while (sel.index.count > 0) {
  4209. i32 index = sel.index[0];
  4210. sel = sub_selection(sel, 1);
  4211. bool finish = false;
  4212. value = get_constant_field_single(c, value, index, success_, &finish);
  4213. if (finish) {
  4214. return value;
  4215. }
  4216. }
  4217. if (success_) *success_ = true;
  4218. return value;
  4219. } else if (value.kind == ExactValue_Quaternion) {
  4220. // @QuaternionLayout
  4221. Quaternion256 q = *value.value_quaternion;
  4222. GB_ASSERT(sel.index.count == 1);
  4223. switch (sel.index[0]) {
  4224. case 3: // w
  4225. if (success_) *success_ = true;
  4226. return exact_value_float(q.real);
  4227. case 0: // x
  4228. if (success_) *success_ = true;
  4229. return exact_value_float(q.imag);
  4230. case 1: // y
  4231. if (success_) *success_ = true;
  4232. return exact_value_float(q.jmag);
  4233. case 2: // z
  4234. if (success_) *success_ = true;
  4235. return exact_value_float(q.kmag);
  4236. }
  4237. if (success_) *success_ = false;
  4238. return empty_exact_value;
  4239. } else if (value.kind == ExactValue_Complex) {
  4240. // @QuaternionLayout
  4241. Complex128 c = *value.value_complex;
  4242. GB_ASSERT(sel.index.count == 1);
  4243. switch (sel.index[0]) {
  4244. case 0: // real
  4245. if (success_) *success_ = true;
  4246. return exact_value_float(c.real);
  4247. case 1: // imag
  4248. if (success_) *success_ = true;
  4249. return exact_value_float(c.imag);
  4250. }
  4251. if (success_) *success_ = false;
  4252. return empty_exact_value;
  4253. }
  4254. if (success_) *success_ = true;
  4255. return empty_exact_value;
  4256. }
  4257. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4258. Type *array_type = base_type(type_deref(original_type));
  4259. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4260. if (array_type->kind == Type_SimdVector) {
  4261. Type *elem_type = array_type->SimdVector.elem;
  4262. return alloc_type_simd_vector(new_count, elem_type);
  4263. }
  4264. Type *elem_type = array_type->Array.elem;
  4265. Type *swizzle_array_type = nullptr;
  4266. Type *bth = base_type(type_deref(type_hint));
  4267. if (bth != nullptr && bth->kind == Type_Array &&
  4268. bth->Array.count == new_count &&
  4269. are_types_identical(bth->Array.elem, elem_type)) {
  4270. swizzle_array_type = type_hint;
  4271. } else {
  4272. i64 max_count = array_type->Array.count;
  4273. if (new_count == max_count) {
  4274. swizzle_array_type = original_type;
  4275. } else {
  4276. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4277. }
  4278. }
  4279. return swizzle_array_type;
  4280. }
  4281. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4282. bool is_declared = entity != nullptr;
  4283. if (is_declared) {
  4284. if (entity->kind == Entity_Builtin) {
  4285. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4286. // This means that we should just ignore the found result through it
  4287. *allow_builtin = entity->scope == import_scope ||
  4288. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4289. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4290. is_declared = false;
  4291. }
  4292. }
  4293. return is_declared;
  4294. }
  4295. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4296. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4297. if (node->kind == Ast_Ident) {
  4298. String name = node->Ident.token.string;
  4299. return scope_lookup(c->scope, name);
  4300. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4301. ast_node(se, SelectorExpr, node);
  4302. if (se->token.kind == Token_ArrowRight) {
  4303. return nullptr;
  4304. }
  4305. Ast *op_expr = se->expr;
  4306. Ast *selector = unparen_expr(se->selector);
  4307. if (selector == nullptr) {
  4308. return nullptr;
  4309. }
  4310. if (selector->kind != Ast_Ident) {
  4311. return nullptr;
  4312. }
  4313. Entity *entity = nullptr;
  4314. Entity *expr_entity = nullptr;
  4315. bool check_op_expr = true;
  4316. if (op_expr->kind == Ast_Ident) {
  4317. String op_name = op_expr->Ident.token.string;
  4318. Entity *e = scope_lookup(c->scope, op_name);
  4319. if (e == nullptr) {
  4320. return nullptr;
  4321. }
  4322. add_entity_use(c, op_expr, e);
  4323. expr_entity = e;
  4324. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4325. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4326. // It pretty much needs to be in this order and this way
  4327. // If you can clean this up, please do but be really careful
  4328. String import_name = op_name;
  4329. Scope *import_scope = e->ImportName.scope;
  4330. String entity_name = selector->Ident.token.string;
  4331. check_op_expr = false;
  4332. entity = scope_lookup_current(import_scope, entity_name);
  4333. bool allow_builtin = false;
  4334. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4335. return nullptr;
  4336. }
  4337. check_entity_decl(c, entity, nullptr, nullptr);
  4338. if (entity->kind == Entity_ProcGroup) {
  4339. return entity;
  4340. }
  4341. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4342. }
  4343. }
  4344. Operand operand = {};
  4345. if (check_op_expr) {
  4346. check_expr_base(c, &operand, op_expr, nullptr);
  4347. if (operand.mode == Addressing_Invalid) {
  4348. return nullptr;
  4349. }
  4350. }
  4351. if (entity == nullptr && selector->kind == Ast_Ident) {
  4352. String field_name = selector->Ident.token.string;
  4353. if (is_type_dynamic_array(type_deref(operand.type))) {
  4354. init_mem_allocator(c->checker);
  4355. }
  4356. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4357. entity = sel.entity;
  4358. }
  4359. if (entity != nullptr) {
  4360. return entity;
  4361. }
  4362. }
  4363. return nullptr;
  4364. }
  4365. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4366. ast_node(se, SelectorExpr, node);
  4367. bool check_op_expr = true;
  4368. Entity *expr_entity = nullptr;
  4369. Entity *entity = nullptr;
  4370. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4371. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4372. ERROR_BLOCK();
  4373. error(node, "Illegal use of -> selector shorthand outside of a call");
  4374. gbString x = expr_to_string(se->expr);
  4375. gbString y = expr_to_string(se->selector);
  4376. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4377. gb_string_free(y);
  4378. gb_string_free(x);
  4379. // TODO(bill): Should this terminate here or propagate onwards?
  4380. // operand->mode = Addressing_Invalid;
  4381. // operand->expr = node;
  4382. // return nullptr;
  4383. }
  4384. operand->expr = node;
  4385. Ast *op_expr = se->expr;
  4386. Ast *selector = unparen_expr(se->selector);
  4387. if (selector == nullptr) {
  4388. operand->mode = Addressing_Invalid;
  4389. operand->expr = node;
  4390. return nullptr;
  4391. }
  4392. if (selector->kind != Ast_Ident) {
  4393. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4394. operand->mode = Addressing_Invalid;
  4395. operand->expr = node;
  4396. return nullptr;
  4397. }
  4398. if (op_expr->kind == Ast_Ident) {
  4399. String op_name = op_expr->Ident.token.string;
  4400. Entity *e = scope_lookup(c->scope, op_name);
  4401. add_entity_use(c, op_expr, e);
  4402. expr_entity = e;
  4403. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4404. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4405. // It pretty much needs to be in this order and this way
  4406. // If you can clean this up, please do but be really careful
  4407. String import_name = op_name;
  4408. Scope *import_scope = e->ImportName.scope;
  4409. String entity_name = selector->Ident.token.string;
  4410. check_op_expr = false;
  4411. entity = scope_lookup_current(import_scope, entity_name);
  4412. bool allow_builtin = false;
  4413. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4414. ERROR_BLOCK();
  4415. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4416. operand->mode = Addressing_Invalid;
  4417. operand->expr = node;
  4418. check_did_you_mean_scope(entity_name, import_scope);
  4419. return nullptr;
  4420. }
  4421. check_entity_decl(c, entity, nullptr, nullptr);
  4422. if (entity->kind == Entity_ProcGroup) {
  4423. operand->mode = Addressing_ProcGroup;
  4424. operand->proc_group = entity;
  4425. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4426. return entity;
  4427. }
  4428. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4429. if (!is_entity_exported(entity, allow_builtin)) {
  4430. gbString sel_str = expr_to_string(selector);
  4431. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4432. gb_string_free(sel_str);
  4433. // NOTE(bill): make the state valid still, even if it's "invalid"
  4434. // operand->mode = Addressing_Invalid;
  4435. // operand->expr = node;
  4436. // return nullptr;
  4437. }
  4438. if (entity->kind == Entity_ProcGroup) {
  4439. Array<Entity *> procs = entity->ProcGroup.entities;
  4440. bool skip = false;
  4441. for (Entity *p : procs) {
  4442. Type *t = base_type(p->type);
  4443. if (t == t_invalid) {
  4444. continue;
  4445. }
  4446. Operand x = {};
  4447. x.mode = Addressing_Value;
  4448. x.type = t;
  4449. if (type_hint != nullptr) {
  4450. if (check_is_assignable_to(c, &x, type_hint)) {
  4451. entity = p;
  4452. skip = true;
  4453. break;
  4454. }
  4455. }
  4456. }
  4457. if (!skip) {
  4458. GB_ASSERT(entity != nullptr);
  4459. operand->mode = Addressing_ProcGroup;
  4460. operand->type = t_invalid;
  4461. operand->expr = node;
  4462. operand->proc_group = entity;
  4463. return entity;
  4464. }
  4465. }
  4466. }
  4467. }
  4468. if (check_op_expr) {
  4469. check_expr_base(c, operand, op_expr, nullptr);
  4470. if (operand->mode == Addressing_Invalid) {
  4471. operand->mode = Addressing_Invalid;
  4472. operand->expr = node;
  4473. return nullptr;
  4474. }
  4475. }
  4476. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4477. complete_soa_type(c->checker, type_deref(operand->type), false);
  4478. }
  4479. if (entity == nullptr && selector->kind == Ast_Ident) {
  4480. String field_name = selector->Ident.token.string;
  4481. Type *t = type_deref(operand->type);
  4482. if (t == nullptr) {
  4483. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4484. } else if (is_type_dynamic_array(t)) {
  4485. init_mem_allocator(c->checker);
  4486. }
  4487. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4488. entity = sel.entity;
  4489. // NOTE(bill): Add type info needed for fields like 'names'
  4490. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4491. add_type_info_type(c, operand->type);
  4492. }
  4493. if (is_type_enum(operand->type)) {
  4494. add_type_info_type(c, operand->type);
  4495. }
  4496. }
  4497. if (entity == nullptr && selector->kind == Ast_Ident && (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4498. String field_name = selector->Ident.token.string;
  4499. if (1 < field_name.len && field_name.len <= 4) {
  4500. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4501. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4502. bool found_xyzw = false;
  4503. bool found_rgba = false;
  4504. for (isize i = 0; i < field_name.len; i++) {
  4505. bool valid = false;
  4506. for (isize j = 0; j < 4; j++) {
  4507. if (field_name.text[i] == swizzles_xyzw[j]) {
  4508. found_xyzw = true;
  4509. valid = true;
  4510. break;
  4511. }
  4512. if (field_name.text[i] == swizzles_rgba[j]) {
  4513. found_rgba = true;
  4514. valid = true;
  4515. break;
  4516. }
  4517. }
  4518. if (!valid) {
  4519. goto end_of_array_selector_swizzle;
  4520. }
  4521. }
  4522. u8 *swizzles = nullptr;
  4523. u8 index_count = cast(u8)field_name.len;
  4524. if (found_xyzw && found_rgba) {
  4525. gbString op_str = expr_to_string(op_expr);
  4526. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4527. gb_string_free(op_str);
  4528. operand->mode = Addressing_Invalid;
  4529. operand->expr = node;
  4530. return nullptr;
  4531. }
  4532. u8 indices = 0;
  4533. if (found_xyzw) {
  4534. swizzles = swizzles_xyzw;
  4535. } else if (found_rgba) {
  4536. swizzles = swizzles_rgba;
  4537. }
  4538. for (isize i = 0; i < field_name.len; i++) {
  4539. for (isize j = 0; j < 4; j++) {
  4540. if (field_name.text[i] == swizzles[j]) {
  4541. indices |= cast(u8)(j)<<(i*2);
  4542. break;
  4543. }
  4544. }
  4545. }
  4546. Type *original_type = operand->type;
  4547. Type *array_type = base_type(type_deref(original_type));
  4548. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4549. i64 array_count = get_array_type_count(array_type);
  4550. for (u8 i = 0; i < index_count; i++) {
  4551. u8 idx = indices>>(i*2) & 3;
  4552. if (idx >= array_count) {
  4553. char c = 0;
  4554. if (found_xyzw) {
  4555. c = swizzles_xyzw[idx];
  4556. } else if (found_rgba) {
  4557. c = swizzles_rgba[idx];
  4558. } else {
  4559. GB_PANIC("unknown swizzle kind");
  4560. }
  4561. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4562. break;
  4563. }
  4564. }
  4565. se->swizzle_count = index_count;
  4566. se->swizzle_indices = indices;
  4567. AddressingMode prev_mode = operand->mode;
  4568. operand->mode = Addressing_SwizzleValue;
  4569. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4570. operand->expr = node;
  4571. switch (prev_mode) {
  4572. case Addressing_Variable:
  4573. case Addressing_SoaVariable:
  4574. case Addressing_SwizzleVariable:
  4575. operand->mode = Addressing_SwizzleVariable;
  4576. break;
  4577. }
  4578. if (array_type->kind == Type_SimdVector) {
  4579. operand->mode = Addressing_Value;
  4580. }
  4581. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4582. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4583. return swizzle_entity;
  4584. }
  4585. end_of_array_selector_swizzle:;
  4586. }
  4587. if (entity == nullptr) {
  4588. gbString op_str = expr_to_string(op_expr);
  4589. gbString type_str = type_to_string_shorthand(operand->type);
  4590. gbString sel_str = expr_to_string(selector);
  4591. if (operand->mode == Addressing_Type) {
  4592. if (is_type_polymorphic(operand->type, true)) {
  4593. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4594. } else {
  4595. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4596. }
  4597. } else {
  4598. ERROR_BLOCK();
  4599. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4600. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4601. String const &name = selector->Ident.token.string;
  4602. Type *bt = base_type(operand->type);
  4603. if (operand->type->kind == Type_Named &&
  4604. operand->type->Named.type_name &&
  4605. operand->type->Named.type_name->kind == Entity_TypeName &&
  4606. operand->type->Named.type_name->TypeName.objc_metadata) {
  4607. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4608. } else if (bt->kind == Type_Struct) {
  4609. check_did_you_mean_type(name, bt->Struct.fields);
  4610. } else if (bt->kind == Type_Enum) {
  4611. check_did_you_mean_type(name, bt->Enum.fields);
  4612. }
  4613. }
  4614. }
  4615. gb_string_free(sel_str);
  4616. gb_string_free(type_str);
  4617. gb_string_free(op_str);
  4618. operand->mode = Addressing_Invalid;
  4619. operand->expr = node;
  4620. return nullptr;
  4621. }
  4622. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4623. bool success = false;
  4624. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4625. if (success) {
  4626. operand->mode = Addressing_Constant;
  4627. operand->expr = node;
  4628. operand->value = field_value;
  4629. operand->type = entity->type;
  4630. add_entity_use(c, selector, entity);
  4631. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4632. return entity;
  4633. }
  4634. gbString op_str = expr_to_string(op_expr);
  4635. gbString type_str = type_to_string_shorthand(operand->type);
  4636. gbString sel_str = expr_to_string(selector);
  4637. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4638. gb_string_free(sel_str);
  4639. gb_string_free(type_str);
  4640. gb_string_free(op_str);
  4641. operand->mode = Addressing_Invalid;
  4642. operand->expr = node;
  4643. return nullptr;
  4644. }
  4645. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4646. bool success = false;
  4647. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4648. if (success) {
  4649. operand->mode = Addressing_Constant;
  4650. operand->expr = node;
  4651. operand->value = field_value;
  4652. operand->type = entity->type;
  4653. add_entity_use(c, selector, entity);
  4654. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4655. return entity;
  4656. }
  4657. gbString op_str = expr_to_string(op_expr);
  4658. gbString type_str = type_to_string_shorthand(operand->type);
  4659. gbString sel_str = expr_to_string(selector);
  4660. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4661. gb_string_free(sel_str);
  4662. gb_string_free(type_str);
  4663. gb_string_free(op_str);
  4664. operand->mode = Addressing_Invalid;
  4665. operand->expr = node;
  4666. return nullptr;
  4667. }
  4668. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4669. gbString op_str = expr_to_string(op_expr);
  4670. gbString type_str = type_to_string_shorthand(operand->type);
  4671. gbString sel_str = expr_to_string(selector);
  4672. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4673. gb_string_free(sel_str);
  4674. gb_string_free(type_str);
  4675. gb_string_free(op_str);
  4676. operand->mode = Addressing_Invalid;
  4677. operand->expr = node;
  4678. return nullptr;
  4679. }
  4680. add_entity_use(c, selector, entity);
  4681. operand->type = entity->type;
  4682. operand->expr = node;
  4683. if (entity->flags & EntityFlag_BitFieldField) {
  4684. add_package_dependency(c, "runtime", "__write_bits");
  4685. add_package_dependency(c, "runtime", "__read_bits");
  4686. }
  4687. switch (entity->kind) {
  4688. case Entity_Constant:
  4689. operand->value = entity->Constant.value;
  4690. operand->mode = Addressing_Constant;
  4691. if (operand->value.kind == ExactValue_Procedure) {
  4692. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4693. if (proc != nullptr) {
  4694. operand->mode = Addressing_Value;
  4695. operand->type = proc->type;
  4696. }
  4697. }
  4698. break;
  4699. case Entity_Variable:
  4700. if (sel.is_bit_field) {
  4701. se->is_bit_field = true;
  4702. }
  4703. if (sel.indirect) {
  4704. operand->mode = Addressing_Variable;
  4705. } else if (operand->mode == Addressing_Context) {
  4706. // Do nothing
  4707. } else if (operand->mode == Addressing_MapIndex) {
  4708. operand->mode = Addressing_Value;
  4709. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4710. operand->mode = Addressing_SoaVariable;
  4711. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4712. operand->mode = Addressing_Value;
  4713. } else if (operand->mode == Addressing_SoaVariable) {
  4714. operand->mode = Addressing_Variable;
  4715. } else if (operand->mode != Addressing_Value) {
  4716. operand->mode = Addressing_Variable;
  4717. } else {
  4718. operand->mode = Addressing_Value;
  4719. }
  4720. break;
  4721. case Entity_TypeName:
  4722. operand->mode = Addressing_Type;
  4723. break;
  4724. case Entity_Procedure:
  4725. operand->mode = Addressing_Value;
  4726. operand->value = exact_value_procedure(node);
  4727. break;
  4728. case Entity_Builtin:
  4729. operand->mode = Addressing_Builtin;
  4730. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4731. break;
  4732. case Entity_ProcGroup:
  4733. operand->mode = Addressing_ProcGroup;
  4734. operand->proc_group = entity;
  4735. break;
  4736. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4737. case Entity_Nil:
  4738. operand->mode = Addressing_Value;
  4739. break;
  4740. }
  4741. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4742. return entity;
  4743. }
  4744. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4745. ptr = base_type(ptr);
  4746. if (is_type_pointer(ptr)) {
  4747. if (is_type_rawptr(ptr)) {
  4748. return false;
  4749. }
  4750. if (elem) *elem = ptr->Pointer.elem;
  4751. return true;
  4752. }
  4753. return false;
  4754. }
  4755. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4756. elem = core_type(elem);
  4757. if (is_type_internally_pointer_like(elem)) {
  4758. return true;
  4759. }
  4760. if (elem->kind == Type_BitSet) {
  4761. elem = bit_set_to_int(elem);
  4762. }
  4763. if (elem->kind != Type_Basic) {
  4764. return false;
  4765. }
  4766. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4767. }
  4768. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4769. switch (node->kind) {
  4770. case_ast_node(i, Ident, node);
  4771. String name = i->token.string;
  4772. if (nested) {
  4773. Entity *e = scope_lookup_current(s, name);
  4774. if (e != nullptr) {
  4775. if (out_scope) *out_scope = e->scope;
  4776. return true;
  4777. }
  4778. } else {
  4779. Entity *e = scope_lookup(s, name);
  4780. if (e != nullptr) {
  4781. if (out_scope) *out_scope = e->scope;
  4782. return true;
  4783. }
  4784. }
  4785. case_end;
  4786. case_ast_node(se, SelectorExpr, node);
  4787. Ast *lhs = se->expr;
  4788. Ast *rhs = se->selector;
  4789. Scope *lhs_scope = nullptr;
  4790. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4791. return check_identifier_exists(lhs_scope, rhs, true);
  4792. }
  4793. case_end;
  4794. }
  4795. return false;
  4796. }
  4797. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4798. if (o.type && is_type_no_copy(o.type)) {
  4799. Ast *expr = unparen_expr(o.expr);
  4800. if (expr && o.mode != Addressing_Constant) {
  4801. if (expr->kind == Ast_CallExpr) {
  4802. // Okay
  4803. } else {
  4804. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4805. return true;
  4806. }
  4807. }
  4808. }
  4809. return false;
  4810. }
  4811. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4812. bool optional_ok = false;
  4813. isize tuple_index = 0;
  4814. for (Ast *rhs_expr : rhs) {
  4815. CheckerContext c_ = *ctx;
  4816. CheckerContext *c = &c_;
  4817. Operand o = {};
  4818. Type *type_hint = nullptr;
  4819. if (tuple_index < lhs.count) {
  4820. type_hint = lhs[tuple_index].type;
  4821. }
  4822. check_expr_base(c, &o, rhs_expr, type_hint);
  4823. if (o.mode == Addressing_NoValue) {
  4824. error_operand_no_value(&o);
  4825. o.mode = Addressing_Invalid;
  4826. }
  4827. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4828. if (lhs.count == 2 && rhs.count == 1 &&
  4829. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4830. Ast *expr = unparen_expr(o.expr);
  4831. Operand val0 = o;
  4832. Operand val1 = o;
  4833. val0.mode = Addressing_Value;
  4834. val1.mode = Addressing_Value;
  4835. val1.type = t_untyped_bool;
  4836. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4837. if (expr->kind == Ast_TypeAssertion &&
  4838. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4839. // NOTE(bill): Used only for optimizations in the backend
  4840. if (is_blank_ident(lhs[0].expr)) {
  4841. expr->TypeAssertion.ignores[0] = true;
  4842. }
  4843. if (is_blank_ident(lhs[1].expr)) {
  4844. expr->TypeAssertion.ignores[1] = true;
  4845. }
  4846. }
  4847. array_add(operands, val0);
  4848. array_add(operands, val1);
  4849. optional_ok = true;
  4850. tuple_index += 2;
  4851. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4852. Type *tuple = o.type;
  4853. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4854. Ast *expr = unparen_expr(o.expr);
  4855. if (expr->kind == Ast_CallExpr) {
  4856. expr->CallExpr.optional_ok_one = true;
  4857. }
  4858. Operand val = o;
  4859. val.type = tuple->Tuple.variables[0]->type;
  4860. val.mode = Addressing_Value;
  4861. array_add(operands, val);
  4862. tuple_index += tuple->Tuple.variables.count;
  4863. } else {
  4864. array_add(operands, o);
  4865. tuple_index += 1;
  4866. }
  4867. } else {
  4868. TypeTuple *tuple = &o.type->Tuple;
  4869. for (Entity *e : tuple->variables) {
  4870. o.type = e->type;
  4871. array_add(operands, o);
  4872. check_no_copy_assignment(o, str_lit("assignment"));
  4873. }
  4874. tuple_index += tuple->variables.count;
  4875. }
  4876. }
  4877. return optional_ok;
  4878. }
  4879. typedef u32 UnpackFlags;
  4880. enum UnpackFlag : u32 {
  4881. UnpackFlag_None = 0,
  4882. UnpackFlag_AllowOk = 1<<0,
  4883. UnpackFlag_IsVariadic = 1<<1,
  4884. UnpackFlag_AllowUndef = 1<<2,
  4885. };
  4886. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4887. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4888. if (lhs == nullptr || c->decl == nullptr) {
  4889. return tuple_count;
  4890. }
  4891. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4892. Entity *e = lhs[tuple_index + j];
  4893. if (e == nullptr) {
  4894. continue;
  4895. }
  4896. DeclInfo *decl = decl_info_of_entity(e);
  4897. if (decl == nullptr) {
  4898. continue;
  4899. }
  4900. rw_mutex_shared_lock(&decl->deps_mutex);
  4901. rw_mutex_lock(&c->decl->deps_mutex);
  4902. for (Entity *dep : decl->deps) {
  4903. ptr_set_add(&c->decl->deps, dep);
  4904. }
  4905. rw_mutex_unlock(&c->decl->deps_mutex);
  4906. rw_mutex_shared_unlock(&decl->deps_mutex);
  4907. }
  4908. return tuple_count;
  4909. };
  4910. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4911. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4912. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4913. bool optional_ok = false;
  4914. isize tuple_index = 0;
  4915. for (Ast *rhs : rhs_arguments) {
  4916. if (rhs->kind == Ast_FieldValue) {
  4917. error(rhs, "Invalid use of 'field = value'");
  4918. rhs = rhs->FieldValue.value;
  4919. }
  4920. CheckerContext c_ = *ctx;
  4921. CheckerContext *c = &c_;
  4922. Operand o = {};
  4923. Type *type_hint = nullptr;
  4924. if (lhs != nullptr && tuple_index < lhs_count) {
  4925. // NOTE(bill): override DeclInfo for dependency
  4926. Entity *e = lhs[tuple_index];
  4927. if (e != nullptr) {
  4928. type_hint = e->type;
  4929. if (e->flags & EntityFlag_Ellipsis) {
  4930. GB_ASSERT(is_type_slice(e->type));
  4931. GB_ASSERT(e->type->kind == Type_Slice);
  4932. type_hint = e->type->Slice.elem;
  4933. }
  4934. }
  4935. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4936. // NOTE(bill): override DeclInfo for dependency
  4937. Entity *e = lhs[lhs_count-1];
  4938. if (e != nullptr) {
  4939. type_hint = e->type;
  4940. if (e->flags & EntityFlag_Ellipsis) {
  4941. GB_ASSERT(is_type_slice(e->type));
  4942. GB_ASSERT(e->type->kind == Type_Slice);
  4943. type_hint = e->type->Slice.elem;
  4944. }
  4945. }
  4946. }
  4947. Ast *rhs_expr = unparen_expr(rhs);
  4948. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4949. // NOTE(bill): Just handle this very specific logic here
  4950. o.type = t_untyped_uninit;
  4951. o.mode = Addressing_Value;
  4952. o.expr = rhs;
  4953. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4954. } else {
  4955. check_expr_base(c, &o, rhs, type_hint);
  4956. }
  4957. if (o.mode == Addressing_NoValue) {
  4958. error_operand_no_value(&o);
  4959. o.mode = Addressing_Invalid;
  4960. }
  4961. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4962. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4963. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4964. Ast *expr = unparen_expr(o.expr);
  4965. Operand val0 = o;
  4966. Operand val1 = o;
  4967. val0.mode = Addressing_Value;
  4968. val1.mode = Addressing_Value;
  4969. val1.type = t_untyped_bool;
  4970. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4971. if (expr->kind == Ast_TypeAssertion &&
  4972. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4973. // NOTE(bill): Used only for optimizations in the backend
  4974. if (is_blank_ident(lhs[0]->token)) {
  4975. expr->TypeAssertion.ignores[0] = true;
  4976. }
  4977. if (is_blank_ident(lhs[1]->token)) {
  4978. expr->TypeAssertion.ignores[1] = true;
  4979. }
  4980. }
  4981. array_add(operands, val0);
  4982. array_add(operands, val1);
  4983. optional_ok = true;
  4984. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4985. } else {
  4986. array_add(operands, o);
  4987. tuple_index += 1;
  4988. }
  4989. } else {
  4990. TypeTuple *tuple = &o.type->Tuple;
  4991. for (Entity *e : tuple->variables) {
  4992. o.type = e->type;
  4993. array_add(operands, o);
  4994. }
  4995. isize count = tuple->variables.count;
  4996. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4997. }
  4998. }
  4999. return optional_ok;
  5000. }
  5001. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5002. GB_ASSERT(pt != nullptr);
  5003. GB_ASSERT(pt->kind == Type_Proc);
  5004. isize param_count = 0;
  5005. isize param_count_excluding_defaults = 0;
  5006. bool variadic = pt->Proc.variadic;
  5007. TypeTuple *param_tuple = nullptr;
  5008. if (pt->Proc.params != nullptr) {
  5009. param_tuple = &pt->Proc.params->Tuple;
  5010. param_count = param_tuple->variables.count;
  5011. if (variadic) {
  5012. for (isize i = param_count-1; i >= 0; i--) {
  5013. Entity *e = param_tuple->variables[i];
  5014. if (e->kind == Entity_TypeName) {
  5015. break;
  5016. }
  5017. if (e->kind == Entity_Variable) {
  5018. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5019. param_count--;
  5020. continue;
  5021. }
  5022. }
  5023. break;
  5024. }
  5025. param_count--;
  5026. }
  5027. }
  5028. param_count_excluding_defaults = param_count;
  5029. if (param_tuple != nullptr) {
  5030. for (isize i = param_count-1; i >= 0; i--) {
  5031. Entity *e = param_tuple->variables[i];
  5032. if (e->kind == Entity_TypeName) {
  5033. break;
  5034. }
  5035. if (e->kind == Entity_Variable) {
  5036. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5037. param_count_excluding_defaults--;
  5038. continue;
  5039. }
  5040. }
  5041. break;
  5042. }
  5043. }
  5044. if (param_count_) *param_count_ = param_count;
  5045. return param_count_excluding_defaults;
  5046. }
  5047. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5048. isize param_count = pt->param_count;
  5049. for (isize i = 0; i < param_count; i++) {
  5050. Entity *e = pt->params->Tuple.variables[i];
  5051. String name = e->token.string;
  5052. if (is_blank_ident(name)) {
  5053. continue;
  5054. }
  5055. if (name == parameter_name) {
  5056. return i;
  5057. }
  5058. }
  5059. return -1;
  5060. }
  5061. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5062. type = base_type(type);
  5063. GB_ASSERT(type->kind == Type_Proc);
  5064. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5065. }
  5066. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5067. Entity *entity, Type *proc_type,
  5068. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5069. CallArgumentErrorMode show_error_mode,
  5070. CallArgumentData *data) {
  5071. TEMPORARY_ALLOCATOR_GUARD();
  5072. CallArgumentError err = CallArgumentError_None;
  5073. ast_node(ce, CallExpr, call);
  5074. GB_ASSERT(is_type_proc(proc_type));
  5075. proc_type = base_type(proc_type);
  5076. TypeProc *pt = &proc_type->Proc;
  5077. isize param_count = 0;
  5078. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5079. bool variadic = pt->variadic;
  5080. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5081. i64 score = 0;
  5082. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5083. Type *final_proc_type = proc_type;
  5084. Entity *gen_entity = nullptr;
  5085. if (vari_expand && !variadic) {
  5086. if (show_error) {
  5087. error(ce->ellipsis,
  5088. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5089. LIT(ce->proc->Ident.token.string));
  5090. }
  5091. err = CallArgumentError_NonVariadicExpand;
  5092. } else if (vari_expand && pt->c_vararg) {
  5093. if (show_error) {
  5094. error(ce->ellipsis,
  5095. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5096. LIT(ce->proc->Ident.token.string));
  5097. }
  5098. err = CallArgumentError_NonVariadicExpand;
  5099. }
  5100. GB_ASSERT(ce->split_args);
  5101. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5102. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5103. defer ({
  5104. for (Operand const &o : ordered_operands) {
  5105. if (o.expr != nullptr) {
  5106. call->viral_state_flags |= o.expr->viral_state_flags;
  5107. }
  5108. }
  5109. });
  5110. isize positional_operand_count = positional_operands.count;
  5111. if (variadic) {
  5112. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5113. } else if (positional_operand_count > pt->param_count) {
  5114. err = CallArgumentError_TooManyArguments;
  5115. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5116. if (show_error) {
  5117. gbString proc_str = expr_to_string(ce->proc);
  5118. defer (gb_string_free(proc_str));
  5119. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5120. }
  5121. return err;
  5122. }
  5123. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5124. for (isize i = 0; i < positional_operand_count; i++) {
  5125. ordered_operands[i] = positional_operands[i];
  5126. visited[i] = true;
  5127. }
  5128. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5129. bool named_variadic_param = false;
  5130. if (named_operands.count != 0) {
  5131. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5132. for_array(i, ce->split_args->named) {
  5133. Ast *arg = ce->split_args->named[i];
  5134. Operand operand = named_operands[i];
  5135. ast_node(fv, FieldValue, arg);
  5136. if (fv->field->kind != Ast_Ident) {
  5137. if (show_error) {
  5138. gbString expr_str = expr_to_string(fv->field);
  5139. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5140. gb_string_free(expr_str);
  5141. }
  5142. err = CallArgumentError_InvalidFieldValue;
  5143. continue;
  5144. }
  5145. String name = fv->field->Ident.token.string;
  5146. isize param_index = lookup_procedure_parameter(pt, name);
  5147. if (param_index < 0) {
  5148. if (show_error) {
  5149. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5150. }
  5151. err = CallArgumentError_ParameterNotFound;
  5152. continue;
  5153. }
  5154. if (pt->variadic && param_index == pt->variadic_index) {
  5155. named_variadic_param = true;
  5156. }
  5157. if (visited[param_index]) {
  5158. if (show_error) {
  5159. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5160. }
  5161. err = CallArgumentError_DuplicateParameter;
  5162. continue;
  5163. }
  5164. visited[param_index] = true;
  5165. ordered_operands[param_index] = operand;
  5166. }
  5167. }
  5168. isize dummy_argument_count = 0;
  5169. bool actually_variadic = false;
  5170. if (variadic) {
  5171. if (visited[pt->variadic_index] &&
  5172. positional_operand_count < positional_operands.count) {
  5173. if (show_error) {
  5174. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5175. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5176. }
  5177. err = CallArgumentError_DuplicateParameter;
  5178. } else if (!visited[pt->variadic_index]) {
  5179. visited[pt->variadic_index] = true;
  5180. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5181. if (vari_expand) {
  5182. if (variadic_operands.count == 0) {
  5183. error(call, "'..' in the wrong position");
  5184. } else {
  5185. GB_ASSERT(variadic_operands.count != 0);
  5186. *variadic_operand = variadic_operands[0];
  5187. variadic_operand->type = default_type(variadic_operand->type);
  5188. actually_variadic = true;
  5189. }
  5190. } else {
  5191. AstFile *f = call->file();
  5192. // HACK(bill): this is an awful hack
  5193. Operand o = {};
  5194. o.mode = Addressing_Value;
  5195. o.expr = ast_ident(f, make_token_ident("nil"));
  5196. o.expr->Ident.token.pos = ast_token(call).pos;
  5197. if (variadic_operands.count != 0) {
  5198. actually_variadic = true;
  5199. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5200. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5201. o.type = vt->type;
  5202. } else {
  5203. dummy_argument_count += 1;
  5204. o.type = t_untyped_nil;
  5205. }
  5206. *variadic_operand = o;
  5207. }
  5208. }
  5209. }
  5210. for (Operand const &o : ordered_operands) {
  5211. if (o.mode != Addressing_Invalid) {
  5212. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5213. }
  5214. }
  5215. for (isize i = 0; i < pt->param_count; i++) {
  5216. if (!visited[i]) {
  5217. Entity *e = pt->params->Tuple.variables[i];
  5218. if (e->kind == Entity_Variable) {
  5219. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5220. ordered_operands[i].mode = Addressing_Value;
  5221. ordered_operands[i].type = e->type;
  5222. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5223. dummy_argument_count += 1;
  5224. score += assign_score_function(1);
  5225. continue;
  5226. }
  5227. }
  5228. if (show_error) {
  5229. if (e->kind == Entity_TypeName) {
  5230. error(call, "Type parameter '%.*s' is missing in procedure call",
  5231. LIT(e->token.string));
  5232. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5233. // Ignore
  5234. } else {
  5235. gbString str = type_to_string(e->type);
  5236. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5237. LIT(e->token.string), str);
  5238. gb_string_free(str);
  5239. }
  5240. }
  5241. err = CallArgumentError_ParameterMissing;
  5242. }
  5243. }
  5244. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5245. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5246. i64 s = 0;
  5247. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5248. bool ok = false;
  5249. if (e && (e->flags & EntityFlag_AnyInt)) {
  5250. if (is_type_integer(param_type)) {
  5251. ok = check_is_castable_to(c, o, param_type);
  5252. }
  5253. }
  5254. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5255. if (show_error) {
  5256. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5257. }
  5258. }
  5259. if (ok) {
  5260. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5261. } else {
  5262. if (show_error) {
  5263. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5264. }
  5265. err = CallArgumentError_WrongTypes;
  5266. }
  5267. } else if (show_error) {
  5268. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5269. }
  5270. if (e && e->flags & EntityFlag_ConstInput) {
  5271. if (o->mode != Addressing_Constant) {
  5272. if (show_error) {
  5273. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5274. }
  5275. err = CallArgumentError_NoneConstantParameter;
  5276. }
  5277. }
  5278. if (!err && is_type_any(param_type)) {
  5279. add_type_info_type(c, o->type);
  5280. }
  5281. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5282. add_type_info_type(c, o->type);
  5283. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5284. } else if (show_error && is_type_untyped(o->type)) {
  5285. update_untyped_expr_type(c, o->expr, param_type, true);
  5286. }
  5287. return s;
  5288. };
  5289. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5290. err = CallArgumentError_None;
  5291. if (variadic) {
  5292. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5293. Type *t = pt->params->Tuple.variables[0]->type;
  5294. if (is_type_polymorphic(t)) {
  5295. if (show_error) {
  5296. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5297. }
  5298. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5299. }
  5300. }
  5301. } else {
  5302. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5303. PolyProcData poly_proc_data = {};
  5304. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5305. gen_entity = poly_proc_data.gen_entity;
  5306. Type *gept = base_type(gen_entity->type);
  5307. GB_ASSERT(is_type_proc(gept));
  5308. final_proc_type = gen_entity->type;
  5309. pt = &gept->Proc;
  5310. } else {
  5311. err = CallArgumentError_WrongTypes;
  5312. }
  5313. }
  5314. for (isize i = 0; i < pt->param_count; i++) {
  5315. Operand *o = &ordered_operands[i];
  5316. if (o->mode == Addressing_Invalid) {
  5317. continue;
  5318. }
  5319. Entity *e = pt->params->Tuple.variables[i];
  5320. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5321. if (e->kind == Entity_TypeName) {
  5322. GB_ASSERT(pt->is_polymorphic);
  5323. if (o->mode != Addressing_Type) {
  5324. if (show_error) {
  5325. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5326. }
  5327. err = CallArgumentError_WrongTypes;
  5328. }
  5329. if (are_types_identical(e->type, o->type)) {
  5330. score += assign_score_function(1);
  5331. } else {
  5332. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5333. }
  5334. continue;
  5335. }
  5336. if (param_is_variadic) {
  5337. continue;
  5338. }
  5339. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5340. }
  5341. }
  5342. if (variadic) {
  5343. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5344. Type *slice = var_entity->type;
  5345. GB_ASSERT(is_type_slice(slice));
  5346. Type *elem = base_type(slice)->Slice.elem;
  5347. Type *t = elem;
  5348. if (is_type_polymorphic(t)) {
  5349. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5350. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5351. }
  5352. for_array(operand_index, variadic_operands) {
  5353. Operand *o = &variadic_operands[operand_index];
  5354. if (vari_expand) {
  5355. t = slice;
  5356. if (operand_index > 0) {
  5357. if (show_error) {
  5358. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5359. }
  5360. if (data) {
  5361. data->score = score;
  5362. data->result_type = final_proc_type->Proc.results;
  5363. data->gen_entity = gen_entity;
  5364. }
  5365. return CallArgumentError_MultipleVariadicExpand;
  5366. }
  5367. }
  5368. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5369. }
  5370. }
  5371. if (data) {
  5372. data->score = score;
  5373. data->result_type = final_proc_type->Proc.results;
  5374. data->gen_entity = gen_entity;
  5375. Ast *proc_lit = nullptr;
  5376. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5377. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5378. if (vp && vp->kind == Ast_ProcLit) {
  5379. proc_lit = vp;
  5380. }
  5381. }
  5382. if (proc_lit == nullptr) {
  5383. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5384. }
  5385. }
  5386. return err;
  5387. }
  5388. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5389. GB_ASSERT(ce != nullptr);
  5390. if (ce->args.count == 0) {
  5391. return false;
  5392. }
  5393. return ce->args[0]->kind == Ast_FieldValue;
  5394. }
  5395. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5396. Entity **lhs = nullptr;
  5397. isize lhs_count = -1;
  5398. if (proc_type == nullptr) {
  5399. return nullptr;
  5400. }
  5401. GB_ASSERT(is_type_proc(proc_type));
  5402. TypeProc *pt = &base_type(proc_type)->Proc;
  5403. *is_variadic = pt->variadic;
  5404. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5405. if (pt->params != nullptr) {
  5406. lhs = pt->params->Tuple.variables.data;
  5407. lhs_count = pt->params->Tuple.variables.count;
  5408. }
  5409. } else {
  5410. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5411. if (pt->params == nullptr) {
  5412. lhs_count = 0;
  5413. } else {
  5414. lhs_count = pt->params->Tuple.variables.count;
  5415. }
  5416. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5417. for (isize i = 0; i < lhs_count; i++) {
  5418. Entity *e = pt->params->Tuple.variables[i];
  5419. if (!is_type_polymorphic(e->type)) {
  5420. lhs[i] = e;
  5421. }
  5422. }
  5423. }
  5424. if (lhs_count_) *lhs_count_ = lhs_count;
  5425. return lhs;
  5426. }
  5427. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5428. if (clauses != nullptr) {
  5429. for (Ast *clause : *clauses) {
  5430. Operand o = {};
  5431. check_expr(ctx, &o, clause);
  5432. if (o.mode != Addressing_Constant) {
  5433. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5434. if (print_err && call_expr) error(call_expr, "at caller location");
  5435. return false;
  5436. } else if (o.value.kind != ExactValue_Bool) {
  5437. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5438. if (print_err && call_expr) error(call_expr, "at caller location");
  5439. return false;
  5440. } else if (!o.value.value_bool) {
  5441. if (print_err) {
  5442. ERROR_BLOCK();
  5443. gbString str = expr_to_string(clause);
  5444. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5445. gb_string_free(str);
  5446. if (scope != nullptr) {
  5447. isize print_count = 0;
  5448. for (auto const &entry : scope->elements) {
  5449. Entity *e = entry.value;
  5450. switch (e->kind) {
  5451. case Entity_TypeName: {
  5452. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5453. gbString str = type_to_string(e->type);
  5454. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5455. gb_string_free(str);
  5456. print_count += 1;
  5457. break;
  5458. }
  5459. case Entity_Constant: {
  5460. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5461. gbString str = exact_value_to_string(e->Constant.value);
  5462. if (is_type_untyped(e->type)) {
  5463. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5464. } else {
  5465. gbString t = type_to_string(e->type);
  5466. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5467. gb_string_free(t);
  5468. }
  5469. gb_string_free(str);
  5470. print_count += 1;
  5471. break;
  5472. }
  5473. }
  5474. }
  5475. }
  5476. if (call_expr) {
  5477. TokenPos pos = ast_token(call_expr).pos;
  5478. error_line("%s at caller location\n", token_pos_to_string(pos));
  5479. }
  5480. }
  5481. return false;
  5482. }
  5483. if (ast_file_vet_style(ctx->file)) {
  5484. Ast *c = unparen_expr(clause);
  5485. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5486. ERROR_BLOCK();
  5487. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5488. gbString x = expr_to_string(c->BinaryExpr.left);
  5489. gbString y = expr_to_string(c->BinaryExpr.right);
  5490. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5491. gb_string_free(y);
  5492. gb_string_free(x);
  5493. }
  5494. }
  5495. }
  5496. }
  5497. return true;
  5498. }
  5499. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5500. bool success = true;
  5501. type = base_type(type);
  5502. if (named_args.count > 0) {
  5503. TypeProc *pt = nullptr;
  5504. if (is_type_proc(type)) {
  5505. pt = &type->Proc;
  5506. }
  5507. for_array(i, named_args) {
  5508. Ast *arg = named_args[i];
  5509. if (arg->kind != Ast_FieldValue) {
  5510. if (show_error) {
  5511. error(arg, "Expected a 'field = value'");
  5512. }
  5513. return false;
  5514. }
  5515. ast_node(fv, FieldValue, arg);
  5516. if (fv->field->kind != Ast_Ident) {
  5517. if (show_error) {
  5518. gbString expr_str = expr_to_string(fv->field);
  5519. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5520. gb_string_free(expr_str);
  5521. }
  5522. success = false;
  5523. continue;
  5524. }
  5525. String key = fv->field->Ident.token.string;
  5526. Ast *value = fv->value;
  5527. Type *type_hint = nullptr;
  5528. if (pt) {
  5529. isize param_index = lookup_procedure_parameter(pt, key);
  5530. if (param_index < 0) {
  5531. if (show_error) {
  5532. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5533. }
  5534. success = false;
  5535. continue;
  5536. }
  5537. Entity *e = pt->params->Tuple.variables[param_index];
  5538. if (!is_type_polymorphic(e->type)) {
  5539. type_hint = e->type;
  5540. }
  5541. }
  5542. Operand o = {};
  5543. check_expr_with_type_hint(c, &o, value, type_hint);
  5544. if (o.mode == Addressing_Invalid) {
  5545. success = false;
  5546. }
  5547. array_add(named_operands, o);
  5548. }
  5549. }
  5550. return success;
  5551. }
  5552. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5553. Entity *e, Type *proc_type,
  5554. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5555. CallArgumentErrorMode show_error_mode,
  5556. CallArgumentData *data) {
  5557. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5558. Ast *ident = operand->expr;
  5559. while (ident->kind == Ast_SelectorExpr) {
  5560. Ast *s = ident->SelectorExpr.selector;
  5561. ident = s;
  5562. }
  5563. if (e == nullptr) {
  5564. e = entity_of_node(ident);
  5565. if (e != nullptr) {
  5566. proc_type = e->type;
  5567. }
  5568. }
  5569. GB_ASSERT(proc_type != nullptr);
  5570. proc_type = base_type(proc_type);
  5571. GB_ASSERT(proc_type->kind == Type_Proc);
  5572. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5573. if (return_on_failure && err != CallArgumentError_None) {
  5574. return false;
  5575. }
  5576. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5577. if (!return_on_failure && entity_to_use != nullptr) {
  5578. add_entity_use(c, ident, entity_to_use);
  5579. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5580. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5581. }
  5582. if (data->gen_entity != nullptr) {
  5583. Entity *e = data->gen_entity;
  5584. DeclInfo *decl = data->gen_entity->decl_info;
  5585. CheckerContext ctx = *c;
  5586. ctx.scope = decl->scope;
  5587. ctx.decl = decl;
  5588. ctx.proc_name = e->token.string;
  5589. ctx.curr_proc_decl = decl;
  5590. ctx.curr_proc_sig = e->type;
  5591. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5592. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5593. if (return_on_failure) {
  5594. if (!ok) {
  5595. return false;
  5596. }
  5597. } else {
  5598. decl->where_clauses_evaluated = true;
  5599. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5600. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5601. }
  5602. if (is_type_proc(data->gen_entity->type)) {
  5603. Type *t = base_type(entity_to_use->type);
  5604. data->result_type = t->Proc.results;
  5605. }
  5606. }
  5607. }
  5608. return true;
  5609. }
  5610. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5611. ast_node(ce, CallExpr, call);
  5612. GB_ASSERT(ce->split_args != nullptr);
  5613. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5614. Slice<Ast *> const &named_args = ce->split_args->named;
  5615. CallArgumentData data = {};
  5616. data.result_type = t_invalid;
  5617. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5618. auto procs = proc_group_entities_cloned(c, *operand);
  5619. if (procs.count > 1) {
  5620. isize max_arg_count = positional_args.count + named_args.count;
  5621. for (Ast *arg : positional_args) {
  5622. // NOTE(bill): The only thing that may have multiple values
  5623. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5624. arg = strip_or_return_expr(arg);
  5625. if (arg && arg->kind == Ast_CallExpr) {
  5626. max_arg_count = ISIZE_MAX;
  5627. break;
  5628. }
  5629. }
  5630. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5631. // NOTE(bill): The only thing that may have multiple values
  5632. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5633. if (arg->kind == Ast_FieldValue) {
  5634. arg = strip_or_return_expr(arg->FieldValue.value);
  5635. if (arg && arg->kind == Ast_CallExpr) {
  5636. max_arg_count = ISIZE_MAX;
  5637. break;
  5638. }
  5639. }
  5640. }
  5641. // ignore named arguments first
  5642. for (Ast *arg : named_args) {
  5643. if (arg->kind != Ast_FieldValue) {
  5644. continue;
  5645. }
  5646. ast_node(fv, FieldValue, arg);
  5647. if (fv->field->kind != Ast_Ident) {
  5648. continue;
  5649. }
  5650. String key = fv->field->Ident.token.string;
  5651. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5652. Type *t = procs[proc_index]->type;
  5653. if (is_type_proc(t)) {
  5654. isize param_index = lookup_procedure_parameter(t, key);
  5655. if (param_index < 0) {
  5656. array_unordered_remove(&procs, proc_index);
  5657. }
  5658. }
  5659. }
  5660. }
  5661. if (procs.count == 0) {
  5662. // if any of the named arguments are wrong, the `procs` will be empty
  5663. // just start from scratch
  5664. array_free(&procs);
  5665. procs = proc_group_entities_cloned(c, *operand);
  5666. }
  5667. // filter by positional argument length
  5668. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5669. Entity *proc = procs[proc_index];
  5670. Type *pt = base_type(proc->type);
  5671. if (!(pt != nullptr && is_type_proc(pt))) {
  5672. proc_index++;
  5673. continue;
  5674. }
  5675. isize param_count = 0;
  5676. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5677. if (param_count_excluding_defaults > max_arg_count) {
  5678. array_unordered_remove(&procs, proc_index);
  5679. continue;
  5680. }
  5681. proc_index++;
  5682. }
  5683. }
  5684. Entity **lhs = nullptr;
  5685. isize lhs_count = -1;
  5686. bool is_variadic = false;
  5687. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5688. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5689. defer (array_free(&positional_operands));
  5690. defer (array_free(&named_operands));
  5691. if (procs.count == 1) {
  5692. Entity *e = procs[0];
  5693. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5694. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5695. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5696. check_call_arguments_single(c, call, operand,
  5697. e, e->type,
  5698. positional_operands, named_operands,
  5699. CallArgumentErrorMode::ShowErrors,
  5700. &data);
  5701. }
  5702. return data;
  5703. }
  5704. {
  5705. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5706. // where the same positional parameter has the same type value (and ellipsis)
  5707. isize proc_arg_count = -1;
  5708. for (Entity *p : procs) {
  5709. Type *pt = base_type(p->type);
  5710. if (pt != nullptr && is_type_proc(pt)) {
  5711. if (proc_arg_count < 0) {
  5712. proc_arg_count = pt->Proc.param_count;
  5713. } else {
  5714. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5715. }
  5716. }
  5717. }
  5718. if (proc_arg_count >= 0) {
  5719. lhs_count = proc_arg_count;
  5720. if (lhs_count > 0) {
  5721. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5722. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5723. Entity *e = nullptr;
  5724. for (Entity *p : procs) {
  5725. Type *pt = base_type(p->type);
  5726. if (!(pt != nullptr && is_type_proc(pt))) {
  5727. continue;
  5728. }
  5729. if (e == nullptr) {
  5730. e = pt->Proc.params->Tuple.variables[param_index];
  5731. } else {
  5732. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5733. if (e == f) {
  5734. continue;
  5735. }
  5736. if (are_types_identical(e->type, f->type)) {
  5737. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5738. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5739. if (ee == fe) {
  5740. continue;
  5741. }
  5742. }
  5743. // NOTE(bill): Entities are not close enough to be used
  5744. e = nullptr;
  5745. break;
  5746. }
  5747. }
  5748. lhs[param_index] = e;
  5749. }
  5750. }
  5751. }
  5752. }
  5753. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5754. for_array(i, named_args) {
  5755. Ast *arg = named_args[i];
  5756. if (arg->kind != Ast_FieldValue) {
  5757. error(arg, "Expected a 'field = value'");
  5758. return data;
  5759. }
  5760. ast_node(fv, FieldValue, arg);
  5761. if (fv->field->kind != Ast_Ident) {
  5762. gbString expr_str = expr_to_string(fv->field);
  5763. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5764. gb_string_free(expr_str);
  5765. return data;
  5766. }
  5767. String key = fv->field->Ident.token.string;
  5768. Ast *value = fv->value;
  5769. Type *type_hint = nullptr;
  5770. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5771. Entity *e = lhs[lhs_idx];
  5772. if (e != nullptr && e->token.string == key &&
  5773. !is_type_polymorphic(e->type)) {
  5774. type_hint = e->type;
  5775. break;
  5776. }
  5777. }
  5778. Operand o = {};
  5779. check_expr_with_type_hint(c, &o, value, type_hint);
  5780. array_add(&named_operands, o);
  5781. }
  5782. gb_free(heap_allocator(), lhs);
  5783. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5784. defer (array_free(&valids));
  5785. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5786. defer (array_free(&proc_entities));
  5787. for (Entity *proc : procs) {
  5788. array_add(&proc_entities, proc);
  5789. }
  5790. int max_matched_features = 0;
  5791. gbString expr_name = expr_to_string(operand->expr);
  5792. defer (gb_string_free(expr_name));
  5793. for_array(i, procs) {
  5794. Entity *p = procs[i];
  5795. if (p->flags & EntityFlag_Disabled) {
  5796. continue;
  5797. }
  5798. Type *pt = base_type(p->type);
  5799. if (pt != nullptr && is_type_proc(pt)) {
  5800. CallArgumentData data = {};
  5801. CheckerContext ctx = *c;
  5802. ctx.no_polymorphic_errors = true;
  5803. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5804. ctx.hide_polymorphic_errors = true;
  5805. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5806. p, pt,
  5807. positional_operands, named_operands,
  5808. CallArgumentErrorMode::NoErrors,
  5809. &data);
  5810. if (!is_a_candidate) {
  5811. continue;
  5812. }
  5813. isize index = i;
  5814. ValidIndexAndScore item = {};
  5815. item.score = data.score;
  5816. if (data.gen_entity != nullptr) {
  5817. array_add(&proc_entities, data.gen_entity);
  5818. index = proc_entities.count-1;
  5819. // prefer non-polymorphic procedures over polymorphic
  5820. item.score += assign_score_function(1);
  5821. }
  5822. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  5823. item.index = index;
  5824. array_add(&valids, item);
  5825. }
  5826. }
  5827. if (max_matched_features > 0) {
  5828. for_array(i, valids) {
  5829. Entity *p = procs[valids[i].index];
  5830. Type *t = base_type(p->type);
  5831. GB_ASSERT(t->kind == Type_Proc);
  5832. int matched = matched_target_features(&t->Proc);
  5833. valids[i].score += assign_score_function(max_matched_features-matched);
  5834. }
  5835. }
  5836. if (valids.count > 1) {
  5837. array_sort(valids, valid_index_and_score_cmp);
  5838. i64 best_score = valids[0].score;
  5839. Entity *best_entity = proc_entities[valids[0].index];
  5840. GB_ASSERT(best_entity != nullptr);
  5841. for (isize i = 1; i < valids.count; i++) {
  5842. if (best_score > valids[i].score) {
  5843. valids.count = i;
  5844. break;
  5845. }
  5846. if (best_entity == proc_entities[valids[i].index]) {
  5847. valids.count = i;
  5848. break;
  5849. }
  5850. }
  5851. }
  5852. auto print_argument_types = [&]() {
  5853. error_line("\tGiven argument types: (");
  5854. isize i = 0;
  5855. for (Operand const &o : positional_operands) {
  5856. if (i++ > 0) error_line(", ");
  5857. gbString type = type_to_string(o.type);
  5858. defer (gb_string_free(type));
  5859. error_line("%s", type);
  5860. }
  5861. for (Operand const &o : named_operands) {
  5862. if (i++ > 0) error_line(", ");
  5863. gbString type = type_to_string(o.type);
  5864. defer (gb_string_free(type));
  5865. if (i < ce->split_args->named.count) {
  5866. Ast *named_field = ce->split_args->named[i];
  5867. ast_node(fv, FieldValue, named_field);
  5868. gbString field = expr_to_string(fv->field);
  5869. defer (gb_string_free(field));
  5870. error_line("%s = %s", field, type);
  5871. } else {
  5872. error_line("%s", type);
  5873. }
  5874. }
  5875. error_line(")\n");
  5876. };
  5877. if (valids.count == 0) {
  5878. ERROR_BLOCK();
  5879. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5880. if (positional_operands.count == 0 && named_operands.count == 0) {
  5881. error_line("\tNo given arguments\n");
  5882. } else {
  5883. print_argument_types();
  5884. }
  5885. if (procs.count == 0) {
  5886. procs = proc_group_entities_cloned(c, *operand);
  5887. }
  5888. if (procs.count > 0) {
  5889. error_line("Did you mean to use one of the following:\n");
  5890. }
  5891. isize max_name_length = 0;
  5892. isize max_type_length = 0;
  5893. for (Entity *proc : procs) {
  5894. Type *t = base_type(proc->type);
  5895. if (t == t_invalid) continue;
  5896. String prefix = {};
  5897. String prefix_sep = {};
  5898. if (proc->pkg) {
  5899. prefix = proc->pkg->name;
  5900. prefix_sep = str_lit(".");
  5901. }
  5902. String name = proc->token.string;
  5903. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5904. gbString pt;
  5905. if (t->Proc.node != nullptr) {
  5906. pt = expr_to_string(t->Proc.node);
  5907. } else {
  5908. pt = type_to_string(t);
  5909. }
  5910. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5911. gb_string_free(pt);
  5912. }
  5913. isize max_spaces = gb_max(max_name_length, max_type_length);
  5914. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5915. for (isize i = 0; i < max_spaces; i++) {
  5916. spaces[i] = ' ';
  5917. }
  5918. spaces[max_spaces] = 0;
  5919. for (Entity *proc : procs) {
  5920. TokenPos pos = proc->token.pos;
  5921. Type *t = base_type(proc->type);
  5922. if (t == t_invalid) continue;
  5923. GB_ASSERT(t->kind == Type_Proc);
  5924. gbString pt;
  5925. defer (gb_string_free(pt));
  5926. if (t->Proc.node != nullptr) {
  5927. pt = expr_to_string(t->Proc.node);
  5928. } else {
  5929. pt = type_to_string(t);
  5930. }
  5931. String prefix = {};
  5932. String prefix_sep = {};
  5933. if (proc->pkg) {
  5934. prefix = proc->pkg->name;
  5935. prefix_sep = str_lit(".");
  5936. }
  5937. String name = proc->token.string;
  5938. isize len = prefix.len + prefix_sep.len + name.len;
  5939. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5940. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5941. char const *sep = "::";
  5942. if (proc->kind == Entity_Variable) {
  5943. sep = ":=";
  5944. }
  5945. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5946. LIT(prefix), LIT(prefix_sep), LIT(name),
  5947. name_padding, spaces,
  5948. sep,
  5949. pt,
  5950. type_padding, spaces,
  5951. token_pos_to_string(pos)
  5952. );
  5953. }
  5954. if (procs.count > 0) {
  5955. error_line("\n");
  5956. }
  5957. data.result_type = t_invalid;
  5958. } else if (valids.count > 1) {
  5959. ERROR_BLOCK();
  5960. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5961. if (positional_operands.count == 0 && named_operands.count == 0) {
  5962. error_line("\tNo given arguments\n");
  5963. } else {
  5964. print_argument_types();
  5965. }
  5966. for (auto const &valid : valids) {
  5967. Entity *proc = proc_entities[valid.index];
  5968. GB_ASSERT(proc != nullptr);
  5969. TokenPos pos = proc->token.pos;
  5970. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5971. gbString pt = nullptr;
  5972. defer (gb_string_free(pt));
  5973. if (t->Proc.node != nullptr) {
  5974. pt = expr_to_string(t->Proc.node);
  5975. } else {
  5976. pt = type_to_string(t);
  5977. }
  5978. String name = proc->token.string;
  5979. char const *sep = "::";
  5980. if (proc->kind == Entity_Variable) {
  5981. sep = ":=";
  5982. }
  5983. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5984. if (proc->decl_info->proc_lit != nullptr) {
  5985. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5986. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5987. if (pl->where_token.kind != Token_Invalid) {
  5988. error_line("\n\t\twhere ");
  5989. for_array(j, pl->where_clauses) {
  5990. Ast *clause = pl->where_clauses[j];
  5991. if (j != 0) {
  5992. error_line("\t\t ");
  5993. }
  5994. gbString str = expr_to_string(clause);
  5995. error_line("%s", str);
  5996. gb_string_free(str);
  5997. if (j != pl->where_clauses.count-1) {
  5998. error_line(",");
  5999. }
  6000. }
  6001. error_line("\n\t");
  6002. }
  6003. }
  6004. error_line("at %s\n", token_pos_to_string(pos));
  6005. }
  6006. data.result_type = t_invalid;
  6007. } else {
  6008. GB_ASSERT(valids.count == 1);
  6009. Ast *ident = operand->expr;
  6010. while (ident->kind == Ast_SelectorExpr) {
  6011. Ast *s = ident->SelectorExpr.selector;
  6012. ident = s;
  6013. }
  6014. Entity *e = proc_entities[valids[0].index];
  6015. GB_ASSERT(e != nullptr);
  6016. Array<Operand> named_operands = {};
  6017. check_call_arguments_single(c, call, operand,
  6018. e, e->type,
  6019. positional_operands, named_operands,
  6020. CallArgumentErrorMode::ShowErrors,
  6021. &data);
  6022. return data;
  6023. }
  6024. return data;
  6025. }
  6026. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6027. Type *proc_type = nullptr;
  6028. CallArgumentData data = {};
  6029. data.result_type = t_invalid;
  6030. proc_type = base_type(operand->type);
  6031. TypeProc *pt = nullptr;
  6032. if (proc_type) {
  6033. pt = &proc_type->Proc;
  6034. }
  6035. TEMPORARY_ALLOCATOR_GUARD();
  6036. ast_node(ce, CallExpr, call);
  6037. bool any_failure = false;
  6038. // Split positional and named args into separate arrays/slices
  6039. Slice<Ast *> positional_args = {};
  6040. Slice<Ast *> named_args = {};
  6041. if (ce->split_args == nullptr) {
  6042. positional_args = ce->args;
  6043. for (isize i = 0; i < ce->args.count; i++) {
  6044. Ast *arg = ce->args.data[i];
  6045. if (arg->kind == Ast_FieldValue) {
  6046. positional_args.count = i;
  6047. break;
  6048. }
  6049. }
  6050. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6051. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6052. split_args->positional = positional_args;
  6053. split_args->named = named_args;
  6054. ce->split_args = split_args;
  6055. } else {
  6056. positional_args = ce->split_args->positional;
  6057. named_args = ce->split_args->named;
  6058. }
  6059. if (operand->mode == Addressing_ProcGroup) {
  6060. return check_call_arguments_proc_group(c, operand, call);
  6061. }
  6062. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6063. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6064. defer (array_free(&positional_operands));
  6065. defer (array_free(&named_operands));
  6066. if (positional_args.count > 0) {
  6067. isize lhs_count = -1;
  6068. bool is_variadic = false;
  6069. Entity **lhs = nullptr;
  6070. if (pt != nullptr) {
  6071. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6072. }
  6073. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6074. }
  6075. if (named_args.count > 0) {
  6076. for_array(i, named_args) {
  6077. Ast *arg = named_args[i];
  6078. if (arg->kind != Ast_FieldValue) {
  6079. error(arg, "Expected a 'field = value'");
  6080. return data;
  6081. }
  6082. ast_node(fv, FieldValue, arg);
  6083. if (fv->field->kind != Ast_Ident) {
  6084. gbString expr_str = expr_to_string(fv->field);
  6085. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6086. any_failure = true;
  6087. gb_string_free(expr_str);
  6088. continue;
  6089. }
  6090. String key = fv->field->Ident.token.string;
  6091. Ast *value = fv->value;
  6092. isize param_index = lookup_procedure_parameter(pt, key);
  6093. Type *type_hint = nullptr;
  6094. if (param_index >= 0) {
  6095. Entity *e = pt->params->Tuple.variables[param_index];
  6096. type_hint = e->type;
  6097. }
  6098. Operand o = {};
  6099. check_expr_with_type_hint(c, &o, value, type_hint);
  6100. if (o.mode == Addressing_Invalid) {
  6101. any_failure = true;
  6102. }
  6103. array_add(&named_operands, o);
  6104. }
  6105. }
  6106. if (!any_failure) {
  6107. check_call_arguments_single(c, call, operand,
  6108. nullptr, proc_type,
  6109. positional_operands, named_operands,
  6110. CallArgumentErrorMode::ShowErrors,
  6111. &data);
  6112. } else if (pt) {
  6113. data.result_type = pt->results;
  6114. }
  6115. return data;
  6116. }
  6117. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6118. if (!is_type_polymorphic_record(t)) {
  6119. return -1;
  6120. }
  6121. TypeTuple *params = get_record_polymorphic_params(t);
  6122. if (params == nullptr) {
  6123. return -1;
  6124. }
  6125. for_array(i, params->variables) {
  6126. Entity *e = params->variables[i];
  6127. String name = e->token.string;
  6128. if (is_blank_ident(name)) {
  6129. continue;
  6130. }
  6131. if (name == parameter_name) {
  6132. return i;
  6133. }
  6134. }
  6135. return -1;
  6136. }
  6137. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6138. ast_node(ce, CallExpr, call);
  6139. Type *original_type = operand->type;
  6140. GB_ASSERT(is_type_polymorphic_record(original_type));
  6141. bool show_error = true;
  6142. Array<Operand> operands = {};
  6143. defer (array_free(&operands));
  6144. bool named_fields = false;
  6145. {
  6146. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6147. auto prev_type_path = c->type_path;
  6148. c->type_path = new_checker_type_path();
  6149. defer ({
  6150. destroy_checker_type_path(c->type_path);
  6151. c->type_path = prev_type_path;
  6152. });
  6153. if (is_call_expr_field_value(ce)) {
  6154. named_fields = true;
  6155. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6156. for_array(i, ce->args) {
  6157. Ast *arg = ce->args[i];
  6158. ast_node(fv, FieldValue, arg);
  6159. if (fv->field->kind == Ast_Ident) {
  6160. String name = fv->field->Ident.token.string;
  6161. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6162. if (index >= 0) {
  6163. TypeTuple *params = get_record_polymorphic_params(original_type);
  6164. Entity *e = params->variables[index];
  6165. if (e->kind == Entity_Constant) {
  6166. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6167. continue;
  6168. }
  6169. }
  6170. }
  6171. check_expr_or_type(c, &operands[i], fv->value);
  6172. }
  6173. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6174. if (vari_expand) {
  6175. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6176. }
  6177. } else {
  6178. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6179. Entity **lhs = nullptr;
  6180. isize lhs_count = -1;
  6181. TypeTuple *params = get_record_polymorphic_params(original_type);
  6182. if (params != nullptr) {
  6183. lhs = params->variables.data;
  6184. lhs_count = params->variables.count;
  6185. }
  6186. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6187. }
  6188. }
  6189. CallArgumentError err = CallArgumentError_None;
  6190. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6191. isize param_count = tuple->variables.count;
  6192. isize minimum_param_count = param_count;
  6193. for (; minimum_param_count > 0; minimum_param_count--) {
  6194. Entity *e = tuple->variables[minimum_param_count-1];
  6195. if (e->kind != Entity_Constant) {
  6196. break;
  6197. }
  6198. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6199. break;
  6200. }
  6201. }
  6202. Array<Operand> ordered_operands = operands;
  6203. if (!named_fields) {
  6204. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6205. array_copy(&ordered_operands, operands, 0);
  6206. } else {
  6207. TEMPORARY_ALLOCATOR_GUARD();
  6208. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6209. // LEAK(bill)
  6210. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6211. for_array(i, ce->args) {
  6212. Ast *arg = ce->args[i];
  6213. ast_node(fv, FieldValue, arg);
  6214. if (fv->field->kind != Ast_Ident) {
  6215. if (show_error) {
  6216. gbString expr_str = expr_to_string(fv->field);
  6217. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6218. gb_string_free(expr_str);
  6219. }
  6220. err = CallArgumentError_InvalidFieldValue;
  6221. continue;
  6222. }
  6223. String name = fv->field->Ident.token.string;
  6224. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6225. if (index < 0) {
  6226. if (show_error) {
  6227. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6228. }
  6229. err = CallArgumentError_ParameterNotFound;
  6230. continue;
  6231. }
  6232. if (visited[index]) {
  6233. if (show_error) {
  6234. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6235. }
  6236. err = CallArgumentError_DuplicateParameter;
  6237. continue;
  6238. }
  6239. visited[index] = true;
  6240. ordered_operands[index] = operands[i];
  6241. }
  6242. for (isize i = 0; i < param_count; i++) {
  6243. if (!visited[i]) {
  6244. Entity *e = tuple->variables[i];
  6245. if (is_blank_ident(e->token)) {
  6246. continue;
  6247. }
  6248. if (show_error) {
  6249. if (e->kind == Entity_TypeName) {
  6250. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6251. LIT(e->token.string));
  6252. } else {
  6253. gbString str = type_to_string(e->type);
  6254. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6255. LIT(e->token.string), str);
  6256. gb_string_free(str);
  6257. }
  6258. }
  6259. err = CallArgumentError_ParameterMissing;
  6260. }
  6261. }
  6262. }
  6263. if (err != 0) {
  6264. operand->mode = Addressing_Invalid;
  6265. return err;
  6266. }
  6267. while (ordered_operands.count > 0) {
  6268. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6269. break;
  6270. }
  6271. array_pop(&ordered_operands);
  6272. }
  6273. if (minimum_param_count != param_count) {
  6274. if (param_count < ordered_operands.count) {
  6275. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6276. err = CallArgumentError_TooManyArguments;
  6277. } else if (minimum_param_count > ordered_operands.count) {
  6278. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6279. err = CallArgumentError_TooFewArguments;
  6280. }
  6281. } else {
  6282. if (param_count < ordered_operands.count) {
  6283. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6284. err = CallArgumentError_TooManyArguments;
  6285. } else if (param_count > ordered_operands.count) {
  6286. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6287. err = CallArgumentError_TooFewArguments;
  6288. }
  6289. }
  6290. if (err != 0) {
  6291. return err;
  6292. }
  6293. if (minimum_param_count != param_count) {
  6294. array_resize(&ordered_operands, param_count);
  6295. isize missing_count = 0;
  6296. // NOTE(bill): Replace missing operands with the default values (if possible)
  6297. for_array(i, ordered_operands) {
  6298. Operand *o = &ordered_operands[i];
  6299. if (o->expr == nullptr) {
  6300. Entity *e = tuple->variables[i];
  6301. if (e->kind == Entity_Constant) {
  6302. missing_count += 1;
  6303. o->mode = Addressing_Constant;
  6304. o->type = default_type(e->type);
  6305. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6306. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6307. o->value = e->Constant.param_value.value;
  6308. }
  6309. } else if (e->kind == Entity_TypeName) {
  6310. missing_count += 1;
  6311. o->mode = Addressing_Type;
  6312. o->type = e->type;
  6313. o->expr = e->identifier;
  6314. }
  6315. }
  6316. }
  6317. }
  6318. isize oo_count = gb_min(param_count, ordered_operands.count);
  6319. i64 score = 0;
  6320. for (isize i = 0; i < oo_count; i++) {
  6321. Entity *e = tuple->variables[i];
  6322. Operand *o = &ordered_operands[i];
  6323. if (o->mode == Addressing_Invalid) {
  6324. continue;
  6325. }
  6326. if (e->kind == Entity_TypeName) {
  6327. if (o->mode != Addressing_Type) {
  6328. if (show_error) {
  6329. gbString expr = expr_to_string(o->expr);
  6330. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6331. gb_string_free(expr);
  6332. }
  6333. err = CallArgumentError_WrongTypes;
  6334. }
  6335. if (are_types_identical(e->type, o->type)) {
  6336. score += assign_score_function(1);
  6337. } else {
  6338. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6339. }
  6340. } else {
  6341. i64 s = 0;
  6342. if (o->type->kind == Type_Generic) {
  6343. // Polymorphic name!
  6344. score += assign_score_function(1);
  6345. continue;
  6346. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6347. if (show_error) {
  6348. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6349. }
  6350. err = CallArgumentError_WrongTypes;
  6351. }
  6352. o->type = e->type;
  6353. if (o->mode != Addressing_Constant) {
  6354. bool valid = false;
  6355. if (is_type_proc(o->type)) {
  6356. Entity *proc_entity = entity_from_expr(o->expr);
  6357. valid = proc_entity != nullptr;
  6358. }
  6359. if (!valid) {
  6360. if (show_error) {
  6361. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6362. }
  6363. err = CallArgumentError_NoneConstantParameter;
  6364. }
  6365. }
  6366. score += s;
  6367. }
  6368. // NOTE(bill): Add type info the parameters
  6369. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6370. // add_type_info_type(c, o->type);
  6371. }
  6372. if (show_error && err) {
  6373. return err;
  6374. }
  6375. {
  6376. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6377. mutex_lock(&found_gen_types->mutex);
  6378. defer (mutex_unlock(&found_gen_types->mutex));
  6379. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6380. if (found_entity) {
  6381. operand->mode = Addressing_Type;
  6382. operand->type = found_entity->type;
  6383. return err;
  6384. }
  6385. CheckerContext ctx = *c;
  6386. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6387. ctx.scope = polymorphic_record_parent_scope(original_type);
  6388. GB_ASSERT(ctx.scope != nullptr);
  6389. Type *bt = base_type(original_type);
  6390. String generated_name = make_string_c(expr_to_string(call));
  6391. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6392. if (bt->kind == Type_Struct) {
  6393. Ast *node = clone_ast(bt->Struct.node);
  6394. Type *struct_type = alloc_type_struct();
  6395. struct_type->Struct.node = node;
  6396. struct_type->Struct.polymorphic_parent = original_type;
  6397. set_base_type(named_type, struct_type);
  6398. check_open_scope(&ctx, node);
  6399. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6400. check_close_scope(&ctx);
  6401. } else if (bt->kind == Type_Union) {
  6402. Ast *node = clone_ast(bt->Union.node);
  6403. Type *union_type = alloc_type_union();
  6404. union_type->Union.node = node;
  6405. union_type->Union.polymorphic_parent = original_type;
  6406. set_base_type(named_type, union_type);
  6407. check_open_scope(&ctx, node);
  6408. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6409. check_close_scope(&ctx);
  6410. } else {
  6411. GB_PANIC("Unsupported parametric polymorphic record type");
  6412. }
  6413. bt = base_type(named_type);
  6414. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6415. GB_ASSERT(original_type->kind == Type_Named);
  6416. Entity *e = original_type->Named.type_name;
  6417. GB_ASSERT(e->kind == Entity_TypeName);
  6418. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6419. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6420. TypeTuple *tuple = get_record_polymorphic_params(e->type);
  6421. if (tuple != nullptr) for_array(i, tuple->variables) {
  6422. Entity *v = tuple->variables[i];
  6423. String name = v->token.string;
  6424. if (i > 0) {
  6425. s = gb_string_append_fmt(s, ", ");
  6426. }
  6427. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6428. if (v->kind == Entity_TypeName) {
  6429. if (v->type->kind != Type_Generic) {
  6430. s = gb_string_append_fmt(s, "=");
  6431. s = write_type_to_string(s, v->type, false);
  6432. }
  6433. } else if (v->kind == Entity_Constant) {
  6434. s = gb_string_append_fmt(s, "=");
  6435. s = write_exact_value_to_string(s, v->Constant.value);
  6436. }
  6437. }
  6438. s = gb_string_append_fmt(s, ")");
  6439. String new_name = make_string_c(s);
  6440. named_type->Named.name = new_name;
  6441. if (named_type->Named.type_name) {
  6442. named_type->Named.type_name->token.string = new_name;
  6443. }
  6444. }
  6445. operand->mode = Addressing_Type;
  6446. operand->type = named_type;
  6447. }
  6448. return err;
  6449. }
  6450. // returns true on success
  6451. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6452. bool success = true;
  6453. if (args.count > 0) {
  6454. if (allow_mixed) {
  6455. bool was_named = false;
  6456. for (Ast *arg : args) {
  6457. if (was_named && arg->kind != Ast_FieldValue) {
  6458. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6459. success = false;
  6460. break;
  6461. }
  6462. was_named = was_named || arg->kind == Ast_FieldValue;
  6463. }
  6464. } else {
  6465. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6466. for (Ast *arg : args) {
  6467. bool mix = false;
  6468. if (first_is_field_value) {
  6469. mix = arg->kind != Ast_FieldValue;
  6470. } else {
  6471. mix = arg->kind == Ast_FieldValue;
  6472. }
  6473. if (mix) {
  6474. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6475. success = false;
  6476. }
  6477. }
  6478. }
  6479. }
  6480. return success;
  6481. }
  6482. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6483. operand->mode = Addressing_Invalid; \
  6484. operand->expr = call; \
  6485. return Expr_Stmt; \
  6486. }
  6487. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6488. if (proc != nullptr &&
  6489. proc->kind == Ast_BasicDirective) {
  6490. ast_node(bd, BasicDirective, proc);
  6491. String name = bd->name.string;
  6492. if (
  6493. name == "location" ||
  6494. name == "exists" ||
  6495. name == "assert" ||
  6496. name == "panic" ||
  6497. name == "defined" ||
  6498. name == "config" ||
  6499. name == "load" ||
  6500. name == "load_directory" ||
  6501. name == "load_hash" ||
  6502. name == "hash"
  6503. ) {
  6504. operand->mode = Addressing_Builtin;
  6505. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6506. operand->expr = proc;
  6507. operand->type = t_invalid;
  6508. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6509. } else {
  6510. error(proc, "Unknown directive: #%.*s", LIT(name));
  6511. operand->expr = proc;
  6512. operand->type = t_invalid;
  6513. operand->mode = Addressing_Invalid;
  6514. return Expr_Expr;
  6515. }
  6516. if (inlining != ProcInlining_none) {
  6517. error(call, "Inlining operators are not allowed on built-in procedures");
  6518. }
  6519. } else {
  6520. if (proc != nullptr) {
  6521. check_expr_or_type(c, operand, proc);
  6522. } else {
  6523. GB_ASSERT(operand->expr != nullptr);
  6524. }
  6525. }
  6526. if (operand->mode == Addressing_Invalid) {
  6527. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6528. for (Ast *arg : args) {
  6529. if (arg->kind == Ast_FieldValue) {
  6530. arg = arg->FieldValue.value;
  6531. }
  6532. check_expr_base(c, operand, arg, nullptr);
  6533. }
  6534. operand->mode = Addressing_Invalid;
  6535. operand->expr = call;
  6536. return Expr_Stmt;
  6537. }
  6538. if (operand->mode == Addressing_Type) {
  6539. Type *t = operand->type;
  6540. if (is_type_polymorphic_record(t)) {
  6541. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6542. if (!is_type_named(t)) {
  6543. gbString s = expr_to_string(operand->expr);
  6544. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6545. gb_string_free(s);
  6546. operand->mode = Addressing_Invalid;
  6547. operand->type = t_invalid;;
  6548. return Expr_Expr;
  6549. }
  6550. auto err = check_polymorphic_record_type(c, operand, call);
  6551. if (err == 0) {
  6552. Ast *ident = operand->expr;
  6553. while (ident->kind == Ast_SelectorExpr) {
  6554. Ast *s = ident->SelectorExpr.selector;
  6555. ident = s;
  6556. }
  6557. Type *ot = operand->type;
  6558. GB_ASSERT(ot->kind == Type_Named);
  6559. Entity *e = ot->Named.type_name;
  6560. add_entity_use(c, ident, e);
  6561. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6562. } else {
  6563. operand->mode = Addressing_Invalid;
  6564. operand->type = t_invalid;
  6565. }
  6566. } else {
  6567. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6568. operand->mode = Addressing_Invalid;
  6569. isize arg_count = args.count;
  6570. switch (arg_count) {
  6571. case 0:
  6572. {
  6573. gbString str = type_to_string(t);
  6574. error(call, "Missing argument in conversion to '%s'", str);
  6575. gb_string_free(str);
  6576. } break;
  6577. default:
  6578. {
  6579. gbString str = type_to_string(t);
  6580. error(call, "Too many arguments in conversion to '%s'", str);
  6581. gb_string_free(str);
  6582. } break;
  6583. case 1: {
  6584. Ast *arg = args[0];
  6585. if (arg->kind == Ast_FieldValue) {
  6586. error(call, "'field = value' cannot be used in a type conversion");
  6587. arg = arg->FieldValue.value;
  6588. // NOTE(bill): Carry on the cast regardless
  6589. }
  6590. check_expr_with_type_hint(c, operand, arg, t);
  6591. if (operand->mode != Addressing_Invalid) {
  6592. if (is_type_polymorphic(t)) {
  6593. error(call, "A polymorphic type cannot be used in a type conversion");
  6594. } else {
  6595. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6596. // as it assumes it is determining the type
  6597. check_cast(c, operand, t);
  6598. }
  6599. }
  6600. operand->type = t;
  6601. operand->expr = call;
  6602. break;
  6603. }
  6604. }
  6605. }
  6606. return Expr_Expr;
  6607. }
  6608. if (operand->mode == Addressing_Builtin) {
  6609. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6610. i32 id = operand->builtin_id;
  6611. Entity *e = entity_of_node(operand->expr);
  6612. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6613. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6614. }
  6615. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6616. operand->mode = Addressing_Invalid;
  6617. operand->type = t_invalid;
  6618. }
  6619. operand->expr = call;
  6620. return builtin_procs[id].kind;
  6621. }
  6622. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6623. Entity *initial_entity = entity_of_node(operand->expr);
  6624. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6625. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6626. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6627. if (c->decl) {
  6628. c->decl->defer_used += 1;
  6629. }
  6630. }
  6631. add_entity_use(c, operand->expr, initial_entity);
  6632. if (initial_entity->Procedure.entry_point_only) {
  6633. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6634. // Okay
  6635. } else {
  6636. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6637. }
  6638. }
  6639. }
  6640. if (operand->mode != Addressing_ProcGroup) {
  6641. Type *proc_type = base_type(operand->type);
  6642. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6643. bool valid_mode = is_operand_value(*operand);
  6644. if (!valid_type || !valid_mode) {
  6645. Ast *e = operand->expr;
  6646. gbString str = expr_to_string(e);
  6647. gbString type_str = type_to_string(operand->type);
  6648. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6649. gb_string_free(type_str);
  6650. gb_string_free(str);
  6651. operand->mode = Addressing_Invalid;
  6652. operand->expr = call;
  6653. return Expr_Stmt;
  6654. }
  6655. }
  6656. CallArgumentData data = check_call_arguments(c, operand, call);
  6657. Type *result_type = data.result_type;
  6658. gb_zero_item(operand);
  6659. operand->expr = call;
  6660. if (result_type == t_invalid) {
  6661. operand->mode = Addressing_Invalid;
  6662. operand->type = t_invalid;
  6663. return Expr_Stmt;
  6664. }
  6665. Type *pt = base_type(operand->type);
  6666. if (pt == nullptr) {
  6667. pt = t_invalid;
  6668. }
  6669. if (pt == t_invalid) {
  6670. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6671. pt = type_of_expr(operand->expr->CallExpr.proc);
  6672. }
  6673. if (pt == t_invalid && data.gen_entity) {
  6674. pt = data.gen_entity->type;
  6675. }
  6676. }
  6677. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6678. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6679. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6680. }
  6681. }
  6682. if (result_type == nullptr) {
  6683. operand->mode = Addressing_NoValue;
  6684. } else {
  6685. GB_ASSERT(is_type_tuple(result_type));
  6686. isize count = result_type->Tuple.variables.count;
  6687. switch (count) {
  6688. case 0:
  6689. operand->mode = Addressing_NoValue;
  6690. break;
  6691. case 1:
  6692. operand->mode = Addressing_Value;
  6693. operand->type = result_type->Tuple.variables[0]->type;
  6694. break;
  6695. default:
  6696. operand->mode = Addressing_Value;
  6697. operand->type = result_type;
  6698. break;
  6699. }
  6700. }
  6701. bool is_call_inlined = false;
  6702. switch (inlining) {
  6703. case ProcInlining_inline:
  6704. is_call_inlined = true;
  6705. if (proc != nullptr) {
  6706. Entity *e = entity_from_expr(proc);
  6707. if (e != nullptr && e->kind == Entity_Procedure) {
  6708. DeclInfo *decl = e->decl_info;
  6709. if (decl->proc_lit) {
  6710. ast_node(pl, ProcLit, decl->proc_lit);
  6711. if (pl->inlining == ProcInlining_no_inline) {
  6712. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6713. }
  6714. }
  6715. }
  6716. }
  6717. break;
  6718. case ProcInlining_no_inline:
  6719. break;
  6720. case ProcInlining_none:
  6721. if (proc != nullptr) {
  6722. Entity *e = entity_from_expr(proc);
  6723. if (e != nullptr && e->kind == Entity_Procedure) {
  6724. DeclInfo *decl = e->decl_info;
  6725. if (decl->proc_lit) {
  6726. ast_node(pl, ProcLit, decl->proc_lit);
  6727. if (pl->inlining == ProcInlining_inline) {
  6728. is_call_inlined = true;
  6729. }
  6730. }
  6731. }
  6732. }
  6733. }
  6734. {
  6735. String invalid;
  6736. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  6737. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  6738. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  6739. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  6740. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  6741. }
  6742. }
  6743. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  6744. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  6745. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  6746. }
  6747. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  6748. if (is_call_inlined) {
  6749. GB_ASSERT(c->curr_proc_decl);
  6750. GB_ASSERT(c->curr_proc_decl->entity);
  6751. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  6752. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  6753. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  6754. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  6755. }
  6756. }
  6757. }
  6758. }
  6759. operand->expr = call;
  6760. {
  6761. Type *type = nullptr;
  6762. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6763. type = type_of_expr(operand->expr->CallExpr.proc);
  6764. }
  6765. if (type == nullptr) {
  6766. type = pt;
  6767. }
  6768. type = base_type(type);
  6769. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6770. operand->mode = Addressing_OptionalOk;
  6771. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6772. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6773. operand->expr->CallExpr.optional_ok_one = true;
  6774. }
  6775. }
  6776. }
  6777. return Expr_Expr;
  6778. }
  6779. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6780. check_expr_base(c, o, e, t);
  6781. check_not_tuple(c, o);
  6782. char const *err_str = nullptr;
  6783. switch (o->mode) {
  6784. case Addressing_NoValue:
  6785. err_str = "used as a value";
  6786. break;
  6787. case Addressing_Type:
  6788. if (t == nullptr || !is_type_typeid(t)) {
  6789. err_str = "is not an expression but a type, in this context it is ambiguous";
  6790. }
  6791. break;
  6792. case Addressing_Builtin:
  6793. err_str = "must be called";
  6794. break;
  6795. }
  6796. if (err_str != nullptr) {
  6797. gbString str = expr_to_string(e);
  6798. error(e, "'%s' %s", str, err_str);
  6799. gb_string_free(str);
  6800. o->mode = Addressing_Invalid;
  6801. }
  6802. }
  6803. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6804. switch (t->kind) {
  6805. case Type_Basic:
  6806. if (t->Basic.kind == Basic_string) {
  6807. if (o->mode == Addressing_Constant) {
  6808. *max_count = o->value.value_string.len;
  6809. }
  6810. if (o->mode != Addressing_Constant) {
  6811. o->mode = Addressing_Value;
  6812. }
  6813. o->type = t_u8;
  6814. return true;
  6815. } else if (t->Basic.kind == Basic_UntypedString) {
  6816. if (o->mode == Addressing_Constant) {
  6817. *max_count = o->value.value_string.len;
  6818. o->type = t_u8;
  6819. return true;
  6820. }
  6821. return false;
  6822. }
  6823. break;
  6824. case Type_MultiPointer:
  6825. o->type = t->MultiPointer.elem;
  6826. if (o->mode != Addressing_Constant) {
  6827. o->mode = Addressing_Variable;
  6828. }
  6829. return true;
  6830. case Type_Array:
  6831. *max_count = t->Array.count;
  6832. if (indirection) {
  6833. o->mode = Addressing_Variable;
  6834. } else if (o->mode != Addressing_Variable &&
  6835. o->mode != Addressing_Constant) {
  6836. o->mode = Addressing_Value;
  6837. }
  6838. o->type = t->Array.elem;
  6839. return true;
  6840. case Type_EnumeratedArray:
  6841. *max_count = t->EnumeratedArray.count;
  6842. if (indirection) {
  6843. o->mode = Addressing_Variable;
  6844. } else if (o->mode != Addressing_Variable &&
  6845. o->mode != Addressing_Constant) {
  6846. o->mode = Addressing_Value;
  6847. }
  6848. o->type = t->EnumeratedArray.elem;
  6849. return true;
  6850. case Type_Matrix:
  6851. if (indirection) {
  6852. o->mode = Addressing_Variable;
  6853. } else if (o->mode != Addressing_Variable) {
  6854. o->mode = Addressing_Value;
  6855. }
  6856. if (t->Matrix.is_row_major) {
  6857. *max_count = t->Matrix.row_count;
  6858. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  6859. } else {
  6860. *max_count = t->Matrix.column_count;
  6861. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6862. }
  6863. return true;
  6864. case Type_Slice:
  6865. o->type = t->Slice.elem;
  6866. if (o->mode != Addressing_Constant) {
  6867. o->mode = Addressing_Variable;
  6868. }
  6869. return true;
  6870. case Type_RelativeMultiPointer:
  6871. {
  6872. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6873. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6874. o->type = pointer_type->MultiPointer.elem;
  6875. if (o->mode != Addressing_Constant) {
  6876. o->mode = Addressing_Variable;
  6877. }
  6878. }
  6879. return true;
  6880. case Type_DynamicArray:
  6881. o->type = t->DynamicArray.elem;
  6882. if (o->mode != Addressing_Constant) {
  6883. o->mode = Addressing_Variable;
  6884. }
  6885. return true;
  6886. case Type_Struct:
  6887. if (t->Struct.soa_kind != StructSoa_None) {
  6888. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6889. *max_count = t->Struct.soa_count;
  6890. }
  6891. o->type = t->Struct.soa_elem;
  6892. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  6893. o->mode = Addressing_SoaVariable;
  6894. } else {
  6895. o->mode = Addressing_Value;
  6896. }
  6897. return true;
  6898. }
  6899. return false;
  6900. }
  6901. if (is_type_pointer(original_type) && indirection) {
  6902. Type *ptr = base_type(original_type);
  6903. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  6904. o->type = ptr->MultiPointer.elem;
  6905. o->mode = Addressing_Value;
  6906. return true;
  6907. }
  6908. }
  6909. return false;
  6910. }
  6911. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6912. if (is_type_untyped_uninit(x)) {
  6913. return true;
  6914. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6915. return true;
  6916. } else if (is_type_untyped_uninit(y)) {
  6917. return true;
  6918. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6919. return true;
  6920. }
  6921. return are_types_identical(x, y);
  6922. }
  6923. gb_internal bool check_range(CheckerContext *c, Ast *node, bool is_for_loop, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  6924. if (!is_ast_range(node)) {
  6925. return false;
  6926. }
  6927. ast_node(ie, BinaryExpr, node);
  6928. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6929. if (x->mode == Addressing_Invalid) {
  6930. return false;
  6931. }
  6932. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6933. if (y->mode == Addressing_Invalid) {
  6934. return false;
  6935. }
  6936. convert_to_typed(c, x, y->type);
  6937. if (x->mode == Addressing_Invalid) {
  6938. return false;
  6939. }
  6940. convert_to_typed(c, y, x->type);
  6941. if (y->mode == Addressing_Invalid) {
  6942. return false;
  6943. }
  6944. convert_to_typed(c, x, default_type(y->type));
  6945. if (x->mode == Addressing_Invalid) {
  6946. return false;
  6947. }
  6948. convert_to_typed(c, y, default_type(x->type));
  6949. if (y->mode == Addressing_Invalid) {
  6950. return false;
  6951. }
  6952. if (!are_types_identical(x->type, y->type)) {
  6953. if (x->type != t_invalid &&
  6954. y->type != t_invalid) {
  6955. gbString xt = type_to_string(x->type);
  6956. gbString yt = type_to_string(y->type);
  6957. gbString expr_str = expr_to_string(x->expr);
  6958. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6959. gb_string_free(expr_str);
  6960. gb_string_free(yt);
  6961. gb_string_free(xt);
  6962. }
  6963. return false;
  6964. }
  6965. Type *type = x->type;
  6966. if (is_for_loop) {
  6967. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6968. error(ie->op, "Only numerical types are allowed within interval expressions");
  6969. return false;
  6970. }
  6971. } else {
  6972. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6973. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6974. return false;
  6975. }
  6976. }
  6977. if (x->mode == Addressing_Constant &&
  6978. y->mode == Addressing_Constant) {
  6979. ExactValue a = x->value;
  6980. ExactValue b = y->value;
  6981. GB_ASSERT(are_types_identical(x->type, y->type));
  6982. TokenKind op = Token_Lt;
  6983. switch (ie->op.kind) {
  6984. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6985. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6986. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6987. default: error(ie->op, "Invalid range operator"); break;
  6988. }
  6989. bool ok = compare_exact_values(op, a, b);
  6990. if (!ok) {
  6991. // TODO(bill): Better error message
  6992. error(ie->op, "Invalid interval range");
  6993. return false;
  6994. }
  6995. ExactValue inline_for_depth = exact_value_sub(b, a);
  6996. if (ie->op.kind != Token_RangeHalf) {
  6997. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6998. }
  6999. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7000. } else if (inline_for_depth_ != nullptr) {
  7001. error(ie->op, "Interval expressions must be constant");
  7002. return false;
  7003. }
  7004. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7005. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7006. return true;
  7007. }
  7008. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7009. if (is_operand_nil(*o)) {
  7010. return true;
  7011. }
  7012. Ast *expr = unparen_expr(o->expr);
  7013. if (expr != nullptr) {
  7014. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7015. if (e != nullptr && e->kind == Entity_Procedure) {
  7016. return true;
  7017. }
  7018. if (expr->kind == Ast_ProcLit) {
  7019. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7020. return true;
  7021. }
  7022. }
  7023. return o->mode == Addressing_Constant;
  7024. }
  7025. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7026. if (is_type_enum(th)) {
  7027. Type *enum_type = base_type(th);
  7028. GB_ASSERT(enum_type->kind == Type_Enum);
  7029. String name = ise->selector->Ident.token.string;
  7030. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7031. if (e == nullptr) {
  7032. return false;
  7033. }
  7034. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7035. GB_ASSERT(e->kind == Entity_Constant);
  7036. o->value = e->Constant.value;
  7037. o->mode = Addressing_Constant;
  7038. o->type = e->type;
  7039. return true;
  7040. }
  7041. if (is_type_union(th)) {
  7042. TEMPORARY_ALLOCATOR_GUARD();
  7043. Type *union_type = base_type(th);
  7044. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7045. for (Type *vt : union_type->Union.variants) {
  7046. Operand x = {};
  7047. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7048. array_add(&operands, x);
  7049. }
  7050. }
  7051. if (operands.count == 1) {
  7052. *o = operands[0];
  7053. return true;
  7054. }
  7055. }
  7056. return false;
  7057. }
  7058. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7059. ast_node(ise, ImplicitSelectorExpr, node);
  7060. o->type = t_invalid;
  7061. o->expr = node;
  7062. o->mode = Addressing_Invalid;
  7063. Type *th = type_hint;
  7064. if (th == nullptr) {
  7065. gbString str = expr_to_string(node);
  7066. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7067. gb_string_free(str);
  7068. return Expr_Expr;
  7069. }
  7070. o->type = th;
  7071. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7072. if (!ok) {
  7073. String name = ise->selector->Ident.token.string;
  7074. if (is_type_enum(th)) {
  7075. ERROR_BLOCK();
  7076. Type *bt = base_type(th);
  7077. GB_ASSERT(bt->kind == Type_Enum);
  7078. gbString typ = type_to_string(th);
  7079. defer (gb_string_free(typ));
  7080. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7081. check_did_you_mean_type(name, bt->Enum.fields);
  7082. } else {
  7083. gbString typ = type_to_string(th);
  7084. gbString str = expr_to_string(node);
  7085. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7086. gb_string_free(str);
  7087. gb_string_free(typ);
  7088. }
  7089. }
  7090. o->expr = node;
  7091. return Expr_Expr;
  7092. }
  7093. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7094. switch (x->mode) {
  7095. case Addressing_MapIndex:
  7096. case Addressing_OptionalOk:
  7097. case Addressing_OptionalOkPtr:
  7098. if (val_type_) *val_type_ = x->type;
  7099. break;
  7100. default:
  7101. if (ok_type_) *ok_type_ = x->type;
  7102. return;
  7103. }
  7104. Ast *expr = unparen_expr(x->expr);
  7105. if (expr->kind == Ast_CallExpr) {
  7106. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7107. if (is_type_proc(pt)) {
  7108. Type *tuple = pt->Proc.results;
  7109. if (pt->Proc.result_count >= 2) {
  7110. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7111. }
  7112. if (change_operand) {
  7113. expr->CallExpr.optional_ok_one = false;
  7114. x->type = tuple;
  7115. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7116. }
  7117. return;
  7118. }
  7119. }
  7120. Type *tuple = make_optional_ok_type(x->type);
  7121. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7122. if (change_operand) {
  7123. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7124. x->type = tuple;
  7125. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7126. }
  7127. }
  7128. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7129. ast_node(ie, MatrixIndexExpr, node);
  7130. check_expr(c, o, ie->expr);
  7131. node->viral_state_flags |= ie->expr->viral_state_flags;
  7132. if (o->mode == Addressing_Invalid) {
  7133. o->expr = node;
  7134. return;
  7135. }
  7136. Type *t = base_type(type_deref(o->type));
  7137. bool is_ptr = is_type_pointer(o->type);
  7138. bool is_const = o->mode == Addressing_Constant;
  7139. if (t->kind != Type_Matrix) {
  7140. gbString str = expr_to_string(o->expr);
  7141. gbString type_str = type_to_string(o->type);
  7142. defer (gb_string_free(str));
  7143. defer (gb_string_free(type_str));
  7144. if (is_const) {
  7145. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7146. } else {
  7147. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7148. }
  7149. o->mode = Addressing_Invalid;
  7150. o->expr = node;
  7151. return;
  7152. }
  7153. o->type = t->Matrix.elem;
  7154. if (is_ptr) {
  7155. o->mode = Addressing_Variable;
  7156. } else if (o->mode != Addressing_Variable) {
  7157. o->mode = Addressing_Value;
  7158. }
  7159. if (ie->row_index == nullptr) {
  7160. gbString str = expr_to_string(o->expr);
  7161. error(o->expr, "Missing row index for '%s'", str);
  7162. gb_string_free(str);
  7163. o->mode = Addressing_Invalid;
  7164. o->expr = node;
  7165. return;
  7166. }
  7167. if (ie->column_index == nullptr) {
  7168. gbString str = expr_to_string(o->expr);
  7169. error(o->expr, "Missing column index for '%s'", str);
  7170. gb_string_free(str);
  7171. o->mode = Addressing_Invalid;
  7172. o->expr = node;
  7173. return;
  7174. }
  7175. i64 row_count = t->Matrix.row_count;
  7176. i64 column_count = t->Matrix.column_count;
  7177. i64 row_index = 0;
  7178. i64 column_index = 0;
  7179. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7180. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7181. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7182. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7183. }
  7184. gb_unused(row_ok);
  7185. gb_unused(column_ok);
  7186. }
  7187. struct TypeAndToken {
  7188. Type *type;
  7189. Token token;
  7190. };
  7191. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7192. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7193. if (operand.mode != Addressing_Constant) {
  7194. return;
  7195. }
  7196. if (operand.value.kind == ExactValue_Invalid) {
  7197. return;
  7198. }
  7199. uintptr key = hash_exact_value(operand.value);
  7200. GB_ASSERT(key != 0);
  7201. isize count = multi_map_count(seen, key);
  7202. if (count) {
  7203. TEMPORARY_ALLOCATOR_GUARD();
  7204. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7205. multi_map_get_all(seen, key, taps);
  7206. for (isize i = 0; i < count; i++) {
  7207. TypeAndToken tap = taps[i];
  7208. Operand to = {};
  7209. to.mode = Addressing_Value;
  7210. to.type = tap.type;
  7211. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7212. continue;
  7213. }
  7214. TokenPos pos = tap.token.pos;
  7215. if (use_expr) {
  7216. gbString expr_str = expr_to_string(operand.expr);
  7217. error(operand.expr,
  7218. "Duplicate case '%s'\n"
  7219. "\tprevious case at %s",
  7220. expr_str,
  7221. token_pos_to_string(pos));
  7222. gb_string_free(expr_str);
  7223. } else {
  7224. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7225. }
  7226. return;
  7227. }
  7228. }
  7229. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7230. multi_map_insert(seen, key, tap);
  7231. }
  7232. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7233. if (is_type_enum(x.type)) {
  7234. // TODO(bill): Fix this logic so it's fast!!!
  7235. i64 v0 = exact_value_to_i64(lhs.value);
  7236. i64 v1 = exact_value_to_i64(rhs.value);
  7237. Operand v = {};
  7238. v.mode = Addressing_Constant;
  7239. v.type = x.type;
  7240. v.expr = x.expr;
  7241. Type *bt = base_type(x.type);
  7242. GB_ASSERT(bt->kind == Type_Enum);
  7243. for (i64 vi = v0; vi <= v1; vi++) {
  7244. if (upper_op != Token_LtEq && vi == v1) {
  7245. break;
  7246. }
  7247. v.value = exact_value_i64(vi);
  7248. add_constant_switch_case(ctx, seen, v);
  7249. }
  7250. } else {
  7251. add_constant_switch_case(ctx, seen, lhs);
  7252. if (upper_op == Token_LtEq) {
  7253. add_constant_switch_case(ctx, seen, rhs);
  7254. }
  7255. }
  7256. }
  7257. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7258. add_constant_switch_case(ctx, seen, x);
  7259. }
  7260. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7261. ast_node(bd, BasicDirective, node);
  7262. ExprKind kind = Expr_Expr;
  7263. o->mode = Addressing_Constant;
  7264. String name = bd->name.string;
  7265. if (name == "file") {
  7266. String file = get_file_path_string(bd->token.pos.file_id);
  7267. if (build_context.obfuscate_source_code_locations) {
  7268. file = obfuscate_string(file, "F");
  7269. }
  7270. o->type = t_untyped_string;
  7271. o->value = exact_value_string(file);
  7272. } else if (name == "line") {
  7273. i32 line = bd->token.pos.line;
  7274. if (build_context.obfuscate_source_code_locations) {
  7275. line = obfuscate_i32(line);
  7276. }
  7277. o->type = t_untyped_integer;
  7278. o->value = exact_value_i64(line);
  7279. } else if (name == "procedure") {
  7280. if (c->curr_proc_decl == nullptr) {
  7281. error(node, "#procedure may only be used within procedures");
  7282. o->type = t_untyped_string;
  7283. o->value = exact_value_string(str_lit(""));
  7284. } else {
  7285. String p = c->proc_name;
  7286. if (build_context.obfuscate_source_code_locations) {
  7287. p = obfuscate_string(p, "P");
  7288. }
  7289. o->type = t_untyped_string;
  7290. o->value = exact_value_string(p);
  7291. }
  7292. } else if (name == "caller_location") {
  7293. init_core_source_code_location(c->checker);
  7294. error(node, "#caller_location may only be used as a default argument parameter");
  7295. o->type = t_source_code_location;
  7296. o->mode = Addressing_Value;
  7297. } else {
  7298. if (name == "location") {
  7299. init_core_source_code_location(c->checker);
  7300. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7301. o->type = t_source_code_location;
  7302. o->mode = Addressing_Value;
  7303. } else if (
  7304. name == "assert" ||
  7305. name == "defined" ||
  7306. name == "config" ||
  7307. name == "exists" ||
  7308. name == "load" ||
  7309. name == "load_hash" ||
  7310. name == "load_directory" ||
  7311. name == "load_or"
  7312. ) {
  7313. error(node, "'#%.*s' must be used as a call", LIT(name));
  7314. o->type = t_invalid;
  7315. o->mode = Addressing_Invalid;
  7316. } else {
  7317. error(node, "Unknown directive: #%.*s", LIT(name));
  7318. o->type = t_invalid;
  7319. o->mode = Addressing_Invalid;
  7320. }
  7321. }
  7322. return kind;
  7323. }
  7324. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7325. ExprKind kind = Expr_Expr;
  7326. Operand cond = {Addressing_Invalid};
  7327. ast_node(te, TernaryIfExpr, node);
  7328. check_expr(c, &cond, te->cond);
  7329. node->viral_state_flags |= te->cond->viral_state_flags;
  7330. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7331. error(te->cond, "Non-boolean condition in ternary if expression");
  7332. }
  7333. Operand x = {Addressing_Invalid};
  7334. Operand y = {Addressing_Invalid};
  7335. check_expr_or_type(c, &x, te->x, type_hint);
  7336. node->viral_state_flags |= te->x->viral_state_flags;
  7337. if (te->y != nullptr) {
  7338. Type *th = type_hint;
  7339. if (type_hint == nullptr && is_type_typed(x.type)) {
  7340. th = x.type;
  7341. }
  7342. check_expr_or_type(c, &y, te->y, th);
  7343. node->viral_state_flags |= te->y->viral_state_flags;
  7344. } else {
  7345. error(node, "A ternary expression must have an else clause");
  7346. return kind;
  7347. }
  7348. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7349. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7350. gbString type_string = expr_to_string(type_expr);
  7351. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7352. gb_string_free(type_string);
  7353. return kind;
  7354. }
  7355. if (x.type == nullptr || x.type == t_invalid ||
  7356. y.type == nullptr || y.type == t_invalid) {
  7357. return kind;
  7358. }
  7359. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7360. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7361. if (x.mode == Addressing_Invalid) {
  7362. return kind;
  7363. }
  7364. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7365. if (y.mode == Addressing_Invalid) {
  7366. x.mode = Addressing_Invalid;
  7367. return kind;
  7368. }
  7369. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7370. // x: union{f32} = f32(123) if cond else nil
  7371. if (type_hint && !is_type_any(type_hint)) {
  7372. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7373. check_cast(c, &x, type_hint);
  7374. check_cast(c, &y, type_hint);
  7375. }
  7376. }
  7377. if (!ternary_compare_types(x.type, y.type)) {
  7378. gbString its = type_to_string(x.type);
  7379. gbString ets = type_to_string(y.type);
  7380. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7381. gb_string_free(ets);
  7382. gb_string_free(its);
  7383. return kind;
  7384. }
  7385. o->type = x.type;
  7386. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7387. o->type = y.type;
  7388. }
  7389. o->mode = Addressing_Value;
  7390. o->expr = node;
  7391. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7392. if (check_cast_internal(c, &x, type_hint) &&
  7393. check_cast_internal(c, &y, type_hint)) {
  7394. convert_to_typed(c, o, type_hint);
  7395. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7396. o->type = type_hint;
  7397. }
  7398. }
  7399. return kind;
  7400. }
  7401. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7402. ExprKind kind = Expr_Expr;
  7403. Operand cond = {};
  7404. ast_node(te, TernaryWhenExpr, node);
  7405. check_expr(c, &cond, te->cond);
  7406. node->viral_state_flags |= te->cond->viral_state_flags;
  7407. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7408. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7409. return kind;
  7410. }
  7411. if (cond.value.value_bool) {
  7412. check_expr_or_type(c, o, te->x, type_hint);
  7413. node->viral_state_flags |= te->x->viral_state_flags;
  7414. } else {
  7415. if (te->y != nullptr) {
  7416. check_expr_or_type(c, o, te->y, type_hint);
  7417. node->viral_state_flags |= te->y->viral_state_flags;
  7418. } else {
  7419. error(node, "A ternary when expression must have an else clause");
  7420. return kind;
  7421. }
  7422. }
  7423. return kind;
  7424. }
  7425. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7426. ast_node(oe, OrElseExpr, node);
  7427. String name = oe->token.string;
  7428. Ast *arg = oe->x;
  7429. Ast *default_value = oe->y;
  7430. Operand x = {};
  7431. Operand y = {};
  7432. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7433. if (is_load_directive_call(arg)) {
  7434. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7435. // Allow for chaining of '#load(path) or_else #load(path)'
  7436. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7437. bool y_is_diverging = false;
  7438. check_expr_base(c, &y, default_value, x.type);
  7439. switch (y.mode) {
  7440. case Addressing_NoValue:
  7441. if (is_diverging_expr(y.expr)) {
  7442. // Allow
  7443. y.mode = Addressing_Value;
  7444. y_is_diverging = true;
  7445. } else {
  7446. error_operand_no_value(&y);
  7447. y.mode = Addressing_Invalid;
  7448. }
  7449. break;
  7450. case Addressing_Type:
  7451. error_operand_not_expression(&y);
  7452. y.mode = Addressing_Invalid;
  7453. break;
  7454. }
  7455. if (y.mode == Addressing_Invalid) {
  7456. o->mode = Addressing_Value;
  7457. o->type = t_invalid;
  7458. o->expr = node;
  7459. return Expr_Expr;
  7460. }
  7461. if (!y_is_diverging) {
  7462. check_assignment(c, &y, x.type, name);
  7463. if (y.mode != Addressing_Constant) {
  7464. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7465. }
  7466. }
  7467. }
  7468. if (res == LoadDirective_Success) {
  7469. *o = x;
  7470. } else {
  7471. *o = y;
  7472. }
  7473. o->expr = node;
  7474. return Expr_Expr;
  7475. }
  7476. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7477. if (x.mode == Addressing_Invalid) {
  7478. o->mode = Addressing_Value;
  7479. o->type = t_invalid;
  7480. o->expr = node;
  7481. return Expr_Expr;
  7482. }
  7483. bool y_is_diverging = false;
  7484. check_expr_base(c, &y, default_value, x.type);
  7485. switch (y.mode) {
  7486. case Addressing_NoValue:
  7487. if (is_diverging_expr(y.expr)) {
  7488. // Allow
  7489. y.mode = Addressing_Value;
  7490. y_is_diverging = true;
  7491. } else {
  7492. error_operand_no_value(&y);
  7493. y.mode = Addressing_Invalid;
  7494. }
  7495. break;
  7496. case Addressing_Type:
  7497. error_operand_not_expression(&y);
  7498. y.mode = Addressing_Invalid;
  7499. break;
  7500. }
  7501. if (y.mode == Addressing_Invalid) {
  7502. o->mode = Addressing_Value;
  7503. o->type = t_invalid;
  7504. o->expr = node;
  7505. return Expr_Expr;
  7506. }
  7507. Type *left_type = nullptr;
  7508. Type *right_type = nullptr;
  7509. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7510. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7511. if (left_type != nullptr) {
  7512. if (!y_is_diverging) {
  7513. check_assignment(c, &y, left_type, name);
  7514. }
  7515. } else {
  7516. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7517. }
  7518. if (left_type == nullptr) {
  7519. left_type = t_invalid;
  7520. }
  7521. o->mode = Addressing_Value;
  7522. o->type = left_type;
  7523. o->expr = node;
  7524. return Expr_Expr;
  7525. }
  7526. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7527. ast_node(re, OrReturnExpr, node);
  7528. String name = re->token.string;
  7529. Operand x = {};
  7530. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7531. if (x.mode == Addressing_Invalid) {
  7532. o->mode = Addressing_Value;
  7533. o->type = t_invalid;
  7534. o->expr = node;
  7535. return Expr_Expr;
  7536. }
  7537. Type *left_type = nullptr;
  7538. Type *right_type = nullptr;
  7539. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7540. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7541. if (right_type == nullptr) {
  7542. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7543. } else {
  7544. Type *proc_type = base_type(c->curr_proc_sig);
  7545. GB_ASSERT(proc_type->kind == Type_Proc);
  7546. Type *result_type = proc_type->Proc.results;
  7547. if (result_type == nullptr) {
  7548. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7549. } else {
  7550. GB_ASSERT(result_type->kind == Type_Tuple);
  7551. auto const &vars = result_type->Tuple.variables;
  7552. Type *end_type = vars[vars.count-1]->type;
  7553. if (vars.count > 1) {
  7554. if (!proc_type->Proc.has_named_results) {
  7555. 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));
  7556. }
  7557. }
  7558. Operand rhs = {};
  7559. rhs.type = right_type;
  7560. rhs.mode = Addressing_Value;
  7561. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7562. // NOTE(bill): allow implicit conversion between boolean types
  7563. // within 'or_return' to improve the experience using third-party code
  7564. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7565. ERROR_BLOCK();
  7566. // TODO(bill): better error message
  7567. gbString a = type_to_string(right_type);
  7568. gbString b = type_to_string(end_type);
  7569. gbString ret_type = type_to_string(result_type);
  7570. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7571. if (vars.count == 1) {
  7572. error_line("\tProcedure return value type: %s\n", ret_type);
  7573. } else {
  7574. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7575. }
  7576. gb_string_free(ret_type);
  7577. gb_string_free(b);
  7578. gb_string_free(a);
  7579. }
  7580. }
  7581. }
  7582. o->expr = node;
  7583. o->type = left_type;
  7584. if (left_type != nullptr) {
  7585. o->mode = Addressing_Value;
  7586. } else {
  7587. o->mode = Addressing_NoValue;
  7588. }
  7589. if (c->curr_proc_sig == nullptr) {
  7590. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7591. }
  7592. if (c->in_defer) {
  7593. error(node, "'or_return' cannot be used within a defer statement");
  7594. }
  7595. return Expr_Expr;
  7596. }
  7597. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7598. ast_node(be, OrBranchExpr, node);
  7599. String name = be->token.string;
  7600. Operand x = {};
  7601. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7602. if (x.mode == Addressing_Invalid) {
  7603. o->mode = Addressing_Value;
  7604. o->type = t_invalid;
  7605. o->expr = node;
  7606. return Expr_Expr;
  7607. }
  7608. Type *left_type = nullptr;
  7609. Type *right_type = nullptr;
  7610. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7611. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7612. if (right_type == nullptr) {
  7613. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7614. } else {
  7615. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7616. // okay
  7617. } else {
  7618. gbString s = type_to_string(right_type);
  7619. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7620. gb_string_free(s);
  7621. }
  7622. }
  7623. o->expr = node;
  7624. o->type = left_type;
  7625. if (left_type != nullptr) {
  7626. o->mode = Addressing_Value;
  7627. } else {
  7628. o->mode = Addressing_NoValue;
  7629. }
  7630. if (c->curr_proc_sig == nullptr) {
  7631. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7632. }
  7633. Ast *label = be->label;
  7634. switch (be->token.kind) {
  7635. case Token_or_break:
  7636. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  7637. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7638. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7639. }
  7640. break;
  7641. case Token_or_continue:
  7642. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7643. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7644. }
  7645. break;
  7646. }
  7647. if (label != nullptr) {
  7648. if (label->kind != Ast_Ident) {
  7649. error(label, "A branch statement's label name must be an identifier");
  7650. return Expr_Expr;
  7651. }
  7652. Ast *ident = label;
  7653. String name = ident->Ident.token.string;
  7654. Operand o = {};
  7655. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7656. if (e == nullptr) {
  7657. error(ident, "Undeclared label name: %.*s", LIT(name));
  7658. return Expr_Expr;
  7659. }
  7660. add_entity_use(c, ident, e);
  7661. if (e->kind != Entity_Label) {
  7662. error(ident, "'%.*s' is not a label", LIT(name));
  7663. return Expr_Expr;
  7664. }
  7665. Ast *parent = e->Label.parent;
  7666. GB_ASSERT(parent != nullptr);
  7667. switch (parent->kind) {
  7668. case Ast_BlockStmt:
  7669. case Ast_IfStmt:
  7670. case Ast_SwitchStmt:
  7671. if (be->token.kind != Token_or_break) {
  7672. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7673. }
  7674. break;
  7675. case Ast_RangeStmt:
  7676. case Ast_ForStmt:
  7677. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7678. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7679. }
  7680. break;
  7681. }
  7682. }
  7683. return Expr_Expr;
  7684. }
  7685. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7686. Type *bt = base_type(type);
  7687. StringSet fields_visited = {};
  7688. defer (string_set_destroy(&fields_visited));
  7689. StringMap<String> fields_visited_through_raw_union = {};
  7690. defer (string_map_destroy(&fields_visited_through_raw_union));
  7691. String assignment_str = str_lit("structure literal");
  7692. if (bt->kind == Type_BitField) {
  7693. assignment_str = str_lit("bit_field literal");
  7694. }
  7695. for (Ast *elem : elems) {
  7696. if (elem->kind != Ast_FieldValue) {
  7697. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7698. continue;
  7699. }
  7700. ast_node(fv, FieldValue, elem);
  7701. Ast *ident = fv->field;
  7702. if (ident->kind == Ast_ImplicitSelectorExpr) {
  7703. gbString expr_str = expr_to_string(ident);
  7704. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  7705. gb_string_free(expr_str);
  7706. ident = ident->ImplicitSelectorExpr.selector;
  7707. }
  7708. if (ident->kind != Ast_Ident) {
  7709. gbString expr_str = expr_to_string(ident);
  7710. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7711. gb_string_free(expr_str);
  7712. continue;
  7713. }
  7714. String name = ident->Ident.token.string;
  7715. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7716. bool is_unknown = sel.entity == nullptr;
  7717. if (is_unknown) {
  7718. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  7719. continue;
  7720. }
  7721. Entity *field = nullptr;
  7722. if (bt->kind == Type_Struct) {
  7723. field = bt->Struct.fields[sel.index[0]];
  7724. } else if (bt->kind == Type_BitField) {
  7725. field = bt->BitField.fields[sel.index[0]];
  7726. } else {
  7727. GB_PANIC("Unknown type");
  7728. }
  7729. add_entity_use(c, ident, field);
  7730. if (string_set_update(&fields_visited, name)) {
  7731. if (sel.index.count > 1) {
  7732. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7733. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7734. } else {
  7735. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  7736. }
  7737. } else {
  7738. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  7739. }
  7740. continue;
  7741. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7742. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7743. continue;
  7744. }
  7745. if (sel.indirect) {
  7746. error(ident, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a %.*s", cast(int)sel.index.count-1, LIT(name), LIT(assignment_str));
  7747. continue;
  7748. }
  7749. if (sel.index.count > 1) {
  7750. GB_ASSERT(bt->kind == Type_Struct);
  7751. if (is_constant) {
  7752. Type *ft = type;
  7753. for (i32 index : sel.index) {
  7754. Type *bt = base_type(ft);
  7755. switch (bt->kind) {
  7756. case Type_Struct:
  7757. if (bt->Struct.is_raw_union) {
  7758. is_constant = false;
  7759. break;
  7760. }
  7761. ft = bt->Struct.fields[index]->type;
  7762. break;
  7763. case Type_Array:
  7764. ft = bt->Array.elem;
  7765. break;
  7766. case Type_BitField:
  7767. is_constant = false;
  7768. ft = bt->BitField.fields[index]->type;
  7769. break;
  7770. default:
  7771. GB_PANIC("invalid type: %s", type_to_string(ft));
  7772. break;
  7773. }
  7774. }
  7775. if (is_constant &&
  7776. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7777. is_constant = false;
  7778. }
  7779. }
  7780. Type *nested_ft = bt;
  7781. for (i32 index : sel.index) {
  7782. Type *bt = base_type(nested_ft);
  7783. switch (bt->kind) {
  7784. case Type_Struct:
  7785. if (bt->Struct.is_raw_union) {
  7786. for (Entity *re : bt->Struct.fields) {
  7787. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7788. }
  7789. }
  7790. nested_ft = bt->Struct.fields[index]->type;
  7791. break;
  7792. case Type_Array:
  7793. nested_ft = bt->Array.elem;
  7794. break;
  7795. case Type_BitField:
  7796. nested_ft = bt->BitField.fields[index]->type;
  7797. break;
  7798. default:
  7799. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7800. break;
  7801. }
  7802. }
  7803. field = sel.entity;
  7804. }
  7805. Operand o = {};
  7806. check_expr_or_type(c, &o, fv->value, field->type);
  7807. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7808. is_constant = false;
  7809. }
  7810. if (is_constant) {
  7811. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7812. }
  7813. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  7814. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  7815. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  7816. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  7817. }
  7818. check_assignment(c, &o, field->type, assignment_str);
  7819. c->bit_field_bit_size = prev_bit_field_bit_size;
  7820. }
  7821. }
  7822. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  7823. type_expr = unparen_expr(type_expr);
  7824. if (type_expr == nullptr) {
  7825. return false;
  7826. }
  7827. // [?]Type
  7828. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7829. Ast *count = type_expr->ArrayType.count;
  7830. if (count->kind == Ast_UnaryExpr &&
  7831. count->UnaryExpr.op.kind == Token_Question) {
  7832. return true;
  7833. }
  7834. }
  7835. return false;
  7836. }
  7837. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7838. ExprKind kind = Expr_Expr;
  7839. ast_node(cl, CompoundLit, node);
  7840. Type *type = type_hint;
  7841. if (type != nullptr && is_type_untyped(type)) {
  7842. type = nullptr;
  7843. }
  7844. bool is_to_be_determined_array_count = false;
  7845. bool is_constant = true;
  7846. Ast *type_expr = cl->type;
  7847. bool used_type_hint_expr = false;
  7848. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  7849. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  7850. type_expr = clone_ast(c->type_hint_expr);
  7851. used_type_hint_expr = true;
  7852. }
  7853. }
  7854. if (type_expr != nullptr) {
  7855. type = nullptr;
  7856. // [?]Type
  7857. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7858. Ast *count = type_expr->ArrayType.count;
  7859. if (count->kind == Ast_UnaryExpr &&
  7860. count->UnaryExpr.op.kind == Token_Question) {
  7861. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  7862. is_to_be_determined_array_count = true;
  7863. }
  7864. if (cl->elems.count > 0) {
  7865. if (type_expr->ArrayType.tag != nullptr) {
  7866. Ast *tag = type_expr->ArrayType.tag;
  7867. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7868. String name = tag->BasicDirective.name.string;
  7869. if (name == "soa") {
  7870. error(node, "#soa arrays are not supported for compound literals");
  7871. return kind;
  7872. }
  7873. }
  7874. }
  7875. }
  7876. if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  7877. if (cl->elems.count > 0) {
  7878. Ast *tag = type_expr->DynamicArrayType.tag;
  7879. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7880. String name = tag->BasicDirective.name.string;
  7881. if (name == "soa") {
  7882. error(node, "#soa arrays are not supported for compound literals");
  7883. return kind;
  7884. }
  7885. }
  7886. }
  7887. if (type == nullptr) {
  7888. type = check_type(c, type_expr);
  7889. }
  7890. }
  7891. if (type == nullptr) {
  7892. error(node, "Missing type in compound literal");
  7893. return kind;
  7894. }
  7895. Type *t = base_type(type);
  7896. if (is_type_polymorphic(t)) {
  7897. gbString str = type_to_string(type);
  7898. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7899. o->expr = node;
  7900. o->type = type;
  7901. gb_string_free(str);
  7902. return kind;
  7903. }
  7904. switch (t->kind) {
  7905. case Type_Struct: {
  7906. if (cl->elems.count == 0) {
  7907. break; // NOTE(bill): No need to init
  7908. }
  7909. if (t->Struct.is_raw_union) {
  7910. if (cl->elems.count > 0) {
  7911. // NOTE: unions cannot be constant
  7912. is_constant = false;
  7913. if (cl->elems[0]->kind != Ast_FieldValue) {
  7914. gbString type_str = type_to_string(type);
  7915. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7916. gb_string_free(type_str);
  7917. } else {
  7918. if (cl->elems.count != 1) {
  7919. gbString type_str = type_to_string(type);
  7920. 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);
  7921. gb_string_free(type_str);
  7922. } else {
  7923. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7924. }
  7925. }
  7926. }
  7927. break;
  7928. }
  7929. wait_signal_until_available(&t->Struct.fields_wait_signal);
  7930. isize field_count = t->Struct.fields.count;
  7931. isize min_field_count = t->Struct.fields.count;
  7932. for (isize i = min_field_count-1; i >= 0; i--) {
  7933. Entity *e = t->Struct.fields[i];
  7934. GB_ASSERT(e->kind == Entity_Variable);
  7935. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7936. min_field_count--;
  7937. } else {
  7938. break;
  7939. }
  7940. }
  7941. if (cl->elems[0]->kind == Ast_FieldValue) {
  7942. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7943. } else {
  7944. bool seen_field_value = false;
  7945. for_array(index, cl->elems) {
  7946. Entity *field = nullptr;
  7947. Ast *elem = cl->elems[index];
  7948. if (elem->kind == Ast_FieldValue) {
  7949. seen_field_value = true;
  7950. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7951. continue;
  7952. } else if (seen_field_value) {
  7953. error(elem, "Value elements cannot be used after a 'field = value'");
  7954. continue;
  7955. }
  7956. if (index >= field_count) {
  7957. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7958. break;
  7959. }
  7960. if (field == nullptr) {
  7961. field = t->Struct.fields[index];
  7962. }
  7963. Operand o = {};
  7964. check_expr_or_type(c, &o, elem, field->type);
  7965. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7966. is_constant = false;
  7967. }
  7968. if (is_constant) {
  7969. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7970. }
  7971. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7972. }
  7973. if (cl->elems.count < field_count) {
  7974. if (min_field_count < field_count) {
  7975. if (cl->elems.count < min_field_count) {
  7976. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7977. }
  7978. } else {
  7979. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7980. }
  7981. }
  7982. }
  7983. break;
  7984. }
  7985. case Type_Slice:
  7986. case Type_Array:
  7987. case Type_DynamicArray:
  7988. case Type_SimdVector:
  7989. case Type_Matrix:
  7990. {
  7991. Type *elem_type = nullptr;
  7992. String context_name = {};
  7993. i64 max_type_count = -1;
  7994. if (t->kind == Type_Slice) {
  7995. elem_type = t->Slice.elem;
  7996. context_name = str_lit("slice literal");
  7997. } else if (t->kind == Type_Array) {
  7998. elem_type = t->Array.elem;
  7999. context_name = str_lit("array literal");
  8000. if (!is_to_be_determined_array_count) {
  8001. max_type_count = t->Array.count;
  8002. }
  8003. } else if (t->kind == Type_DynamicArray) {
  8004. elem_type = t->DynamicArray.elem;
  8005. context_name = str_lit("dynamic array literal");
  8006. is_constant = false;
  8007. if (!build_context.no_dynamic_literals) {
  8008. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8009. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8010. }
  8011. } else if (t->kind == Type_SimdVector) {
  8012. elem_type = t->SimdVector.elem;
  8013. context_name = str_lit("simd vector literal");
  8014. max_type_count = t->SimdVector.count;
  8015. } else if (t->kind == Type_Matrix) {
  8016. elem_type = t->Matrix.elem;
  8017. context_name = str_lit("matrix literal");
  8018. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8019. } else {
  8020. GB_PANIC("unreachable");
  8021. }
  8022. i64 max = 0;
  8023. Type *bet = base_type(elem_type);
  8024. if (!elem_type_can_be_constant(bet)) {
  8025. is_constant = false;
  8026. }
  8027. if (bet == t_invalid) {
  8028. break;
  8029. }
  8030. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8031. RangeCache rc = range_cache_make(heap_allocator());
  8032. defer (range_cache_destroy(&rc));
  8033. for (Ast *elem : cl->elems) {
  8034. if (elem->kind != Ast_FieldValue) {
  8035. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8036. continue;
  8037. }
  8038. ast_node(fv, FieldValue, elem);
  8039. if (is_ast_range(fv->field)) {
  8040. Token op = fv->field->BinaryExpr.op;
  8041. Operand x = {};
  8042. Operand y = {};
  8043. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8044. if (!ok) {
  8045. continue;
  8046. }
  8047. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8048. error(x.expr, "Expected a constant integer as an array field");
  8049. continue;
  8050. }
  8051. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8052. error(y.expr, "Expected a constant integer as an array field");
  8053. continue;
  8054. }
  8055. i64 lo = exact_value_to_i64(x.value);
  8056. i64 hi = exact_value_to_i64(y.value);
  8057. i64 max_index = hi;
  8058. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8059. hi -= 1;
  8060. } else { // .. (inclusive)
  8061. max_index += 1;
  8062. }
  8063. bool new_range = range_cache_add_range(&rc, lo, hi);
  8064. if (!new_range) {
  8065. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8066. continue;
  8067. }
  8068. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8069. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8070. continue;
  8071. }
  8072. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8073. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8074. continue;
  8075. }
  8076. if (max < hi) {
  8077. max = max_index;
  8078. }
  8079. Operand operand = {};
  8080. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8081. check_assignment(c, &operand, elem_type, context_name);
  8082. is_constant = is_constant && operand.mode == Addressing_Constant;
  8083. } else {
  8084. Operand op_index = {};
  8085. check_expr(c, &op_index, fv->field);
  8086. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8087. error(elem, "Expected a constant integer as an array field");
  8088. continue;
  8089. }
  8090. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8091. i64 index = exact_value_to_i64(op_index.value);
  8092. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8093. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8094. continue;
  8095. }
  8096. bool new_index = range_cache_add_index(&rc, index);
  8097. if (!new_index) {
  8098. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8099. continue;
  8100. }
  8101. if (max < index+1) {
  8102. max = index+1;
  8103. }
  8104. Operand operand = {};
  8105. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8106. check_assignment(c, &operand, elem_type, context_name);
  8107. is_constant = is_constant && operand.mode == Addressing_Constant;
  8108. }
  8109. }
  8110. cl->max_count = max;
  8111. } else {
  8112. isize index = 0;
  8113. for (; index < cl->elems.count; index++) {
  8114. Ast *e = cl->elems[index];
  8115. if (e == nullptr) {
  8116. error(node, "Invalid literal element");
  8117. continue;
  8118. }
  8119. if (e->kind == Ast_FieldValue) {
  8120. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8121. continue;
  8122. }
  8123. if (0 <= max_type_count && max_type_count <= index) {
  8124. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8125. }
  8126. Operand operand = {};
  8127. check_expr_with_type_hint(c, &operand, e, elem_type);
  8128. check_assignment(c, &operand, elem_type, context_name);
  8129. is_constant = is_constant && operand.mode == Addressing_Constant;
  8130. }
  8131. if (max < index) {
  8132. max = index;
  8133. }
  8134. }
  8135. if (t->kind == Type_Array) {
  8136. if (is_to_be_determined_array_count) {
  8137. t->Array.count = max;
  8138. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8139. if (0 < max && max < t->Array.count) {
  8140. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8141. }
  8142. }
  8143. }
  8144. if (t->kind == Type_SimdVector) {
  8145. if (!is_constant) {
  8146. // error(node, "Expected all constant elements for a simd vector");
  8147. }
  8148. }
  8149. if (t->kind == Type_DynamicArray) {
  8150. if (build_context.no_dynamic_literals && cl->elems.count) {
  8151. error(node, "Compound literals of dynamic types have been disabled");
  8152. }
  8153. }
  8154. if (t->kind == Type_Matrix) {
  8155. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8156. if (0 < max && max < max_type_count) {
  8157. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8158. }
  8159. }
  8160. }
  8161. break;
  8162. }
  8163. case Type_EnumeratedArray:
  8164. {
  8165. Type *elem_type = t->EnumeratedArray.elem;
  8166. Type *index_type = t->EnumeratedArray.index;
  8167. String context_name = str_lit("enumerated array literal");
  8168. i64 max_type_count = t->EnumeratedArray.count;
  8169. gbString index_type_str = type_to_string(index_type);
  8170. defer (gb_string_free(index_type_str));
  8171. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8172. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8173. String total_lo_string = {};
  8174. String total_hi_string = {};
  8175. GB_ASSERT(is_type_enum(index_type));
  8176. {
  8177. Type *bt = base_type(index_type);
  8178. GB_ASSERT(bt->kind == Type_Enum);
  8179. for (Entity *f : bt->Enum.fields) {
  8180. if (f->kind != Entity_Constant) {
  8181. continue;
  8182. }
  8183. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8184. total_lo_string = f->token.string;
  8185. }
  8186. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8187. total_hi_string = f->token.string;
  8188. }
  8189. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8190. break;
  8191. }
  8192. }
  8193. }
  8194. i64 max = 0;
  8195. Type *bet = base_type(elem_type);
  8196. if (!elem_type_can_be_constant(bet)) {
  8197. is_constant = false;
  8198. }
  8199. if (bet == t_invalid) {
  8200. break;
  8201. }
  8202. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8203. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8204. defer (map_destroy(&seen));
  8205. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8206. RangeCache rc = range_cache_make(heap_allocator());
  8207. defer (range_cache_destroy(&rc));
  8208. for (Ast *elem : cl->elems) {
  8209. if (elem->kind != Ast_FieldValue) {
  8210. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8211. continue;
  8212. }
  8213. ast_node(fv, FieldValue, elem);
  8214. if (is_ast_range(fv->field)) {
  8215. Token op = fv->field->BinaryExpr.op;
  8216. Operand x = {};
  8217. Operand y = {};
  8218. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8219. if (!ok) {
  8220. continue;
  8221. }
  8222. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8223. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8224. continue;
  8225. }
  8226. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8227. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8228. continue;
  8229. }
  8230. i64 lo = exact_value_to_i64(x.value);
  8231. i64 hi = exact_value_to_i64(y.value);
  8232. i64 max_index = hi;
  8233. if (op.kind == Token_RangeHalf) {
  8234. hi -= 1;
  8235. }
  8236. bool new_range = range_cache_add_range(&rc, lo, hi);
  8237. if (!new_range) {
  8238. gbString lo_str = expr_to_string(x.expr);
  8239. gbString hi_str = expr_to_string(y.expr);
  8240. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8241. gb_string_free(hi_str);
  8242. gb_string_free(lo_str);
  8243. continue;
  8244. }
  8245. // NOTE(bill): These are sanity checks for invalid enum values
  8246. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8247. gbString lo_str = expr_to_string(x.expr);
  8248. 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));
  8249. gb_string_free(lo_str);
  8250. continue;
  8251. }
  8252. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8253. gbString hi_str = expr_to_string(y.expr);
  8254. 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));
  8255. gb_string_free(hi_str);
  8256. continue;
  8257. }
  8258. if (max < hi) {
  8259. max = max_index;
  8260. }
  8261. Operand operand = {};
  8262. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8263. check_assignment(c, &operand, elem_type, context_name);
  8264. is_constant = is_constant && operand.mode == Addressing_Constant;
  8265. TokenKind upper_op = Token_LtEq;
  8266. if (op.kind == Token_RangeHalf) {
  8267. upper_op = Token_Lt;
  8268. }
  8269. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8270. } else {
  8271. Operand op_index = {};
  8272. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8273. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8274. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8275. continue;
  8276. }
  8277. i64 index = exact_value_to_i64(op_index.value);
  8278. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8279. gbString idx_str = expr_to_string(op_index.expr);
  8280. 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));
  8281. gb_string_free(idx_str);
  8282. continue;
  8283. }
  8284. bool new_index = range_cache_add_index(&rc, index);
  8285. if (!new_index) {
  8286. gbString idx_str = expr_to_string(op_index.expr);
  8287. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8288. gb_string_free(idx_str);
  8289. continue;
  8290. }
  8291. if (max < index+1) {
  8292. max = index+1;
  8293. }
  8294. Operand operand = {};
  8295. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8296. check_assignment(c, &operand, elem_type, context_name);
  8297. is_constant = is_constant && operand.mode == Addressing_Constant;
  8298. add_to_seen_map(c, &seen, op_index);
  8299. }
  8300. }
  8301. cl->max_count = max;
  8302. } else {
  8303. isize index = 0;
  8304. for (; index < cl->elems.count; index++) {
  8305. Ast *e = cl->elems[index];
  8306. if (e == nullptr) {
  8307. error(node, "Invalid literal element");
  8308. continue;
  8309. }
  8310. if (e->kind == Ast_FieldValue) {
  8311. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8312. continue;
  8313. }
  8314. if (0 <= max_type_count && max_type_count <= index) {
  8315. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8316. }
  8317. Operand operand = {};
  8318. check_expr_with_type_hint(c, &operand, e, elem_type);
  8319. check_assignment(c, &operand, elem_type, context_name);
  8320. is_constant = is_constant && operand.mode == Addressing_Constant;
  8321. }
  8322. if (max < index) {
  8323. max = index;
  8324. }
  8325. }
  8326. bool was_error = false;
  8327. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8328. if (0 < max && max < t->EnumeratedArray.count) {
  8329. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8330. was_error = true;
  8331. } else {
  8332. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8333. was_error = true;
  8334. }
  8335. }
  8336. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8337. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8338. TEMPORARY_ALLOCATOR_GUARD();
  8339. Type *et = base_type(index_type);
  8340. GB_ASSERT(et->kind == Type_Enum);
  8341. auto fields = et->Enum.fields;
  8342. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8343. for (Entity *f : fields) {
  8344. if (f->kind != Entity_Constant) {
  8345. continue;
  8346. }
  8347. ExactValue v = f->Constant.value;
  8348. uintptr hash = hash_exact_value(v);
  8349. auto found = map_get(&seen, hash);
  8350. if (!found) {
  8351. array_add(&unhandled, f);
  8352. }
  8353. }
  8354. if (unhandled.count > 0) {
  8355. ERROR_BLOCK();
  8356. if (unhandled.count == 1) {
  8357. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8358. } else {
  8359. error(node, "Unhandled enumerated array cases:");
  8360. for_array(i, unhandled) {
  8361. Entity *f = unhandled[i];
  8362. error_line("\t%.*s\n", LIT(f->token.string));
  8363. }
  8364. }
  8365. if (!build_context.terse_errors) {
  8366. error_line("\n");
  8367. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8368. }
  8369. }
  8370. }
  8371. break;
  8372. }
  8373. case Type_Basic: {
  8374. if (!is_type_any(t)) {
  8375. if (cl->elems.count != 0) {
  8376. gbString s = type_to_string(t);
  8377. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8378. gb_string_free(s);
  8379. is_constant = false;
  8380. }
  8381. break;
  8382. }
  8383. if (cl->elems.count == 0) {
  8384. break; // NOTE(bill): No need to init
  8385. }
  8386. { // Checker values
  8387. Type *field_types[2] = {t_rawptr, t_typeid};
  8388. isize field_count = 2;
  8389. if (cl->elems[0]->kind == Ast_FieldValue) {
  8390. bool fields_visited[2] = {};
  8391. for_array(i, cl->elems) {
  8392. Ast *elem = cl->elems[i];
  8393. if (elem->kind != Ast_FieldValue) {
  8394. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8395. continue;
  8396. }
  8397. ast_node(fv, FieldValue, elem);
  8398. if (fv->field->kind != Ast_Ident) {
  8399. gbString expr_str = expr_to_string(fv->field);
  8400. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8401. gb_string_free(expr_str);
  8402. continue;
  8403. }
  8404. String name = fv->field->Ident.token.string;
  8405. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8406. if (sel.entity == nullptr) {
  8407. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8408. continue;
  8409. }
  8410. isize index = sel.index[0];
  8411. if (fields_visited[index]) {
  8412. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8413. continue;
  8414. }
  8415. fields_visited[index] = true;
  8416. check_expr(c, o, fv->value);
  8417. // NOTE(bill): 'any' literals can never be constant
  8418. is_constant = false;
  8419. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8420. }
  8421. } else {
  8422. for_array(index, cl->elems) {
  8423. Ast *elem = cl->elems[index];
  8424. if (elem->kind == Ast_FieldValue) {
  8425. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8426. continue;
  8427. }
  8428. check_expr(c, o, elem);
  8429. if (index >= field_count) {
  8430. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8431. break;
  8432. }
  8433. // NOTE(bill): 'any' literals can never be constant
  8434. is_constant = false;
  8435. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8436. }
  8437. if (cl->elems.count < field_count) {
  8438. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8439. }
  8440. }
  8441. }
  8442. break;
  8443. }
  8444. case Type_Map: {
  8445. if (cl->elems.count == 0) {
  8446. break;
  8447. }
  8448. is_constant = false;
  8449. { // Checker values
  8450. bool key_is_typeid = is_type_typeid(t->Map.key);
  8451. bool value_is_typeid = is_type_typeid(t->Map.value);
  8452. for (Ast *elem : cl->elems) {
  8453. if (elem->kind != Ast_FieldValue) {
  8454. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8455. continue;
  8456. }
  8457. ast_node(fv, FieldValue, elem);
  8458. if (key_is_typeid) {
  8459. check_expr_or_type(c, o, fv->field, t->Map.key);
  8460. } else {
  8461. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8462. }
  8463. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8464. if (o->mode == Addressing_Invalid) {
  8465. continue;
  8466. }
  8467. if (value_is_typeid) {
  8468. check_expr_or_type(c, o, fv->value, t->Map.value);
  8469. } else {
  8470. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8471. }
  8472. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8473. }
  8474. }
  8475. if (build_context.no_dynamic_literals && cl->elems.count) {
  8476. error(node, "Compound literals of dynamic types have been disabled");
  8477. } else {
  8478. add_map_reserve_dependencies(c);
  8479. add_map_set_dependencies(c);
  8480. }
  8481. break;
  8482. }
  8483. case Type_BitSet: {
  8484. if (cl->elems.count == 0) {
  8485. break; // NOTE(bill): No need to init
  8486. }
  8487. Type *et = base_type(t->BitSet.elem);
  8488. isize field_count = 0;
  8489. if (et->kind == Type_Enum) {
  8490. field_count = et->Enum.fields.count;
  8491. }
  8492. if (cl->elems[0]->kind == Ast_FieldValue) {
  8493. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8494. is_constant = false;
  8495. } else {
  8496. for (Ast *elem : cl->elems) {
  8497. if (elem->kind == Ast_FieldValue) {
  8498. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8499. continue;
  8500. }
  8501. check_expr_with_type_hint(c, o, elem, et);
  8502. if (is_constant) {
  8503. is_constant = o->mode == Addressing_Constant;
  8504. }
  8505. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8506. if (o->mode == Addressing_Constant) {
  8507. i64 lower = t->BitSet.lower;
  8508. i64 upper = t->BitSet.upper;
  8509. i64 v = exact_value_to_i64(o->value);
  8510. if (lower <= v && v <= upper) {
  8511. // okay
  8512. } else {
  8513. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8514. continue;
  8515. }
  8516. }
  8517. }
  8518. }
  8519. break;
  8520. }
  8521. case Type_BitField: {
  8522. if (cl->elems.count == 0) {
  8523. break; // NOTE(bill): No need to init
  8524. }
  8525. is_constant = false;
  8526. if (cl->elems[0]->kind != Ast_FieldValue) {
  8527. gbString type_str = type_to_string(type);
  8528. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8529. gb_string_free(type_str);
  8530. } else {
  8531. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8532. }
  8533. break;
  8534. }
  8535. default: {
  8536. if (cl->elems.count == 0) {
  8537. break; // NOTE(bill): No need to init
  8538. }
  8539. gbString str = type_to_string(type);
  8540. error(node, "Invalid compound literal type '%s'", str);
  8541. gb_string_free(str);
  8542. return kind;
  8543. }
  8544. }
  8545. if (is_constant) {
  8546. o->mode = Addressing_Constant;
  8547. if (is_type_bit_set(type)) {
  8548. // NOTE(bill): Encode as an integer
  8549. Type *bt = base_type(type);
  8550. BigInt bits = {};
  8551. BigInt one = {};
  8552. big_int_from_u64(&one, 1);
  8553. for (Ast *e : cl->elems) {
  8554. GB_ASSERT(e->kind != Ast_FieldValue);
  8555. TypeAndValue tav = e->tav;
  8556. if (tav.mode != Addressing_Constant) {
  8557. continue;
  8558. }
  8559. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8560. i64 v = big_int_to_i64(&tav.value.value_integer);
  8561. i64 lower = bt->BitSet.lower;
  8562. u64 index = cast(u64)(v-lower);
  8563. BigInt bit = {};
  8564. big_int_from_u64(&bit, index);
  8565. big_int_shl(&bit, &one, &bit);
  8566. big_int_or(&bits, &bits, &bit);
  8567. }
  8568. o->value.kind = ExactValue_Integer;
  8569. o->value.value_integer = bits;
  8570. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8571. ExactValue value = exact_value_compound(node);
  8572. Type *bt = core_type(type);
  8573. if (bt->kind == Type_Basic) {
  8574. if (bt->Basic.flags & BasicFlag_Boolean) {
  8575. value = exact_value_bool(false);
  8576. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8577. value = exact_value_i64(0);
  8578. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8579. value = exact_value_i64(0);
  8580. } else if (bt->Basic.flags & BasicFlag_Float) {
  8581. value = exact_value_float(0);
  8582. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8583. value = exact_value_complex(0, 0);
  8584. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8585. value = exact_value_quaternion(0, 0, 0, 0);
  8586. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8587. value = exact_value_pointer(0);
  8588. } else if (bt->Basic.flags & BasicFlag_String) {
  8589. String empty_string = {};
  8590. value = exact_value_string(empty_string);
  8591. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8592. value = exact_value_i64(0);
  8593. }
  8594. }
  8595. o->value = value;
  8596. } else {
  8597. o->value = exact_value_compound(node);
  8598. }
  8599. } else {
  8600. o->mode = Addressing_Value;
  8601. }
  8602. o->type = type;
  8603. return kind;
  8604. }
  8605. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8606. ExprKind kind = Expr_Expr;
  8607. ast_node(ta, TypeAssertion, node);
  8608. check_expr(c, o, ta->expr);
  8609. node->viral_state_flags |= ta->expr->viral_state_flags;
  8610. if (o->mode == Addressing_Invalid) {
  8611. o->expr = node;
  8612. return kind;
  8613. }
  8614. if (o->mode == Addressing_Constant) {
  8615. gbString expr_str = expr_to_string(o->expr);
  8616. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8617. gb_string_free(expr_str);
  8618. o->mode = Addressing_Invalid;
  8619. o->expr = node;
  8620. return kind;
  8621. }
  8622. if (is_type_untyped(o->type)) {
  8623. gbString expr_str = expr_to_string(o->expr);
  8624. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8625. gb_string_free(expr_str);
  8626. o->mode = Addressing_Invalid;
  8627. o->expr = node;
  8628. return kind;
  8629. }
  8630. Type *src = type_deref(o->type);
  8631. Type *bsrc = base_type(src);
  8632. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8633. if (!is_type_union(src)) {
  8634. gbString str = type_to_string(o->type);
  8635. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8636. gb_string_free(str);
  8637. o->mode = Addressing_Invalid;
  8638. o->expr = node;
  8639. return kind;
  8640. }
  8641. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8642. bool allowed = false;
  8643. for (Type *vt : bsrc->Union.variants) {
  8644. if (are_types_identical(vt, type_hint)) {
  8645. allowed = true;
  8646. add_type_info_type(c, vt);
  8647. break;
  8648. }
  8649. }
  8650. if (allowed) {
  8651. add_type_info_type(c, o->type);
  8652. o->type = type_hint;
  8653. o->mode = Addressing_OptionalOk;
  8654. return kind;
  8655. }
  8656. }
  8657. if (bsrc->Union.variants.count != 1) {
  8658. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8659. o->mode = Addressing_Invalid;
  8660. o->expr = node;
  8661. return kind;
  8662. }
  8663. add_type_info_type(c, o->type);
  8664. add_type_info_type(c, bsrc->Union.variants[0]);
  8665. o->type = bsrc->Union.variants[0];
  8666. o->mode = Addressing_OptionalOk;
  8667. } else {
  8668. Type *t = check_type(c, ta->type);
  8669. Type *dst = t;
  8670. if (is_type_union(src)) {
  8671. bool ok = false;
  8672. for (Type *vt : bsrc->Union.variants) {
  8673. if (are_types_identical(vt, dst)) {
  8674. ok = true;
  8675. break;
  8676. }
  8677. }
  8678. if (!ok) {
  8679. gbString expr_str = expr_to_string(o->expr);
  8680. gbString dst_type_str = type_to_string(t);
  8681. defer (gb_string_free(expr_str));
  8682. defer (gb_string_free(dst_type_str));
  8683. if (bsrc->Union.variants.count == 0) {
  8684. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8685. } else {
  8686. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8687. }
  8688. o->mode = Addressing_Invalid;
  8689. o->expr = node;
  8690. return kind;
  8691. }
  8692. add_type_info_type(c, o->type);
  8693. add_type_info_type(c, t);
  8694. o->type = t;
  8695. o->mode = Addressing_OptionalOk;
  8696. } else if (is_type_any(src)) {
  8697. o->type = t;
  8698. o->mode = Addressing_OptionalOk;
  8699. add_type_info_type(c, o->type);
  8700. add_type_info_type(c, t);
  8701. } else {
  8702. gbString str = type_to_string(o->type);
  8703. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8704. gb_string_free(str);
  8705. o->mode = Addressing_Invalid;
  8706. o->expr = node;
  8707. return kind;
  8708. }
  8709. }
  8710. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8711. add_package_dependency(c, "runtime", "type_assertion_check");
  8712. add_package_dependency(c, "runtime", "type_assertion_check2");
  8713. }
  8714. return kind;
  8715. }
  8716. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8717. ast_node(se, SelectorCallExpr, node);
  8718. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8719. // COM APIs is a great example of where this kind of thing is extremely useful
  8720. // General idea:
  8721. //
  8722. // x->y(123) == x.y(x, 123)
  8723. //
  8724. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8725. // Just regenerating a new AST aids things
  8726. //
  8727. // TODO(bill): Is this a good hack or not?
  8728. //
  8729. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8730. if (se->modified_call) {
  8731. // Prevent double evaluation
  8732. o->expr = node;
  8733. o->type = node->tav.type;
  8734. o->value = node->tav.value;
  8735. o->mode = node->tav.mode;
  8736. return Expr_Expr;
  8737. }
  8738. bool allow_arrow_right_selector_expr;
  8739. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8740. c->allow_arrow_right_selector_expr = true;
  8741. Operand x = {};
  8742. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8743. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8744. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8745. o->mode = Addressing_Invalid;
  8746. o->type = t_invalid;
  8747. o->expr = node;
  8748. return kind;
  8749. }
  8750. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8751. gbString type_str = type_to_string(x.type);
  8752. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8753. gb_string_free(type_str);
  8754. o->mode = Addressing_Invalid;
  8755. o->type = t_invalid;
  8756. o->expr = node;
  8757. return Expr_Stmt;
  8758. }
  8759. ast_node(ce, CallExpr, se->call);
  8760. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8761. Ast *first_arg = x.expr->SelectorExpr.expr;
  8762. GB_ASSERT(first_arg != nullptr);
  8763. Entity *e = entity_of_node(se->expr);
  8764. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8765. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8766. }
  8767. if (e->kind != Entity_ProcGroup) {
  8768. Type *pt = base_type(x.type);
  8769. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8770. Type *first_type = nullptr;
  8771. String first_arg_name = {};
  8772. if (pt->Proc.param_count > 0) {
  8773. Entity *f = pt->Proc.params->Tuple.variables[0];
  8774. first_type = f->type;
  8775. first_arg_name = f->token.string;
  8776. }
  8777. if (first_arg_name.len == 0) {
  8778. first_arg_name = str_lit("_");
  8779. }
  8780. if (first_type == nullptr) {
  8781. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8782. o->mode = Addressing_Invalid;
  8783. o->type = t_invalid;
  8784. o->expr = node;
  8785. return Expr_Stmt;
  8786. }
  8787. Operand y = {};
  8788. y.mode = first_arg->tav.mode;
  8789. y.type = first_arg->tav.type;
  8790. y.value = first_arg->tav.value;
  8791. if (check_is_assignable_to(c, &y, first_type)) {
  8792. // Do nothing, it's valid
  8793. } else {
  8794. Operand z = y;
  8795. z.type = type_deref(y.type);
  8796. if (check_is_assignable_to(c, &z, first_type)) {
  8797. // NOTE(bill): AST GENERATION HACK!
  8798. Token op = {Token_Pointer};
  8799. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8800. } else if (y.mode == Addressing_Variable) {
  8801. Operand w = y;
  8802. w.type = alloc_type_pointer(y.type);
  8803. if (check_is_assignable_to(c, &w, first_type)) {
  8804. // NOTE(bill): AST GENERATION HACK!
  8805. Token op = {Token_And};
  8806. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8807. }
  8808. }
  8809. }
  8810. if (ce->args.count > 0) {
  8811. bool fail = false;
  8812. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8813. for (Ast *arg : ce->args) {
  8814. bool mix = false;
  8815. if (first_is_field_value) {
  8816. mix = arg->kind != Ast_FieldValue;
  8817. } else {
  8818. mix = arg->kind == Ast_FieldValue;
  8819. }
  8820. if (mix) {
  8821. fail = true;
  8822. break;
  8823. }
  8824. }
  8825. if (!fail && first_is_field_value) {
  8826. Token op = {Token_Eq};
  8827. AstFile *f = first_arg->file();
  8828. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8829. }
  8830. }
  8831. }
  8832. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8833. modified_args[0] = first_arg;
  8834. slice_copy(&modified_args, ce->args, 1);
  8835. ce->args = modified_args;
  8836. se->modified_call = true;
  8837. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8838. c->allow_arrow_right_selector_expr = true;
  8839. check_expr_base(c, o, se->call, type_hint);
  8840. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8841. o->expr = node;
  8842. return Expr_Expr;
  8843. }
  8844. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8845. ExprKind kind = Expr_Expr;
  8846. ast_node(ie, IndexExpr, node);
  8847. check_expr(c, o, ie->expr);
  8848. node->viral_state_flags |= ie->expr->viral_state_flags;
  8849. if (o->mode == Addressing_Invalid) {
  8850. o->expr = node;
  8851. return kind;
  8852. }
  8853. Type *t = base_type(type_deref(o->type));
  8854. bool is_ptr = is_type_pointer(o->type);
  8855. bool is_const = o->mode == Addressing_Constant;
  8856. if (is_type_map(t)) {
  8857. Operand key = {};
  8858. if (is_type_typeid(t->Map.key)) {
  8859. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8860. } else {
  8861. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8862. }
  8863. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8864. if (key.mode == Addressing_Invalid) {
  8865. o->mode = Addressing_Invalid;
  8866. o->expr = node;
  8867. return kind;
  8868. }
  8869. o->mode = Addressing_MapIndex;
  8870. o->type = t->Map.value;
  8871. o->expr = node;
  8872. add_map_get_dependencies(c);
  8873. add_map_set_dependencies(c);
  8874. return Expr_Expr;
  8875. }
  8876. i64 max_count = -1;
  8877. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8878. if (is_const) {
  8879. if (is_type_array(t)) {
  8880. // Okay
  8881. } else if (is_type_slice(t)) {
  8882. // Okay
  8883. } else if (is_type_enumerated_array(t)) {
  8884. // Okay
  8885. } else if (is_type_string(t)) {
  8886. // Okay
  8887. } else if (is_type_relative_multi_pointer(t)) {
  8888. // Okay
  8889. } else if (is_type_matrix(t)) {
  8890. // Okay
  8891. } else {
  8892. valid = false;
  8893. }
  8894. }
  8895. if (!valid) {
  8896. gbString str = expr_to_string(o->expr);
  8897. gbString type_str = type_to_string(o->type);
  8898. defer (gb_string_free(str));
  8899. defer (gb_string_free(type_str));
  8900. if (is_const) {
  8901. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8902. } else {
  8903. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8904. }
  8905. o->mode = Addressing_Invalid;
  8906. o->expr = node;
  8907. return kind;
  8908. }
  8909. if (ie->index == nullptr) {
  8910. gbString str = expr_to_string(o->expr);
  8911. error(o->expr, "Missing index for '%s'", str);
  8912. gb_string_free(str);
  8913. o->mode = Addressing_Invalid;
  8914. o->expr = node;
  8915. return kind;
  8916. }
  8917. Type *index_type_hint = nullptr;
  8918. if (is_type_enumerated_array(t)) {
  8919. Type *bt = base_type(t);
  8920. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8921. index_type_hint = bt->EnumeratedArray.index;
  8922. }
  8923. i64 index = 0;
  8924. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8925. if (is_const) {
  8926. if (index < 0) {
  8927. ERROR_BLOCK();
  8928. gbString str = expr_to_string(o->expr);
  8929. error(o->expr, "Cannot index a constant '%s'", str);
  8930. if (!build_context.terse_errors) {
  8931. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8932. }
  8933. gb_string_free(str);
  8934. o->mode = Addressing_Invalid;
  8935. o->expr = node;
  8936. return kind;
  8937. } else if (ok && !is_type_matrix(t)) {
  8938. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8939. o->mode = Addressing_Constant;
  8940. bool success = false;
  8941. bool finish = false;
  8942. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8943. if (!success) {
  8944. ERROR_BLOCK();
  8945. gbString str = expr_to_string(o->expr);
  8946. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8947. if (!build_context.terse_errors) {
  8948. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8949. }
  8950. gb_string_free(str);
  8951. o->mode = Addressing_Invalid;
  8952. o->expr = node;
  8953. return kind;
  8954. }
  8955. }
  8956. }
  8957. if (type_hint != nullptr && is_type_matrix(t)) {
  8958. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8959. // if a type hint exists
  8960. }
  8961. return kind;
  8962. }
  8963. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8964. ExprKind kind = Expr_Stmt;
  8965. ast_node(se, SliceExpr, node);
  8966. check_expr(c, o, se->expr);
  8967. node->viral_state_flags |= se->expr->viral_state_flags;
  8968. if (o->mode == Addressing_Invalid) {
  8969. o->mode = Addressing_Invalid;
  8970. o->expr = node;
  8971. return kind;
  8972. }
  8973. bool valid = false;
  8974. i64 max_count = -1;
  8975. Type *t = base_type(type_deref(o->type));
  8976. switch (t->kind) {
  8977. case Type_Basic:
  8978. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8979. valid = true;
  8980. if (o->mode == Addressing_Constant) {
  8981. max_count = o->value.value_string.len;
  8982. }
  8983. o->type = type_deref(o->type);
  8984. }
  8985. break;
  8986. case Type_Array:
  8987. valid = true;
  8988. max_count = t->Array.count;
  8989. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8990. gbString str = expr_to_string(node);
  8991. error(node, "Cannot slice array '%s', value is not addressable", str);
  8992. gb_string_free(str);
  8993. o->mode = Addressing_Invalid;
  8994. o->expr = node;
  8995. return kind;
  8996. }
  8997. o->type = alloc_type_slice(t->Array.elem);
  8998. break;
  8999. case Type_MultiPointer:
  9000. valid = true;
  9001. o->type = type_deref(o->type);
  9002. break;
  9003. case Type_Slice:
  9004. valid = true;
  9005. o->type = type_deref(o->type);
  9006. break;
  9007. case Type_DynamicArray:
  9008. valid = true;
  9009. o->type = alloc_type_slice(t->DynamicArray.elem);
  9010. break;
  9011. case Type_Struct:
  9012. if (is_type_soa_struct(t)) {
  9013. valid = true;
  9014. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9015. max_count = t->Struct.soa_count;
  9016. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9017. gbString str = expr_to_string(node);
  9018. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9019. gb_string_free(str);
  9020. o->mode = Addressing_Invalid;
  9021. o->expr = node;
  9022. return kind;
  9023. }
  9024. }
  9025. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9026. }
  9027. break;
  9028. case Type_RelativeMultiPointer:
  9029. valid = true;
  9030. o->type = type_deref(o->type);
  9031. break;
  9032. case Type_EnumeratedArray:
  9033. {
  9034. gbString str = expr_to_string(o->expr);
  9035. gbString type_str = type_to_string(o->type);
  9036. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9037. gb_string_free(type_str);
  9038. gb_string_free(str);
  9039. o->mode = Addressing_Invalid;
  9040. o->expr = node;
  9041. return kind;
  9042. }
  9043. break;
  9044. }
  9045. if (!valid) {
  9046. gbString str = expr_to_string(o->expr);
  9047. gbString type_str = type_to_string(o->type);
  9048. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9049. gb_string_free(type_str);
  9050. gb_string_free(str);
  9051. o->mode = Addressing_Invalid;
  9052. o->expr = node;
  9053. return kind;
  9054. }
  9055. if (se->low == nullptr && se->high != nullptr) {
  9056. // It is okay to continue as it will assume the 1st index is zero
  9057. }
  9058. i64 indices[2] = {};
  9059. Ast *nodes[2] = {se->low, se->high};
  9060. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9061. i64 index = max_count;
  9062. if (nodes[i] != nullptr) {
  9063. i64 capacity = -1;
  9064. if (max_count >= 0) {
  9065. capacity = max_count;
  9066. }
  9067. i64 j = 0;
  9068. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9069. index = j;
  9070. }
  9071. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9072. } else if (i == 0) {
  9073. index = 0;
  9074. }
  9075. indices[i] = index;
  9076. }
  9077. for (isize i = 0; i < gb_count_of(indices); i++) {
  9078. i64 a = indices[i];
  9079. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9080. i64 b = indices[j];
  9081. if (a > b && b >= 0) {
  9082. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9083. }
  9084. }
  9085. }
  9086. if (max_count < 0) {
  9087. if (o->mode == Addressing_Constant) {
  9088. gbString s = expr_to_string(se->expr);
  9089. error(se->expr, "Cannot slice constant value '%s'", s);
  9090. gb_string_free(s);
  9091. }
  9092. }
  9093. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9094. /*
  9095. x[:] -> [^]T
  9096. x[i:] -> [^]T
  9097. x[:n] -> []T
  9098. x[i:n] -> []T
  9099. */
  9100. o->type = alloc_type_slice(t->MultiPointer.elem);
  9101. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  9102. /*
  9103. x[:] -> [^]T
  9104. x[i:] -> [^]T
  9105. x[:n] -> []T
  9106. x[i:n] -> []T
  9107. */
  9108. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  9109. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  9110. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  9111. }
  9112. o->mode = Addressing_Value;
  9113. if (is_type_string(t) && max_count >= 0) {
  9114. bool all_constant = true;
  9115. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9116. if (nodes[i] != nullptr) {
  9117. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9118. if (tav.mode != Addressing_Constant) {
  9119. all_constant = false;
  9120. break;
  9121. }
  9122. }
  9123. }
  9124. if (!all_constant) {
  9125. ERROR_BLOCK();
  9126. gbString str = expr_to_string(o->expr);
  9127. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9128. if (!build_context.terse_errors) {
  9129. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9130. }
  9131. gb_string_free(str);
  9132. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9133. o->expr = node;
  9134. return kind;
  9135. }
  9136. String s = {};
  9137. if (o->value.kind == ExactValue_String) {
  9138. s = o->value.value_string;
  9139. }
  9140. o->mode = Addressing_Constant;
  9141. o->type = t;
  9142. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9143. }
  9144. return kind;
  9145. }
  9146. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9147. u32 prev_state_flags = c->state_flags;
  9148. defer (c->state_flags = prev_state_flags);
  9149. if (node->state_flags != 0) {
  9150. u32 in = node->state_flags;
  9151. u32 out = c->state_flags;
  9152. if (in & StateFlag_no_bounds_check) {
  9153. out |= StateFlag_no_bounds_check;
  9154. out &= ~StateFlag_bounds_check;
  9155. } else if (in & StateFlag_bounds_check) {
  9156. out |= StateFlag_bounds_check;
  9157. out &= ~StateFlag_no_bounds_check;
  9158. }
  9159. if (in & StateFlag_no_type_assert) {
  9160. out |= StateFlag_no_type_assert;
  9161. out &= ~StateFlag_type_assert;
  9162. } else if (in & StateFlag_type_assert) {
  9163. out |= StateFlag_type_assert;
  9164. out &= ~StateFlag_no_type_assert;
  9165. }
  9166. c->state_flags = out;
  9167. }
  9168. ExprKind kind = Expr_Stmt;
  9169. o->mode = Addressing_Invalid;
  9170. o->type = t_invalid;
  9171. o->value = {ExactValue_Invalid};
  9172. switch (node->kind) {
  9173. default:
  9174. return kind;
  9175. case_ast_node(be, BadExpr, node)
  9176. return kind;
  9177. case_end;
  9178. case_ast_node(i, Implicit, node)
  9179. switch (i->kind) {
  9180. case Token_context:
  9181. {
  9182. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9183. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  9184. return kind;
  9185. }
  9186. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9187. c->scope->flags |= ScopeFlag_ContextDefined;
  9188. }
  9189. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9190. error(node, "'context' has not been defined within this scope");
  9191. // Continue with value
  9192. }
  9193. init_core_context(c->checker);
  9194. o->mode = Addressing_Context;
  9195. o->type = t_context;
  9196. }
  9197. break;
  9198. default:
  9199. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9200. return kind;
  9201. }
  9202. case_end;
  9203. case_ast_node(i, Ident, node);
  9204. check_ident(c, o, node, nullptr, type_hint, false);
  9205. case_end;
  9206. case_ast_node(u, Uninit, node);
  9207. o->mode = Addressing_Value;
  9208. o->type = t_untyped_uninit;
  9209. error(node, "Use of --- outside of variable declaration");
  9210. case_end;
  9211. case_ast_node(bl, BasicLit, node);
  9212. Type *t = t_invalid;
  9213. switch (node->tav.value.kind) {
  9214. case ExactValue_String: t = t_untyped_string; break;
  9215. case ExactValue_Float: t = t_untyped_float; break;
  9216. case ExactValue_Complex: t = t_untyped_complex; break;
  9217. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9218. case ExactValue_Integer:
  9219. t = t_untyped_integer;
  9220. if (bl->token.kind == Token_Rune) {
  9221. t = t_untyped_rune;
  9222. }
  9223. break;
  9224. default:
  9225. GB_PANIC("Unhandled value type for basic literal");
  9226. break;
  9227. }
  9228. o->mode = Addressing_Constant;
  9229. o->type = t;
  9230. o->value = node->tav.value;
  9231. case_end;
  9232. case_ast_node(bd, BasicDirective, node);
  9233. kind = check_basic_directive_expr(c, o, node, type_hint);
  9234. case_end;
  9235. case_ast_node(pg, ProcGroup, node);
  9236. error(node, "Illegal use of a procedure group");
  9237. o->mode = Addressing_Invalid;
  9238. case_end;
  9239. case_ast_node(pl, ProcLit, node);
  9240. CheckerContext ctx = *c;
  9241. DeclInfo *decl = nullptr;
  9242. Type *type = alloc_type(Type_Proc);
  9243. check_open_scope(&ctx, pl->type);
  9244. {
  9245. decl = make_decl_info(ctx.scope, ctx.decl);
  9246. decl->proc_lit = node;
  9247. ctx.decl = decl;
  9248. defer (ctx.decl = ctx.decl->parent);
  9249. if (pl->tags != 0) {
  9250. error(node, "A procedure literal cannot have tags");
  9251. pl->tags = 0; // TODO(bill): Should I zero this?!
  9252. }
  9253. check_procedure_type(&ctx, type, pl->type);
  9254. if (!is_type_proc(type)) {
  9255. gbString str = expr_to_string(node);
  9256. error(node, "Invalid procedure literal '%s'", str);
  9257. gb_string_free(str);
  9258. check_close_scope(&ctx);
  9259. return kind;
  9260. }
  9261. if (pl->body == nullptr) {
  9262. error(node, "A procedure literal must have a body");
  9263. return kind;
  9264. }
  9265. pl->decl = decl;
  9266. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9267. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9268. array_add(&ctx.checker->nested_proc_lits, decl);
  9269. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9270. }
  9271. check_close_scope(&ctx);
  9272. o->mode = Addressing_Value;
  9273. o->type = type;
  9274. case_end;
  9275. case_ast_node(te, TernaryIfExpr, node);
  9276. kind = check_ternary_if_expr(c, o, node, type_hint);
  9277. case_end;
  9278. case_ast_node(te, TernaryWhenExpr, node);
  9279. kind = check_ternary_when_expr(c, o, node, type_hint);
  9280. case_end;
  9281. case_ast_node(oe, OrElseExpr, node);
  9282. return check_or_else_expr(c, o, node, type_hint);
  9283. case_end;
  9284. case_ast_node(re, OrReturnExpr, node);
  9285. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9286. return check_or_return_expr(c, o, node, type_hint);
  9287. case_end;
  9288. case_ast_node(re, OrBranchExpr, node);
  9289. return check_or_branch_expr(c, o, node, type_hint);
  9290. case_end;
  9291. case_ast_node(cl, CompoundLit, node);
  9292. kind = check_compound_literal(c, o, node, type_hint);
  9293. case_end;
  9294. case_ast_node(pe, ParenExpr, node);
  9295. kind = check_expr_base(c, o, pe->expr, type_hint);
  9296. node->viral_state_flags |= pe->expr->viral_state_flags;
  9297. o->expr = node;
  9298. case_end;
  9299. case_ast_node(te, TagExpr, node);
  9300. String name = te->name.string;
  9301. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9302. if (te->expr) {
  9303. kind = check_expr_base(c, o, te->expr, type_hint);
  9304. node->viral_state_flags |= te->expr->viral_state_flags;
  9305. }
  9306. o->expr = node;
  9307. case_end;
  9308. case_ast_node(ta, TypeAssertion, node);
  9309. kind = check_type_assertion(c, o, node, type_hint);
  9310. case_end;
  9311. case_ast_node(tc, TypeCast, node);
  9312. check_expr_or_type(c, o, tc->type);
  9313. if (o->mode != Addressing_Type) {
  9314. gbString str = expr_to_string(tc->type);
  9315. error(tc->type, "Expected a type, got %s", str);
  9316. gb_string_free(str);
  9317. o->mode = Addressing_Invalid;
  9318. }
  9319. if (o->mode == Addressing_Invalid) {
  9320. o->expr = node;
  9321. return kind;
  9322. }
  9323. Type *type = o->type;
  9324. check_expr_base(c, o, tc->expr, type);
  9325. node->viral_state_flags |= tc->expr->viral_state_flags;
  9326. if (o->mode != Addressing_Invalid) {
  9327. switch (tc->token.kind) {
  9328. case Token_transmute:
  9329. check_transmute(c, node, o, type);
  9330. break;
  9331. case Token_cast:
  9332. check_cast(c, o, type);
  9333. break;
  9334. default:
  9335. error(node, "Invalid AST: Invalid casting expression");
  9336. o->mode = Addressing_Invalid;
  9337. break;
  9338. }
  9339. }
  9340. return Expr_Expr;
  9341. case_end;
  9342. case_ast_node(ac, AutoCast, node);
  9343. check_expr_base(c, o, ac->expr, type_hint);
  9344. node->viral_state_flags |= ac->expr->viral_state_flags;
  9345. if (o->mode == Addressing_Invalid) {
  9346. o->expr = node;
  9347. return kind;
  9348. }
  9349. if (type_hint) {
  9350. check_cast(c, o, type_hint);
  9351. }
  9352. o->expr = node;
  9353. return Expr_Expr;
  9354. case_end;
  9355. case_ast_node(ue, UnaryExpr, node);
  9356. Type *th = type_hint;
  9357. if (ue->op.kind == Token_And) {
  9358. th = type_deref(th);
  9359. }
  9360. check_expr_base(c, o, ue->expr, th);
  9361. node->viral_state_flags |= ue->expr->viral_state_flags;
  9362. if (o->mode != Addressing_Invalid) {
  9363. check_unary_expr(c, o, ue->op, node);
  9364. }
  9365. o->expr = node;
  9366. return Expr_Expr;
  9367. case_end;
  9368. case_ast_node(be, BinaryExpr, node);
  9369. check_binary_expr(c, o, node, type_hint, true);
  9370. if (o->mode == Addressing_Invalid) {
  9371. o->expr = node;
  9372. return kind;
  9373. }
  9374. case_end;
  9375. case_ast_node(se, SelectorExpr, node);
  9376. check_selector(c, o, node, type_hint);
  9377. node->viral_state_flags |= se->expr->viral_state_flags;
  9378. case_end;
  9379. case_ast_node(se, SelectorCallExpr, node);
  9380. return check_selector_call_expr(c, o, node, type_hint);
  9381. case_end;
  9382. case_ast_node(ise, ImplicitSelectorExpr, node);
  9383. return check_implicit_selector_expr(c, o, node, type_hint);
  9384. case_end;
  9385. case_ast_node(ie, IndexExpr, node);
  9386. kind = check_index_expr(c, o, node, type_hint);
  9387. case_end;
  9388. case_ast_node(se, SliceExpr, node);
  9389. kind = check_slice_expr(c, o, node, type_hint);
  9390. case_end;
  9391. case_ast_node(mie, MatrixIndexExpr, node);
  9392. check_matrix_index_expr(c, o, node, type_hint);
  9393. o->expr = node;
  9394. return Expr_Expr;
  9395. case_end;
  9396. case_ast_node(ce, CallExpr, node);
  9397. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9398. case_end;
  9399. case_ast_node(de, DerefExpr, node);
  9400. check_expr_or_type(c, o, de->expr);
  9401. node->viral_state_flags |= de->expr->viral_state_flags;
  9402. if (o->mode == Addressing_Invalid) {
  9403. o->mode = Addressing_Invalid;
  9404. o->expr = node;
  9405. return kind;
  9406. } else {
  9407. Type *t = base_type(o->type);
  9408. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9409. o->mode = Addressing_Variable;
  9410. o->type = t->Pointer.elem;
  9411. } else if (t->kind == Type_SoaPointer) {
  9412. o->mode = Addressing_SoaVariable;
  9413. o->type = type_deref(t);
  9414. } else if (t->kind == Type_RelativePointer) {
  9415. if (o->mode != Addressing_Variable) {
  9416. gbString str = expr_to_string(o->expr);
  9417. gbString typ = type_to_string(o->type);
  9418. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9419. gb_string_free(typ);
  9420. gb_string_free(str);
  9421. }
  9422. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9423. add_type_info_type(c, o->type);
  9424. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9425. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9426. o->mode = Addressing_Variable;
  9427. o->type = ptr_type->Pointer.elem;
  9428. } else {
  9429. gbString str = expr_to_string(o->expr);
  9430. gbString typ = type_to_string(o->type);
  9431. ERROR_BLOCK();
  9432. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9433. if (o->type && is_type_multi_pointer(o->type)) {
  9434. if (!build_context.terse_errors) {
  9435. error_line("\tDid you mean '%s[0]'?\n", str);
  9436. }
  9437. }
  9438. gb_string_free(typ);
  9439. gb_string_free(str);
  9440. o->mode = Addressing_Invalid;
  9441. o->expr = node;
  9442. return kind;
  9443. }
  9444. }
  9445. case_end;
  9446. case_ast_node(ia, InlineAsmExpr, node);
  9447. if (c->curr_proc_decl == nullptr) {
  9448. error(node, "Inline asm expressions are only allowed within a procedure body");
  9449. }
  9450. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9451. Type *return_type = nullptr;
  9452. for_array(i, ia->param_types) {
  9453. param_types[i] = check_type(c, ia->param_types[i]);
  9454. }
  9455. if (ia->return_type != nullptr) {
  9456. return_type = check_type(c, ia->return_type);
  9457. }
  9458. Operand x = {};
  9459. check_expr(c, &x, ia->asm_string);
  9460. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9461. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9462. }
  9463. check_expr(c, &x, ia->constraints_string);
  9464. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9465. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9466. }
  9467. Scope *scope = create_scope(c->info, c->scope);
  9468. scope->flags |= ScopeFlag_Proc;
  9469. Type *params = alloc_type_tuple();
  9470. Type *results = alloc_type_tuple();
  9471. if (param_types.count != 0) {
  9472. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9473. for_array(i, param_types) {
  9474. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9475. }
  9476. }
  9477. if (return_type != nullptr) {
  9478. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9479. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9480. }
  9481. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9482. o->type = pt;
  9483. o->mode = Addressing_Value;
  9484. o->expr = node;
  9485. return Expr_Expr;
  9486. case_end;
  9487. case Ast_DistinctType:
  9488. case Ast_TypeidType:
  9489. case Ast_PolyType:
  9490. case Ast_ProcType:
  9491. case Ast_PointerType:
  9492. case Ast_MultiPointerType:
  9493. case Ast_ArrayType:
  9494. case Ast_DynamicArrayType:
  9495. case Ast_StructType:
  9496. case Ast_UnionType:
  9497. case Ast_EnumType:
  9498. case Ast_MapType:
  9499. case Ast_BitSetType:
  9500. case Ast_MatrixType:
  9501. case Ast_RelativeType:
  9502. o->mode = Addressing_Type;
  9503. o->type = check_type(c, node);
  9504. break;
  9505. }
  9506. kind = Expr_Expr;
  9507. o->expr = node;
  9508. return kind;
  9509. }
  9510. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9511. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9512. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9513. o->type = t_invalid;
  9514. gbString xs = expr_to_string(o->expr);
  9515. if (o->mode == Addressing_Type) {
  9516. error(o->expr, "Invalid type usage '%s'", xs);
  9517. } else {
  9518. error(o->expr, "Invalid expression '%s'", xs);
  9519. }
  9520. gb_string_free(xs);
  9521. }
  9522. if (o->type != nullptr && is_type_untyped(o->type)) {
  9523. add_untyped(c, node, o->mode, o->type, o->value);
  9524. }
  9525. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9526. add_type_and_value(c, node, o->mode, o->type, o->value);
  9527. return kind;
  9528. }
  9529. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9530. check_expr_base(c, o, e, nullptr);
  9531. switch (o->mode) {
  9532. default:
  9533. return; // NOTE(bill): Valid
  9534. case Addressing_NoValue:
  9535. error_operand_no_value(o);
  9536. break;
  9537. }
  9538. o->mode = Addressing_Invalid;
  9539. }
  9540. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9541. check_expr_base(c, o, e, nullptr);
  9542. switch (o->mode) {
  9543. default:
  9544. return; // NOTE(bill): Valid
  9545. case Addressing_NoValue:
  9546. error_operand_no_value(o);
  9547. break;
  9548. case Addressing_Type:
  9549. error_operand_not_expression(o);
  9550. break;
  9551. }
  9552. o->mode = Addressing_Invalid;
  9553. }
  9554. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9555. check_expr_base(c, o, e, type_hint);
  9556. switch (o->mode) {
  9557. default:
  9558. return; // NOTE(bill): Valid
  9559. case Addressing_NoValue:
  9560. error_operand_no_value(o);
  9561. break;
  9562. case Addressing_Type:
  9563. error_operand_not_expression(o);
  9564. break;
  9565. }
  9566. o->mode = Addressing_Invalid;
  9567. }
  9568. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9569. if (o->mode == Addressing_Value) {
  9570. // NOTE(bill): Tuples are not first class thus never named
  9571. if (o->type->kind == Type_Tuple) {
  9572. isize count = o->type->Tuple.variables.count;
  9573. error(o->expr,
  9574. "%td-valued expression found where single value expected", count);
  9575. o->mode = Addressing_Invalid;
  9576. GB_ASSERT(count != 1);
  9577. }
  9578. }
  9579. }
  9580. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9581. check_multi_expr(c, o, e);
  9582. check_not_tuple(c, o);
  9583. }
  9584. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9585. check_expr_base(c, o, e, type_hint);
  9586. check_not_tuple(c, o);
  9587. error_operand_no_value(o);
  9588. }
  9589. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9590. switch (v.kind) {
  9591. case ExactValue_Invalid:
  9592. return true;
  9593. case ExactValue_Bool:
  9594. return !v.value_bool;
  9595. case ExactValue_String:
  9596. return v.value_string.len == 0;
  9597. case ExactValue_Integer:
  9598. return big_int_is_zero(&v.value_integer);
  9599. case ExactValue_Float:
  9600. return v.value_float == 0.0;
  9601. case ExactValue_Complex:
  9602. if (v.value_complex) {
  9603. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9604. }
  9605. return true;
  9606. case ExactValue_Quaternion:
  9607. if (v.value_quaternion) {
  9608. return v.value_quaternion->real == 0.0 &&
  9609. v.value_quaternion->imag == 0.0 &&
  9610. v.value_quaternion->jmag == 0.0 &&
  9611. v.value_quaternion->kmag == 0.0;
  9612. }
  9613. return true;
  9614. case ExactValue_Pointer:
  9615. return v.value_pointer == 0;
  9616. case ExactValue_Compound:
  9617. if (v.value_compound == nullptr) {
  9618. return true;
  9619. } else {
  9620. ast_node(cl, CompoundLit, v.value_compound);
  9621. if (cl->elems.count == 0) {
  9622. return true;
  9623. } else {
  9624. for (Ast *elem : cl->elems) {
  9625. if (elem->tav.mode != Addressing_Constant) {
  9626. return false;
  9627. }
  9628. if (!is_exact_value_zero(elem->tav.value)) {
  9629. return false;
  9630. }
  9631. }
  9632. return true;
  9633. }
  9634. }
  9635. case ExactValue_Procedure:
  9636. return v.value_procedure == nullptr;
  9637. case ExactValue_Typeid:
  9638. return v.value_typeid == nullptr;
  9639. }
  9640. return true;
  9641. }
  9642. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9643. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9644. for_array(i, params) {
  9645. if (i > 0) {
  9646. str = gb_string_appendc(str, ", ");
  9647. }
  9648. str = write_expr_to_string(str, params[i], false);
  9649. }
  9650. return str;
  9651. }
  9652. gb_internal gbString string_append_string(gbString str, String string) {
  9653. if (string.len > 0) {
  9654. return gb_string_append_length(str, &string[0], string.len);
  9655. }
  9656. return str;
  9657. }
  9658. gb_internal gbString string_append_token(gbString str, Token token) {
  9659. str = string_append_string(str, token.string);
  9660. return str;
  9661. }
  9662. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9663. if (node == nullptr)
  9664. return str;
  9665. if (is_ast_stmt(node)) {
  9666. GB_ASSERT("stmt passed to write_expr_to_string");
  9667. }
  9668. switch (node->kind) {
  9669. default:
  9670. str = gb_string_appendc(str, "(BadExpr)");
  9671. break;
  9672. case_ast_node(i, Ident, node);
  9673. str = string_append_token(str, i->token);
  9674. case_end;
  9675. case_ast_node(i, Implicit, node);
  9676. str = string_append_token(str, *i);
  9677. case_end;
  9678. case_ast_node(bl, BasicLit, node);
  9679. str = string_append_token(str, bl->token);
  9680. case_end;
  9681. case_ast_node(bd, BasicDirective, node);
  9682. str = gb_string_append_rune(str, '#');
  9683. str = string_append_string(str, bd->name.string);
  9684. case_end;
  9685. case_ast_node(ud, Uninit, node);
  9686. str = gb_string_appendc(str, "---");
  9687. case_end;
  9688. case_ast_node(pg, ProcGroup, node);
  9689. str = gb_string_appendc(str, "proc{");
  9690. for_array(i, pg->args) {
  9691. if (i > 0) str = gb_string_appendc(str, ", ");
  9692. str = write_expr_to_string(str, pg->args[i], shorthand);
  9693. }
  9694. str = gb_string_append_rune(str, '}');
  9695. case_end;
  9696. case_ast_node(pl, ProcLit, node);
  9697. str = write_expr_to_string(str, pl->type, shorthand);
  9698. if (pl->body) {
  9699. str = gb_string_appendc(str, " {...}");
  9700. } else {
  9701. str = gb_string_appendc(str, " ---");
  9702. }
  9703. case_end;
  9704. case_ast_node(cl, CompoundLit, node);
  9705. str = write_expr_to_string(str, cl->type, shorthand);
  9706. str = gb_string_append_rune(str, '{');
  9707. if (shorthand) {
  9708. str = gb_string_appendc(str, "...");
  9709. } else {
  9710. for_array(i, cl->elems) {
  9711. if (i > 0) str = gb_string_appendc(str, ", ");
  9712. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9713. }
  9714. }
  9715. str = gb_string_append_rune(str, '}');
  9716. case_end;
  9717. case_ast_node(te, TagExpr, node);
  9718. str = gb_string_append_rune(str, '#');
  9719. str = string_append_token(str, te->name);
  9720. str = write_expr_to_string(str, te->expr, shorthand);
  9721. case_end;
  9722. case_ast_node(ue, UnaryExpr, node);
  9723. str = string_append_token(str, ue->op);
  9724. str = write_expr_to_string(str, ue->expr, shorthand);
  9725. case_end;
  9726. case_ast_node(de, DerefExpr, node);
  9727. str = write_expr_to_string(str, de->expr, shorthand);
  9728. str = gb_string_append_rune(str, '^');
  9729. case_end;
  9730. case_ast_node(be, BinaryExpr, node);
  9731. str = write_expr_to_string(str, be->left, shorthand);
  9732. str = gb_string_append_rune(str, ' ');
  9733. str = string_append_token(str, be->op);
  9734. str = gb_string_append_rune(str, ' ');
  9735. str = write_expr_to_string(str, be->right, shorthand);
  9736. case_end;
  9737. case_ast_node(te, TernaryIfExpr, node);
  9738. TokenPos x = ast_token(te->x).pos;
  9739. TokenPos cond = ast_token(te->cond).pos;
  9740. if (x < cond) {
  9741. str = write_expr_to_string(str, te->x, shorthand);
  9742. str = gb_string_appendc(str, " if ");
  9743. str = write_expr_to_string(str, te->cond, shorthand);
  9744. str = gb_string_appendc(str, " else ");
  9745. str = write_expr_to_string(str, te->y, shorthand);
  9746. } else {
  9747. str = write_expr_to_string(str, te->cond, shorthand);
  9748. str = gb_string_appendc(str, " ? ");
  9749. str = write_expr_to_string(str, te->x, shorthand);
  9750. str = gb_string_appendc(str, " : ");
  9751. str = write_expr_to_string(str, te->y, shorthand);
  9752. }
  9753. case_end;
  9754. case_ast_node(te, TernaryWhenExpr, node);
  9755. str = write_expr_to_string(str, te->x, shorthand);
  9756. str = gb_string_appendc(str, " when ");
  9757. str = write_expr_to_string(str, te->cond, shorthand);
  9758. str = gb_string_appendc(str, " else ");
  9759. str = write_expr_to_string(str, te->y, shorthand);
  9760. case_end;
  9761. case_ast_node(oe, OrElseExpr, node);
  9762. str = write_expr_to_string(str, oe->x, shorthand);
  9763. str = gb_string_appendc(str, " or_else ");
  9764. str = write_expr_to_string(str, oe->y, shorthand);
  9765. case_end;
  9766. case_ast_node(oe, OrReturnExpr, node);
  9767. str = write_expr_to_string(str, oe->expr, shorthand);
  9768. str = gb_string_appendc(str, " or_return");
  9769. case_end;
  9770. case_ast_node(oe, OrBranchExpr, node);
  9771. str = write_expr_to_string(str, oe->expr, shorthand);
  9772. str = gb_string_append_rune(str, ' ');
  9773. str = string_append_token(str, oe->token);
  9774. if (oe->label) {
  9775. str = gb_string_append_rune(str, ' ');
  9776. str = write_expr_to_string(str, oe->label, shorthand);
  9777. }
  9778. case_end;
  9779. case_ast_node(pe, ParenExpr, node);
  9780. str = gb_string_append_rune(str, '(');
  9781. str = write_expr_to_string(str, pe->expr, shorthand);
  9782. str = gb_string_append_rune(str, ')');
  9783. case_end;
  9784. case_ast_node(se, SelectorExpr, node);
  9785. str = write_expr_to_string(str, se->expr, shorthand);
  9786. str = string_append_token(str, se->token);
  9787. str = write_expr_to_string(str, se->selector, shorthand);
  9788. case_end;
  9789. case_ast_node(se, ImplicitSelectorExpr, node);
  9790. str = gb_string_append_rune(str, '.');
  9791. str = write_expr_to_string(str, se->selector, shorthand);
  9792. case_end;
  9793. case_ast_node(se, SelectorCallExpr, node);
  9794. str = write_expr_to_string(str, se->expr, shorthand);
  9795. str = gb_string_appendc(str, "(");
  9796. ast_node(ce, CallExpr, se->call);
  9797. isize start = se->modified_call ? 1 : 0;
  9798. for (isize i = start; i < ce->args.count; i++) {
  9799. Ast *arg = ce->args[i];
  9800. if (i > start) {
  9801. str = gb_string_appendc(str, ", ");
  9802. }
  9803. str = write_expr_to_string(str, arg, shorthand);
  9804. }
  9805. str = gb_string_appendc(str, ")");
  9806. case_end;
  9807. case_ast_node(ta, TypeAssertion, node);
  9808. str = write_expr_to_string(str, ta->expr, shorthand);
  9809. if (ta->type != nullptr &&
  9810. ta->type->kind == Ast_UnaryExpr &&
  9811. ta->type->UnaryExpr.op.kind == Token_Question) {
  9812. str = gb_string_appendc(str, ".?");
  9813. } else {
  9814. str = gb_string_appendc(str, ".(");
  9815. str = write_expr_to_string(str, ta->type, shorthand);
  9816. str = gb_string_append_rune(str, ')');
  9817. }
  9818. case_end;
  9819. case_ast_node(tc, TypeCast, node);
  9820. str = string_append_token(str, tc->token);
  9821. str = gb_string_append_rune(str, '(');
  9822. str = write_expr_to_string(str, tc->type, shorthand);
  9823. str = gb_string_append_rune(str, ')');
  9824. str = write_expr_to_string(str, tc->expr, shorthand);
  9825. case_end;
  9826. case_ast_node(ac, AutoCast, node);
  9827. str = string_append_token(str, ac->token);
  9828. str = gb_string_append_rune(str, ' ');
  9829. str = write_expr_to_string(str, ac->expr, shorthand);
  9830. case_end;
  9831. case_ast_node(ie, IndexExpr, node);
  9832. str = write_expr_to_string(str, ie->expr, shorthand);
  9833. str = gb_string_append_rune(str, '[');
  9834. str = write_expr_to_string(str, ie->index, shorthand);
  9835. str = gb_string_append_rune(str, ']');
  9836. case_end;
  9837. case_ast_node(se, SliceExpr, node);
  9838. str = write_expr_to_string(str, se->expr, shorthand);
  9839. str = gb_string_append_rune(str, '[');
  9840. str = write_expr_to_string(str, se->low, shorthand);
  9841. str = string_append_token(str, se->interval);
  9842. str = write_expr_to_string(str, se->high, shorthand);
  9843. str = gb_string_append_rune(str, ']');
  9844. case_end;
  9845. case_ast_node(mie, MatrixIndexExpr, node);
  9846. str = write_expr_to_string(str, mie->expr, shorthand);
  9847. str = gb_string_append_rune(str, '[');
  9848. str = write_expr_to_string(str, mie->row_index, shorthand);
  9849. str = gb_string_appendc(str, ", ");
  9850. str = write_expr_to_string(str, mie->column_index, shorthand);
  9851. str = gb_string_append_rune(str, ']');
  9852. case_end;
  9853. case_ast_node(e, Ellipsis, node);
  9854. str = gb_string_appendc(str, "..");
  9855. str = write_expr_to_string(str, e->expr, shorthand);
  9856. case_end;
  9857. case_ast_node(fv, FieldValue, node);
  9858. str = write_expr_to_string(str, fv->field, shorthand);
  9859. str = gb_string_appendc(str, " = ");
  9860. str = write_expr_to_string(str, fv->value, shorthand);
  9861. case_end;
  9862. case_ast_node(fv, EnumFieldValue, node);
  9863. str = write_expr_to_string(str, fv->name, shorthand);
  9864. if (fv->value) {
  9865. str = gb_string_appendc(str, " = ");
  9866. str = write_expr_to_string(str, fv->value, shorthand);
  9867. }
  9868. case_end;
  9869. case_ast_node(ht, HelperType, node);
  9870. str = gb_string_appendc(str, "#type ");
  9871. str = write_expr_to_string(str, ht->type, shorthand);
  9872. case_end;
  9873. case_ast_node(ht, DistinctType, node);
  9874. str = gb_string_appendc(str, "distinct ");
  9875. str = write_expr_to_string(str, ht->type, shorthand);
  9876. case_end;
  9877. case_ast_node(pt, PolyType, node);
  9878. str = gb_string_append_rune(str, '$');
  9879. str = write_expr_to_string(str, pt->type, shorthand);
  9880. if (pt->specialization != nullptr) {
  9881. str = gb_string_append_rune(str, '/');
  9882. str = write_expr_to_string(str, pt->specialization, shorthand);
  9883. }
  9884. case_end;
  9885. case_ast_node(pt, PointerType, node);
  9886. str = gb_string_append_rune(str, '^');
  9887. str = write_expr_to_string(str, pt->type, shorthand);
  9888. case_end;
  9889. case_ast_node(pt, MultiPointerType, node);
  9890. str = gb_string_appendc(str, "[^]");
  9891. str = write_expr_to_string(str, pt->type, shorthand);
  9892. case_end;
  9893. case_ast_node(at, ArrayType, node);
  9894. str = gb_string_append_rune(str, '[');
  9895. if (at->count != nullptr &&
  9896. at->count->kind == Ast_UnaryExpr &&
  9897. at->count->UnaryExpr.op.kind == Token_Question) {
  9898. str = gb_string_appendc(str, "?");
  9899. } else {
  9900. str = write_expr_to_string(str, at->count, shorthand);
  9901. }
  9902. str = gb_string_append_rune(str, ']');
  9903. str = write_expr_to_string(str, at->elem, shorthand);
  9904. case_end;
  9905. case_ast_node(at, DynamicArrayType, node);
  9906. str = gb_string_appendc(str, "[dynamic]");
  9907. str = write_expr_to_string(str, at->elem, shorthand);
  9908. case_end;
  9909. case_ast_node(bs, BitSetType, node);
  9910. str = gb_string_appendc(str, "bit_set[");
  9911. str = write_expr_to_string(str, bs->elem, shorthand);
  9912. str = gb_string_appendc(str, "]");
  9913. case_end;
  9914. case_ast_node(mt, MapType, node);
  9915. str = gb_string_appendc(str, "map[");
  9916. str = write_expr_to_string(str, mt->key, shorthand);
  9917. str = gb_string_append_rune(str, ']');
  9918. str = write_expr_to_string(str, mt->value, shorthand);
  9919. case_end;
  9920. case_ast_node(mt, MatrixType, node);
  9921. str = gb_string_appendc(str, "matrix[");
  9922. str = write_expr_to_string(str, mt->row_count, shorthand);
  9923. str = gb_string_appendc(str, ", ");
  9924. str = write_expr_to_string(str, mt->column_count, shorthand);
  9925. str = gb_string_append_rune(str, ']');
  9926. str = write_expr_to_string(str, mt->elem, shorthand);
  9927. case_end;
  9928. case_ast_node(f, Field, node);
  9929. if (f->flags&FieldFlag_using) {
  9930. str = gb_string_appendc(str, "using ");
  9931. }
  9932. if (f->flags&FieldFlag_no_alias) {
  9933. str = gb_string_appendc(str, "#no_alias ");
  9934. }
  9935. if (f->flags&FieldFlag_c_vararg) {
  9936. str = gb_string_appendc(str, "#c_vararg ");
  9937. }
  9938. if (f->flags&FieldFlag_any_int) {
  9939. str = gb_string_appendc(str, "#any_int ");
  9940. }
  9941. if (f->flags&FieldFlag_no_broadcast) {
  9942. str = gb_string_appendc(str, "#no_broadcast ");
  9943. }
  9944. if (f->flags&FieldFlag_const) {
  9945. str = gb_string_appendc(str, "#const ");
  9946. }
  9947. if (f->flags&FieldFlag_subtype) {
  9948. str = gb_string_appendc(str, "#subtype ");
  9949. }
  9950. for_array(i, f->names) {
  9951. Ast *name = f->names[i];
  9952. if (i > 0) str = gb_string_appendc(str, ", ");
  9953. str = write_expr_to_string(str, name, shorthand);
  9954. }
  9955. if (f->names.count > 0) {
  9956. if (f->type == nullptr && f->default_value != nullptr) {
  9957. str = gb_string_append_rune(str, ' ');
  9958. }
  9959. str = gb_string_appendc(str, ":");
  9960. }
  9961. if (f->type != nullptr) {
  9962. str = gb_string_append_rune(str, ' ');
  9963. str = write_expr_to_string(str, f->type, shorthand);
  9964. }
  9965. if (f->default_value != nullptr) {
  9966. if (f->type != nullptr) {
  9967. str = gb_string_append_rune(str, ' ');
  9968. }
  9969. str = gb_string_appendc(str, "= ");
  9970. str = write_expr_to_string(str, f->default_value, shorthand);
  9971. }
  9972. case_end;
  9973. case_ast_node(f, FieldList, node);
  9974. bool has_name = false;
  9975. for_array(i, f->list) {
  9976. ast_node(field, Field, f->list[i]);
  9977. if (field->names.count > 1) {
  9978. has_name = true;
  9979. break;
  9980. }
  9981. if (field->names.count == 0) {
  9982. continue;
  9983. }
  9984. if (!is_blank_ident(field->names[0])) {
  9985. has_name = true;
  9986. break;
  9987. }
  9988. }
  9989. for_array(i, f->list) {
  9990. if (i > 0) str = gb_string_appendc(str, ", ");
  9991. if (has_name) {
  9992. str = write_expr_to_string(str, f->list[i], shorthand);
  9993. } else {
  9994. ast_node(field, Field, f->list[i]);
  9995. if (field->flags&FieldFlag_using) {
  9996. str = gb_string_appendc(str, "using ");
  9997. }
  9998. if (field->flags&FieldFlag_no_alias) {
  9999. str = gb_string_appendc(str, "#no_alias ");
  10000. }
  10001. if (field->flags&FieldFlag_c_vararg) {
  10002. str = gb_string_appendc(str, "#c_vararg ");
  10003. }
  10004. if (field->flags&FieldFlag_any_int) {
  10005. str = gb_string_appendc(str, "#any_int ");
  10006. }
  10007. if (field->flags&FieldFlag_no_broadcast) {
  10008. str = gb_string_appendc(str, "#no_broadcast ");
  10009. }
  10010. if (field->flags&FieldFlag_const) {
  10011. str = gb_string_appendc(str, "#const ");
  10012. }
  10013. if (field->flags&FieldFlag_subtype) {
  10014. str = gb_string_appendc(str, "#subtype ");
  10015. }
  10016. str = write_expr_to_string(str, field->type, shorthand);
  10017. }
  10018. }
  10019. case_end;
  10020. case_ast_node(ce, CallExpr, node);
  10021. switch (ce->inlining) {
  10022. case ProcInlining_inline:
  10023. str = gb_string_appendc(str, "#force_inline ");
  10024. break;
  10025. case ProcInlining_no_inline:
  10026. str = gb_string_appendc(str, "#force_no_inline ");
  10027. break;
  10028. }
  10029. str = write_expr_to_string(str, ce->proc, shorthand);
  10030. str = gb_string_appendc(str, "(");
  10031. isize idx0 = cast(isize)ce->was_selector;
  10032. for (isize i = idx0; i < ce->args.count; i++) {
  10033. Ast *arg = ce->args[i];
  10034. if (i > idx0) {
  10035. str = gb_string_appendc(str, ", ");
  10036. }
  10037. str = write_expr_to_string(str, arg, shorthand);
  10038. }
  10039. str = gb_string_appendc(str, ")");
  10040. case_end;
  10041. case_ast_node(tt, TypeidType, node);
  10042. str = gb_string_appendc(str, "typeid");
  10043. if (tt->specialization) {
  10044. str = gb_string_appendc(str, "/");
  10045. str = write_expr_to_string(str, tt->specialization, shorthand);
  10046. }
  10047. case_end;
  10048. case_ast_node(pt, ProcType, node);
  10049. str = gb_string_appendc(str, "proc(");
  10050. str = write_expr_to_string(str, pt->params, shorthand);
  10051. str = gb_string_appendc(str, ")");
  10052. if (pt->results != nullptr) {
  10053. str = gb_string_appendc(str, " -> ");
  10054. bool parens_needed = false;
  10055. if (pt->results && pt->results->kind == Ast_FieldList) {
  10056. for (Ast *field : pt->results->FieldList.list) {
  10057. ast_node(f, Field, field);
  10058. if (f->names.count != 0) {
  10059. parens_needed = true;
  10060. break;
  10061. }
  10062. }
  10063. }
  10064. if (parens_needed) {
  10065. str = gb_string_append_rune(str, '(');
  10066. }
  10067. str = write_expr_to_string(str, pt->results, shorthand);
  10068. if (parens_needed) {
  10069. str = gb_string_append_rune(str, ')');
  10070. }
  10071. }
  10072. case_end;
  10073. case_ast_node(st, StructType, node);
  10074. str = gb_string_appendc(str, "struct ");
  10075. if (st->polymorphic_params) {
  10076. str = gb_string_append_rune(str, '(');
  10077. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10078. str = gb_string_appendc(str, ") ");
  10079. }
  10080. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10081. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10082. if (st->align) {
  10083. str = gb_string_appendc(str, "#align ");
  10084. str = write_expr_to_string(str, st->align, shorthand);
  10085. str = gb_string_append_rune(str, ' ');
  10086. }
  10087. str = gb_string_append_rune(str, '{');
  10088. if (shorthand) {
  10089. str = gb_string_appendc(str, "...");
  10090. } else {
  10091. str = write_struct_fields_to_string(str, st->fields);
  10092. }
  10093. str = gb_string_append_rune(str, '}');
  10094. case_end;
  10095. case_ast_node(st, UnionType, node);
  10096. str = gb_string_appendc(str, "union ");
  10097. if (st->polymorphic_params) {
  10098. str = gb_string_append_rune(str, '(');
  10099. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10100. str = gb_string_appendc(str, ") ");
  10101. }
  10102. switch (st->kind) {
  10103. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10104. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10105. }
  10106. if (st->align) {
  10107. str = gb_string_appendc(str, "#align ");
  10108. str = write_expr_to_string(str, st->align, shorthand);
  10109. str = gb_string_append_rune(str, ' ');
  10110. }
  10111. str = gb_string_append_rune(str, '{');
  10112. if (shorthand) {
  10113. str = gb_string_appendc(str, "...");
  10114. } else {
  10115. str = write_struct_fields_to_string(str, st->variants);
  10116. }
  10117. str = gb_string_append_rune(str, '}');
  10118. case_end;
  10119. case_ast_node(et, EnumType, node);
  10120. str = gb_string_appendc(str, "enum ");
  10121. if (et->base_type != nullptr) {
  10122. str = write_expr_to_string(str, et->base_type, shorthand);
  10123. str = gb_string_append_rune(str, ' ');
  10124. }
  10125. str = gb_string_append_rune(str, '{');
  10126. if (shorthand) {
  10127. str = gb_string_appendc(str, "...");
  10128. } else {
  10129. for_array(i, et->fields) {
  10130. if (i > 0) {
  10131. str = gb_string_appendc(str, ", ");
  10132. }
  10133. str = write_expr_to_string(str, et->fields[i], shorthand);
  10134. }
  10135. }
  10136. str = gb_string_append_rune(str, '}');
  10137. case_end;
  10138. case_ast_node(rt, RelativeType, node);
  10139. str = write_expr_to_string(str, rt->tag, shorthand);
  10140. str = gb_string_appendc(str, "" );
  10141. str = write_expr_to_string(str, rt->type, shorthand);
  10142. case_end;
  10143. case_ast_node(f, BitFieldField, node);
  10144. str = write_expr_to_string(str, f->name, shorthand);
  10145. str = gb_string_appendc(str, ": ");
  10146. str = write_expr_to_string(str, f->type, shorthand);
  10147. str = gb_string_appendc(str, " | ");
  10148. str = write_expr_to_string(str, f->bit_size, shorthand);
  10149. case_end;
  10150. case_ast_node(bf, BitFieldType, node);
  10151. str = gb_string_appendc(str, "bit_field ");
  10152. if (!shorthand) {
  10153. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10154. }
  10155. str = gb_string_appendc(str, " {");
  10156. if (shorthand) {
  10157. str = gb_string_appendc(str, "...");
  10158. } else {
  10159. for_array(i, bf->fields) {
  10160. if (i > 0) {
  10161. str = gb_string_appendc(str, ", ");
  10162. }
  10163. str = write_expr_to_string(str, bf->fields[i], false);
  10164. }
  10165. }
  10166. str = gb_string_appendc(str, "}");
  10167. case_end;
  10168. case_ast_node(ia, InlineAsmExpr, node);
  10169. str = gb_string_appendc(str, "asm(");
  10170. for_array(i, ia->param_types) {
  10171. if (i > 0) {
  10172. str = gb_string_appendc(str, ", ");
  10173. }
  10174. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10175. }
  10176. str = gb_string_appendc(str, ")");
  10177. if (ia->return_type != nullptr) {
  10178. str = gb_string_appendc(str, " -> ");
  10179. str = write_expr_to_string(str, ia->return_type, shorthand);
  10180. }
  10181. if (ia->has_side_effects) {
  10182. str = gb_string_appendc(str, " #side_effects");
  10183. }
  10184. if (ia->is_align_stack) {
  10185. str = gb_string_appendc(str, " #stack_align");
  10186. }
  10187. if (ia->dialect) {
  10188. str = gb_string_appendc(str, " #");
  10189. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10190. }
  10191. str = gb_string_appendc(str, " {");
  10192. if (shorthand) {
  10193. str = gb_string_appendc(str, "...");
  10194. } else {
  10195. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10196. str = gb_string_appendc(str, ", ");
  10197. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10198. }
  10199. str = gb_string_appendc(str, "}");
  10200. case_end;
  10201. }
  10202. return str;
  10203. }
  10204. gb_internal gbString expr_to_string(Ast *expression) {
  10205. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10206. }
  10207. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10208. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10209. }
  10210. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10211. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10212. }